printers.py 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  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 select
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  10. from backend.app.core.config import settings
  11. from backend.app.core.database import get_db
  12. from backend.app.core.permissions import Permission
  13. from backend.app.models.printer import Printer
  14. from backend.app.models.slot_preset import SlotPresetMapping
  15. from backend.app.schemas.printer import (
  16. AMSTray,
  17. AMSUnit,
  18. HMSErrorResponse,
  19. NozzleInfoResponse,
  20. NozzleRackSlot,
  21. PrinterCreate,
  22. PrinterResponse,
  23. PrinterStatus,
  24. PrinterUpdate,
  25. PrintOptionsResponse,
  26. )
  27. from backend.app.services.bambu_ftp import (
  28. delete_file_async,
  29. download_file_bytes_async,
  30. download_file_try_paths_async,
  31. get_storage_info_async,
  32. list_files_async,
  33. )
  34. from backend.app.services.printer_manager import get_derived_status_name, printer_manager, supports_chamber_temp
  35. logger = logging.getLogger(__name__)
  36. router = APIRouter(prefix="/printers", tags=["printers"])
  37. @router.get("/", response_model=list[PrinterResponse])
  38. async def list_printers(
  39. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  40. db: AsyncSession = Depends(get_db),
  41. ):
  42. """List all configured printers."""
  43. result = await db.execute(select(Printer).order_by(Printer.name))
  44. return list(result.scalars().all())
  45. @router.post("/", response_model=PrinterResponse)
  46. async def create_printer(
  47. printer_data: PrinterCreate,
  48. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CREATE),
  49. db: AsyncSession = Depends(get_db),
  50. ):
  51. """Add a new printer."""
  52. # Check if serial number already exists
  53. result = await db.execute(select(Printer).where(Printer.serial_number == printer_data.serial_number))
  54. if result.scalar_one_or_none():
  55. raise HTTPException(400, "Printer with this serial number already exists")
  56. printer = Printer(**printer_data.model_dump())
  57. db.add(printer)
  58. await db.commit()
  59. await db.refresh(printer)
  60. # Connect to the printer
  61. if printer.is_active:
  62. await printer_manager.connect_printer(printer)
  63. return printer
  64. @router.get("/usb-cameras")
  65. async def list_usb_cameras(
  66. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  67. ):
  68. """List available USB cameras connected to the system.
  69. Returns a list of detected V4L2 video devices with their info.
  70. Only works on Linux systems with V4L2 support.
  71. Returns:
  72. List of dicts with {device: str, name: str, capabilities: list, formats?: list}
  73. """
  74. from backend.app.services.external_camera import list_usb_cameras
  75. cameras = list_usb_cameras()
  76. return {"cameras": cameras}
  77. @router.get("/developer-mode-warnings")
  78. async def get_developer_mode_warnings(
  79. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  80. db: AsyncSession = Depends(get_db),
  81. ):
  82. """Check if any connected printer lacks developer LAN mode."""
  83. result = await db.execute(select(Printer).where(Printer.is_active == True)) # noqa: E712
  84. printers = result.scalars().all()
  85. statuses = printer_manager.get_all_statuses()
  86. warnings = []
  87. for printer in printers:
  88. state = statuses.get(printer.id)
  89. if state and state.connected and state.developer_mode is False:
  90. warnings.append(
  91. {
  92. "printer_id": printer.id,
  93. "name": printer.name,
  94. }
  95. )
  96. return warnings
  97. @router.get("/{printer_id}", response_model=PrinterResponse)
  98. async def get_printer(
  99. printer_id: int,
  100. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  101. db: AsyncSession = Depends(get_db),
  102. ):
  103. """Get a specific printer."""
  104. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  105. printer = result.scalar_one_or_none()
  106. if not printer:
  107. raise HTTPException(404, "Printer not found")
  108. return printer
  109. @router.patch("/{printer_id}", response_model=PrinterResponse)
  110. async def update_printer(
  111. printer_id: int,
  112. printer_data: PrinterUpdate,
  113. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  114. db: AsyncSession = Depends(get_db),
  115. ):
  116. """Update a printer."""
  117. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  118. printer = result.scalar_one_or_none()
  119. if not printer:
  120. raise HTTPException(404, "Printer not found")
  121. update_data = printer_data.model_dump(exclude_unset=True)
  122. # Handle nested ROI object - flatten to individual columns
  123. if "plate_detection_roi" in update_data:
  124. roi = update_data.pop("plate_detection_roi")
  125. if roi:
  126. update_data["plate_detection_roi_x"] = roi.get("x")
  127. update_data["plate_detection_roi_y"] = roi.get("y")
  128. update_data["plate_detection_roi_w"] = roi.get("w")
  129. update_data["plate_detection_roi_h"] = roi.get("h")
  130. else:
  131. # Clear ROI if set to null
  132. update_data["plate_detection_roi_x"] = None
  133. update_data["plate_detection_roi_y"] = None
  134. update_data["plate_detection_roi_w"] = None
  135. update_data["plate_detection_roi_h"] = None
  136. for field, value in update_data.items():
  137. setattr(printer, field, value)
  138. await db.commit()
  139. await db.refresh(printer)
  140. # Reconnect if connection settings changed
  141. if any(k in update_data for k in ["ip_address", "access_code", "is_active"]):
  142. printer_manager.disconnect_printer(printer_id)
  143. if printer.is_active:
  144. await printer_manager.connect_printer(printer)
  145. return printer
  146. @router.delete("/{printer_id}")
  147. async def delete_printer(
  148. printer_id: int,
  149. delete_archives: bool = True,
  150. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_DELETE),
  151. db: AsyncSession = Depends(get_db),
  152. ):
  153. """Delete a printer.
  154. Args:
  155. printer_id: ID of the printer to delete
  156. delete_archives: If True (default), delete all print archives for this printer.
  157. If False, keep archives but remove their printer association.
  158. """
  159. from sqlalchemy import delete as sql_delete
  160. from backend.app.models.archive import PrintArchive
  161. from backend.app.models.maintenance import MaintenanceHistory, PrinterMaintenance
  162. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  163. printer = result.scalar_one_or_none()
  164. if not printer:
  165. raise HTTPException(404, "Printer not found")
  166. printer_manager.disconnect_printer(printer_id)
  167. if delete_archives:
  168. # Delete all archives for this printer
  169. await db.execute(sql_delete(PrintArchive).where(PrintArchive.printer_id == printer_id))
  170. else:
  171. # Orphan the archives instead of deleting them
  172. from sqlalchemy import update
  173. await db.execute(update(PrintArchive).where(PrintArchive.printer_id == printer_id).values(printer_id=None))
  174. # Delete maintenance history and items for this printer
  175. # (SQLite doesn't enforce FK cascades, so do it explicitly)
  176. maintenance_ids = (
  177. (await db.execute(select(PrinterMaintenance.id).where(PrinterMaintenance.printer_id == printer_id)))
  178. .scalars()
  179. .all()
  180. )
  181. if maintenance_ids:
  182. await db.execute(
  183. sql_delete(MaintenanceHistory).where(MaintenanceHistory.printer_maintenance_id.in_(maintenance_ids))
  184. )
  185. await db.execute(sql_delete(PrinterMaintenance).where(PrinterMaintenance.printer_id == printer_id))
  186. await db.delete(printer)
  187. await db.commit()
  188. return {"status": "deleted", "archives_deleted": delete_archives}
  189. @router.get("/{printer_id}/status", response_model=PrinterStatus)
  190. async def get_printer_status(
  191. printer_id: int,
  192. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  193. db: AsyncSession = Depends(get_db),
  194. ):
  195. """Get real-time status of a printer."""
  196. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  197. printer = result.scalar_one_or_none()
  198. if not printer:
  199. raise HTTPException(404, "Printer not found")
  200. state = printer_manager.get_status(printer_id)
  201. if not state:
  202. return PrinterStatus(
  203. id=printer_id,
  204. name=printer.name,
  205. connected=False,
  206. )
  207. # Determine cover URL if there's an active print (including paused)
  208. cover_url = None
  209. if state.state in ("RUNNING", "PAUSE") and state.gcode_file:
  210. cover_url = f"/api/v1/printers/{printer_id}/cover"
  211. # Convert HMS errors to response format
  212. hms_errors = [
  213. HMSErrorResponse(code=e.code, attr=e.attr, module=e.module, severity=e.severity)
  214. for e in (state.hms_errors or [])
  215. ]
  216. # Parse AMS data from raw_data
  217. ams_units = []
  218. vt_tray = []
  219. ams_exists = False
  220. raw_data = state.raw_data or {}
  221. # Build K-profile lookup map: cali_idx -> k_value
  222. # This allows looking up the calibrated K value for each AMS slot
  223. kprofile_map: dict[int, float] = {}
  224. for kp in state.kprofiles or []:
  225. if kp.slot_id is not None and kp.k_value:
  226. try:
  227. kprofile_map[kp.slot_id] = float(kp.k_value)
  228. except (ValueError, TypeError):
  229. pass # Skip K-profile entries with unparseable values
  230. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  231. ams_exists = True
  232. for ams_data in raw_data["ams"]:
  233. # Skip if ams_data is not a dict (defensive check)
  234. if not isinstance(ams_data, dict):
  235. continue
  236. trays = []
  237. for tray_data in ams_data.get("tray", []):
  238. # Filter out empty/invalid tag values
  239. tag_uid = tray_data.get("tag_uid", "")
  240. if tag_uid in ("", "0000000000000000"):
  241. tag_uid = None
  242. tray_uuid = tray_data.get("tray_uuid", "")
  243. if tray_uuid in ("", "00000000000000000000000000000000"):
  244. tray_uuid = None
  245. # Get K value: first try tray's k field, then lookup from K-profiles
  246. k_value = tray_data.get("k")
  247. cali_idx = tray_data.get("cali_idx")
  248. if k_value is None and cali_idx is not None and cali_idx in kprofile_map:
  249. k_value = kprofile_map[cali_idx]
  250. trays.append(
  251. AMSTray(
  252. id=tray_data.get("id", 0),
  253. tray_color=tray_data.get("tray_color"),
  254. tray_type=tray_data.get("tray_type"),
  255. tray_sub_brands=tray_data.get("tray_sub_brands"),
  256. tray_id_name=tray_data.get("tray_id_name"),
  257. tray_info_idx=tray_data.get("tray_info_idx"),
  258. remain=tray_data.get("remain", 0),
  259. k=k_value,
  260. cali_idx=cali_idx,
  261. tag_uid=tag_uid,
  262. tray_uuid=tray_uuid,
  263. nozzle_temp_min=tray_data.get("nozzle_temp_min"),
  264. nozzle_temp_max=tray_data.get("nozzle_temp_max"),
  265. )
  266. )
  267. # Prefer humidity_raw (percentage) over humidity (index 1-5)
  268. # humidity_raw is the actual percentage value from the sensor
  269. humidity_raw = ams_data.get("humidity_raw")
  270. humidity_idx = ams_data.get("humidity")
  271. humidity_value = None
  272. if humidity_raw is not None:
  273. try:
  274. humidity_value = int(humidity_raw)
  275. except (ValueError, TypeError):
  276. pass # Skip unparseable humidity; will try index fallback
  277. if humidity_value is None and humidity_idx is not None:
  278. try:
  279. humidity_value = int(humidity_idx)
  280. except (ValueError, TypeError):
  281. pass # Skip unparseable humidity index; humidity remains None
  282. # AMS-HT has 1 tray, regular AMS has 4 trays
  283. is_ams_ht = len(trays) == 1
  284. ams_units.append(
  285. AMSUnit(
  286. id=ams_data.get("id", 0),
  287. humidity=humidity_value,
  288. temp=ams_data.get("temp"),
  289. is_ams_ht=is_ams_ht,
  290. tray=trays,
  291. )
  292. )
  293. # Virtual tray (external spool holder) - comes from vt_tray in raw_data (list)
  294. if "vt_tray" in raw_data:
  295. for vt_data in raw_data["vt_tray"]:
  296. # Filter out empty/invalid tag values for vt_tray
  297. vt_tag_uid = vt_data.get("tag_uid", "")
  298. if vt_tag_uid in ("", "0000000000000000"):
  299. vt_tag_uid = None
  300. vt_tray_uuid = vt_data.get("tray_uuid", "")
  301. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  302. vt_tray_uuid = None
  303. # Get K value: first try tray's k field, then lookup from K-profiles
  304. vt_k_value = vt_data.get("k")
  305. vt_cali_idx = vt_data.get("cali_idx")
  306. if vt_k_value is None and vt_cali_idx is not None and vt_cali_idx in kprofile_map:
  307. vt_k_value = kprofile_map[vt_cali_idx]
  308. tray_id = int(vt_data.get("id", 254))
  309. vt_tray.append(
  310. AMSTray(
  311. id=tray_id,
  312. tray_color=vt_data.get("tray_color"),
  313. tray_type=vt_data.get("tray_type"),
  314. tray_sub_brands=vt_data.get("tray_sub_brands"),
  315. tray_id_name=vt_data.get("tray_id_name"),
  316. tray_info_idx=vt_data.get("tray_info_idx"),
  317. remain=vt_data.get("remain", 0),
  318. k=vt_k_value,
  319. cali_idx=vt_cali_idx,
  320. tag_uid=vt_tag_uid,
  321. tray_uuid=vt_tray_uuid,
  322. nozzle_temp_min=vt_data.get("nozzle_temp_min"),
  323. nozzle_temp_max=vt_data.get("nozzle_temp_max"),
  324. )
  325. )
  326. # Convert nozzle info to response format
  327. nozzles = [
  328. NozzleInfoResponse(
  329. nozzle_type=n.nozzle_type,
  330. nozzle_diameter=n.nozzle_diameter,
  331. )
  332. for n in (state.nozzles or [])
  333. ]
  334. # H2C nozzle rack (tool-changer dock positions)
  335. nozzle_rack = [
  336. NozzleRackSlot(
  337. id=n.get("id", 0),
  338. nozzle_type=n.get("type", ""),
  339. nozzle_diameter=n.get("diameter", ""),
  340. wear=n.get("wear"),
  341. stat=n.get("stat"),
  342. max_temp=n.get("max_temp", 0),
  343. serial_number=n.get("serial_number", ""),
  344. filament_color=n.get("filament_color", ""),
  345. filament_id=n.get("filament_id", ""),
  346. filament_type=n.get("filament_type", ""),
  347. )
  348. for n in (state.nozzle_rack or [])
  349. ]
  350. # Convert print options to response format
  351. print_options = PrintOptionsResponse(
  352. spaghetti_detector=state.print_options.spaghetti_detector,
  353. print_halt=state.print_options.print_halt,
  354. halt_print_sensitivity=state.print_options.halt_print_sensitivity,
  355. first_layer_inspector=state.print_options.first_layer_inspector,
  356. printing_monitor=state.print_options.printing_monitor,
  357. buildplate_marker_detector=state.print_options.buildplate_marker_detector,
  358. allow_skip_parts=state.print_options.allow_skip_parts,
  359. nozzle_clumping_detector=state.print_options.nozzle_clumping_detector,
  360. nozzle_clumping_sensitivity=state.print_options.nozzle_clumping_sensitivity,
  361. pileup_detector=state.print_options.pileup_detector,
  362. pileup_sensitivity=state.print_options.pileup_sensitivity,
  363. airprint_detector=state.print_options.airprint_detector,
  364. airprint_sensitivity=state.print_options.airprint_sensitivity,
  365. auto_recovery_step_loss=state.print_options.auto_recovery_step_loss,
  366. filament_tangle_detect=state.print_options.filament_tangle_detect,
  367. )
  368. # Get AMS mapping from raw_data (which AMS is connected to which nozzle)
  369. ams_mapping = raw_data.get("ams_mapping", [])
  370. # Get per-AMS extruder map from state attribute (not raw_data, to avoid race condition
  371. # where raw_data gets replaced during MQTT updates and ams_extruder_map is temporarily missing)
  372. ams_extruder_map = state.ams_extruder_map or {}
  373. logger.debug("API returning ams_mapping: %s, ams_extruder_map: %s", ams_mapping, ams_extruder_map)
  374. # tray_now from MQTT is already a global tray ID: (ams_id * 4) + slot_id
  375. # Per OpenBambuAPI docs: 254 = external spool, 255 = no filament, otherwise global tray ID
  376. # No conversion needed - just use the raw value directly
  377. tray_now = state.tray_now
  378. logger.debug("Using tray_now directly as global ID: %s", tray_now)
  379. # Filter out chamber temp for models that don't have a real sensor
  380. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  381. temperatures = state.temperatures
  382. if not supports_chamber_temp(printer.model):
  383. temperatures = {
  384. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  385. }
  386. return PrinterStatus(
  387. id=printer_id,
  388. name=printer.name,
  389. connected=state.connected,
  390. state=state.state,
  391. current_print=state.current_print,
  392. subtask_name=state.subtask_name,
  393. gcode_file=state.gcode_file,
  394. progress=state.progress,
  395. remaining_time=state.remaining_time,
  396. layer_num=state.layer_num,
  397. total_layers=state.total_layers,
  398. temperatures=temperatures,
  399. cover_url=cover_url,
  400. hms_errors=hms_errors,
  401. ams=ams_units,
  402. ams_exists=ams_exists,
  403. vt_tray=vt_tray,
  404. sdcard=state.sdcard,
  405. store_to_sdcard=state.store_to_sdcard,
  406. timelapse=state.timelapse,
  407. ipcam=state.ipcam,
  408. wifi_signal=state.wifi_signal,
  409. nozzles=nozzles,
  410. nozzle_rack=nozzle_rack,
  411. print_options=print_options,
  412. stg_cur=state.stg_cur,
  413. stg_cur_name=get_derived_status_name(state, printer.model),
  414. stg=state.stg,
  415. airduct_mode=state.airduct_mode,
  416. speed_level=state.speed_level,
  417. chamber_light=state.chamber_light,
  418. active_extruder=state.active_extruder,
  419. ams_mapping=ams_mapping,
  420. ams_extruder_map=ams_extruder_map,
  421. tray_now=tray_now,
  422. ams_status_main=state.ams_status_main,
  423. ams_status_sub=state.ams_status_sub,
  424. mc_print_sub_stage=state.mc_print_sub_stage,
  425. last_ams_update=state.last_ams_update,
  426. printable_objects_count=len(state.printable_objects),
  427. cooling_fan_speed=state.cooling_fan_speed,
  428. big_fan1_speed=state.big_fan1_speed,
  429. big_fan2_speed=state.big_fan2_speed,
  430. heatbreak_fan_speed=state.heatbreak_fan_speed,
  431. firmware_version=state.firmware_version,
  432. developer_mode=state.developer_mode if state else None,
  433. plate_cleared=printer_manager.is_plate_cleared(printer_id),
  434. )
  435. @router.get("/{printer_id}/current-print-user")
  436. async def get_current_print_user(
  437. printer_id: int,
  438. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  439. db: AsyncSession = Depends(get_db),
  440. ):
  441. """Get the user who started the current print (for reprint tracking).
  442. Returns user info if available, empty object otherwise.
  443. This tracks users for reprints (which bypass the queue).
  444. For queue-based prints, use the queue item's created_by field instead.
  445. """
  446. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  447. printer = result.scalar_one_or_none()
  448. if not printer:
  449. raise HTTPException(404, "Printer not found")
  450. user_info = printer_manager.get_current_print_user(printer_id)
  451. return user_info or {}
  452. @router.post("/{printer_id}/refresh-status")
  453. async def refresh_printer_status(
  454. printer_id: int,
  455. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  456. db: AsyncSession = Depends(get_db),
  457. ):
  458. """Request a full status refresh from the printer (sends pushall command)."""
  459. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  460. printer = result.scalar_one_or_none()
  461. if not printer:
  462. raise HTTPException(404, "Printer not found")
  463. success = printer_manager.request_status_update(printer_id)
  464. if not success:
  465. raise HTTPException(400, "Printer not connected")
  466. return {"status": "refresh_requested"}
  467. @router.post("/{printer_id}/connect")
  468. async def connect_printer(
  469. printer_id: int,
  470. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  471. db: AsyncSession = Depends(get_db),
  472. ):
  473. """Manually connect to a printer."""
  474. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  475. printer = result.scalar_one_or_none()
  476. if not printer:
  477. raise HTTPException(404, "Printer not found")
  478. success = await printer_manager.connect_printer(printer)
  479. return {"connected": success}
  480. @router.post("/{printer_id}/disconnect")
  481. async def disconnect_printer(
  482. printer_id: int,
  483. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  484. db: AsyncSession = Depends(get_db),
  485. ):
  486. """Manually disconnect from a printer."""
  487. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  488. printer = result.scalar_one_or_none()
  489. if not printer:
  490. raise HTTPException(404, "Printer not found")
  491. printer_manager.disconnect_printer(printer_id)
  492. return {"connected": False}
  493. @router.post("/test")
  494. async def test_printer_connection(
  495. ip_address: str,
  496. serial_number: str,
  497. access_code: str,
  498. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CREATE),
  499. ):
  500. """Test connection to a printer without saving."""
  501. result = await printer_manager.test_connection(
  502. ip_address=ip_address,
  503. serial_number=serial_number,
  504. access_code=access_code,
  505. )
  506. return result
  507. # Cache for cover images (printer_id -> {(subtask_name, plate_num, view) -> image_bytes})
  508. _cover_cache: dict[int, dict[tuple[str, str], bytes]] = {}
  509. def clear_cover_cache(printer_id: int) -> None:
  510. """Clear cached cover images for a printer. Call on print start to avoid stale thumbnails."""
  511. _cover_cache.pop(printer_id, None)
  512. @router.get("/{printer_id}/cover")
  513. async def get_printer_cover(
  514. printer_id: int,
  515. view: str | None = None,
  516. db: AsyncSession = Depends(get_db),
  517. ):
  518. # Note: No auth required - this is an image asset loaded via <img src> which can't send auth headers
  519. """Get the cover image for the current print job.
  520. Args:
  521. view: Optional view type. Use "top" for top-down build plate view (useful for skip objects).
  522. Default returns angled 3D perspective view.
  523. """
  524. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  525. printer = result.scalar_one_or_none()
  526. if not printer:
  527. raise HTTPException(404, "Printer not found")
  528. state = printer_manager.get_status(printer_id)
  529. if not state:
  530. raise HTTPException(404, "Printer not connected")
  531. # Use subtask_name as the 3MF filename (gcode_file is the path inside the 3MF)
  532. subtask_name = state.subtask_name
  533. if not subtask_name:
  534. raise HTTPException(404, f"No subtask_name in printer state (state={state.state})")
  535. # Extract plate number from gcode_file (e.g., "/data/Metadata/plate_12.gcode" -> 12)
  536. plate_num = 1
  537. gcode_file = state.gcode_file
  538. if gcode_file:
  539. match = re.search(r"plate_(\d+)\.gcode", gcode_file)
  540. if match:
  541. plate_num = int(match.group(1))
  542. logger.info("Detected plate number %s from gcode_file: %s", plate_num, gcode_file)
  543. # Normalize view parameter
  544. view_key = view or "default"
  545. # Check cache - include plate_num in cache key for multi-plate projects
  546. if printer_id in _cover_cache:
  547. cache_key = (subtask_name, plate_num, view_key)
  548. if cache_key in _cover_cache[printer_id]:
  549. return Response(content=_cover_cache[printer_id][cache_key], media_type="image/png")
  550. # Build possible 3MF filenames from subtask_name
  551. # Bambu printers may store files as "name.gcode.3mf" (sliced via Bambu Studio)
  552. # or just "name.3mf" (uploaded directly)
  553. possible_filenames = []
  554. if subtask_name.endswith(".3mf"):
  555. possible_filenames.append(subtask_name)
  556. else:
  557. # Try both naming patterns
  558. possible_filenames.append(f"{subtask_name}.gcode.3mf")
  559. possible_filenames.append(f"{subtask_name}.3mf")
  560. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  561. if " " in subtask_name:
  562. normalized = subtask_name.replace(" ", "_")
  563. if normalized.endswith(".3mf"):
  564. possible_filenames.append(normalized)
  565. else:
  566. possible_filenames.append(f"{normalized}.gcode.3mf")
  567. possible_filenames.append(f"{normalized}.3mf")
  568. # Build list of all remote paths to try
  569. remote_paths = []
  570. for filename in possible_filenames:
  571. remote_paths.extend(
  572. [
  573. f"/{filename}", # Root directory (most common)
  574. f"/cache/{filename}",
  575. f"/model/{filename}",
  576. f"/data/{filename}",
  577. ]
  578. )
  579. # Use first filename for temp path (will be reused)
  580. temp_filename = possible_filenames[0]
  581. temp_path = settings.archive_dir / "temp" / f"cover_{printer_id}_{temp_filename}"
  582. temp_path.parent.mkdir(parents=True, exist_ok=True)
  583. logger.info(
  584. f"Trying to download cover for '{subtask_name}' from {printer.ip_address} (trying {len(remote_paths)} paths)"
  585. )
  586. # Retry logic for transient FTP failures
  587. max_retries = 2
  588. last_error = None
  589. downloaded = False
  590. for attempt in range(max_retries + 1):
  591. try:
  592. downloaded = await download_file_try_paths_async(
  593. printer.ip_address,
  594. printer.access_code,
  595. remote_paths,
  596. temp_path,
  597. printer_model=printer.model,
  598. )
  599. if downloaded:
  600. break
  601. except Exception as e:
  602. last_error = e
  603. if attempt < max_retries:
  604. logger.warning("FTP download attempt %s failed: %s, retrying...", attempt + 1, e)
  605. await asyncio.sleep(0.5 * (attempt + 1)) # Brief backoff
  606. else:
  607. logger.error("FTP download failed after %s attempts: %s", max_retries + 1, e)
  608. if last_error and not downloaded:
  609. raise HTTPException(503, f"FTP download temporarily unavailable: {last_error}")
  610. if not downloaded:
  611. raise HTTPException(
  612. 404,
  613. f"Could not download 3MF file for '{subtask_name}' from printer {printer.ip_address}. Tried: {possible_filenames}",
  614. )
  615. # Verify file actually exists and has content
  616. if not temp_path.exists():
  617. raise HTTPException(500, f"Download reported success but file not found: {temp_path}")
  618. file_size = temp_path.stat().st_size
  619. logger.info("Downloaded file size: %s bytes", file_size)
  620. if file_size == 0:
  621. temp_path.unlink()
  622. raise HTTPException(500, f"Downloaded file is empty for '{subtask_name}'")
  623. try:
  624. # Extract thumbnail from 3MF (which is a ZIP file)
  625. try:
  626. zf = zipfile.ZipFile(temp_path, "r")
  627. except zipfile.BadZipFile:
  628. raise HTTPException(500, "Downloaded file is not a valid 3MF/ZIP archive")
  629. except OSError as e:
  630. logger.error("Failed to open 3MF file: %s", e, exc_info=True)
  631. raise HTTPException(500, "Failed to open 3MF file. Check server logs for details.")
  632. try:
  633. # Try common thumbnail paths in 3MF files
  634. # Use plate_num to get the correct plate's thumbnail for multi-plate projects
  635. # Use top-down view if requested (better for skip objects modal)
  636. if view == "top":
  637. thumbnail_paths = [
  638. f"Metadata/top_{plate_num}.png",
  639. # Fall back to plate 1 if specific plate not found
  640. "Metadata/top_1.png",
  641. f"Metadata/plate_{plate_num}.png",
  642. "Metadata/plate_1.png",
  643. "Metadata/thumbnail.png",
  644. ]
  645. else:
  646. thumbnail_paths = [
  647. f"Metadata/plate_{plate_num}.png",
  648. # Fall back to plate 1 if specific plate not found
  649. "Metadata/plate_1.png",
  650. "Metadata/thumbnail.png",
  651. f"Metadata/plate_{plate_num}_small.png",
  652. "Metadata/plate_1_small.png",
  653. "Thumbnails/thumbnail.png",
  654. "thumbnail.png",
  655. ]
  656. for thumb_path in thumbnail_paths:
  657. try:
  658. image_data = zf.read(thumb_path)
  659. # Cache the result - include plate_num in cache key
  660. if printer_id not in _cover_cache:
  661. _cover_cache[printer_id] = {}
  662. _cover_cache[printer_id][(subtask_name, plate_num, view_key)] = image_data
  663. return Response(content=image_data, media_type="image/png")
  664. except KeyError:
  665. continue
  666. # If no specific thumbnail found, try any PNG in Metadata
  667. for name in zf.namelist():
  668. if name.startswith("Metadata/") and name.endswith(".png"):
  669. image_data = zf.read(name)
  670. if printer_id not in _cover_cache:
  671. _cover_cache[printer_id] = {}
  672. _cover_cache[printer_id][(subtask_name, plate_num, view_key)] = image_data
  673. return Response(content=image_data, media_type="image/png")
  674. raise HTTPException(404, "No thumbnail found in 3MF file")
  675. finally:
  676. zf.close()
  677. finally:
  678. if temp_path.exists():
  679. temp_path.unlink()
  680. # ============================================
  681. # File Manager Endpoints
  682. # ============================================
  683. @router.get("/{printer_id}/files")
  684. async def list_printer_files(
  685. printer_id: int,
  686. path: str = "/",
  687. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  688. db: AsyncSession = Depends(get_db),
  689. ):
  690. """List files on the printer at the specified path."""
  691. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  692. printer = result.scalar_one_or_none()
  693. if not printer:
  694. raise HTTPException(404, "Printer not found")
  695. files = await list_files_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  696. # Add full path to each file
  697. for f in files:
  698. f["path"] = f"{path.rstrip('/')}/{f['name']}" if path != "/" else f"/{f['name']}"
  699. return {
  700. "path": path,
  701. "files": files,
  702. }
  703. @router.get("/{printer_id}/files/download")
  704. async def download_printer_file(
  705. printer_id: int,
  706. path: str,
  707. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  708. db: AsyncSession = Depends(get_db),
  709. ):
  710. """Download a file from the printer."""
  711. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  712. printer = result.scalar_one_or_none()
  713. if not printer:
  714. raise HTTPException(404, "Printer not found")
  715. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  716. if data is None:
  717. raise HTTPException(404, f"File not found: {path}")
  718. # Determine content type based on extension
  719. filename = path.split("/")[-1]
  720. ext = filename.lower().split(".")[-1] if "." in filename else ""
  721. content_types = {
  722. "3mf": "application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  723. "gcode": "text/plain",
  724. "mp4": "video/mp4",
  725. "avi": "video/x-msvideo",
  726. "png": "image/png",
  727. "jpg": "image/jpeg",
  728. "jpeg": "image/jpeg",
  729. "json": "application/json",
  730. "txt": "text/plain",
  731. }
  732. content_type = content_types.get(ext, "application/octet-stream")
  733. return Response(
  734. content=data,
  735. media_type=content_type,
  736. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  737. )
  738. @router.get("/{printer_id}/files/gcode")
  739. async def get_printer_file_gcode(
  740. printer_id: int,
  741. path: str,
  742. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  743. db: AsyncSession = Depends(get_db),
  744. ):
  745. """Get gcode for a file stored on a printer (for preview)."""
  746. import io
  747. # Validate printer
  748. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  749. printer = result.scalar_one_or_none()
  750. if not printer:
  751. raise HTTPException(404, "Printer not found")
  752. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  753. if data is None:
  754. raise HTTPException(404, f"File not found: {path}")
  755. filename = path.split("/")[-1]
  756. lower = filename.lower()
  757. if lower.endswith(".gcode"):
  758. return Response(content=data, media_type="text/plain")
  759. if lower.endswith(".3mf"):
  760. try:
  761. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  762. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  763. if not gcode_files:
  764. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  765. gcode_content = zf.read(gcode_files[0])
  766. return Response(content=gcode_content, media_type="text/plain")
  767. except zipfile.BadZipFile:
  768. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  769. raise HTTPException(status_code=400, detail="Unsupported file type")
  770. @router.get("/{printer_id}/files/plates")
  771. async def get_printer_file_plates(
  772. printer_id: int,
  773. path: str = Query(..., description="Full path to the 3MF file on the printer"),
  774. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  775. db: AsyncSession = Depends(get_db),
  776. ):
  777. """Get available plates from a multi-plate 3MF file stored on a printer."""
  778. import io
  779. import json
  780. import defusedxml.ElementTree as ET
  781. # Validate printer
  782. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  783. printer = result.scalar_one_or_none()
  784. if not printer:
  785. raise HTTPException(404, "Printer not found")
  786. filename = path.split("/")[-1]
  787. if not filename.lower().endswith(".3mf"):
  788. return {
  789. "printer_id": printer_id,
  790. "path": path,
  791. "filename": filename,
  792. "plates": [],
  793. "is_multi_plate": False,
  794. }
  795. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  796. if data is None:
  797. raise HTTPException(404, f"File not found: {path}")
  798. plates = []
  799. try:
  800. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  801. namelist = zf.namelist()
  802. # Find all plate gcode files to determine available plates
  803. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  804. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  805. plate_indices: list[int] = []
  806. if gcode_files:
  807. for gf in gcode_files:
  808. try:
  809. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  810. plate_indices.append(int(plate_str))
  811. except ValueError:
  812. pass # Skip gcode files with non-numeric plate indices
  813. else:
  814. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  815. plate_png_files = [
  816. n
  817. for n in namelist
  818. if n.startswith("Metadata/plate_")
  819. and n.endswith(".png")
  820. and "_small" not in n
  821. and "no_light" not in n
  822. ]
  823. plate_name_candidates = plate_json_files + plate_png_files
  824. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  825. seen_indices: set[int] = set()
  826. for name in plate_name_candidates:
  827. match = plate_re.match(name)
  828. if match:
  829. try:
  830. index = int(match.group(1))
  831. except ValueError:
  832. continue
  833. if index in seen_indices:
  834. continue
  835. seen_indices.add(index)
  836. plate_indices.append(index)
  837. if not plate_indices:
  838. return {
  839. "printer_id": printer_id,
  840. "path": path,
  841. "filename": filename,
  842. "plates": [],
  843. "is_multi_plate": False,
  844. }
  845. plate_indices.sort()
  846. # Parse model_settings.config for plate names
  847. plate_names = {}
  848. if "Metadata/model_settings.config" in namelist:
  849. try:
  850. model_content = zf.read("Metadata/model_settings.config").decode()
  851. model_root = ET.fromstring(model_content)
  852. for plate_elem in model_root.findall(".//plate"):
  853. plater_id = None
  854. plater_name = None
  855. for meta in plate_elem.findall("metadata"):
  856. key = meta.get("key")
  857. value = meta.get("value")
  858. if key == "plater_id" and value:
  859. try:
  860. plater_id = int(value)
  861. except ValueError:
  862. pass # Skip plate with unparseable ID
  863. elif key == "plater_name" and value:
  864. plater_name = value.strip()
  865. if plater_id is not None and plater_name:
  866. plate_names[plater_id] = plater_name
  867. except Exception:
  868. pass # Plate names are optional; continue without them
  869. # Parse slice_info.config for plate metadata
  870. plate_metadata = {}
  871. if "Metadata/slice_info.config" in namelist:
  872. content = zf.read("Metadata/slice_info.config").decode()
  873. root = ET.fromstring(content)
  874. for plate_elem in root.findall(".//plate"):
  875. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  876. plate_index = None
  877. for meta in plate_elem.findall("metadata"):
  878. key = meta.get("key")
  879. value = meta.get("value")
  880. if key == "index" and value:
  881. try:
  882. plate_index = int(value)
  883. except ValueError:
  884. pass # Skip plate with unparseable index
  885. elif key == "prediction" and value:
  886. try:
  887. plate_info["prediction"] = int(value)
  888. except ValueError:
  889. pass # Skip unparseable prediction; leave as None
  890. elif key == "weight" and value:
  891. try:
  892. plate_info["weight"] = float(value)
  893. except ValueError:
  894. pass # Skip unparseable weight; leave as None
  895. # Get filaments used in this plate
  896. for filament_elem in plate_elem.findall("filament"):
  897. filament_id = filament_elem.get("id")
  898. filament_type = filament_elem.get("type", "")
  899. filament_color = filament_elem.get("color", "")
  900. used_g = filament_elem.get("used_g", "0")
  901. used_m = filament_elem.get("used_m", "0")
  902. try:
  903. used_grams = float(used_g)
  904. except (ValueError, TypeError):
  905. used_grams = 0
  906. if used_grams > 0 and filament_id:
  907. plate_info["filaments"].append(
  908. {
  909. "slot_id": int(filament_id),
  910. "type": filament_type,
  911. "color": filament_color,
  912. "used_grams": round(used_grams, 1),
  913. "used_meters": float(used_m) if used_m else 0,
  914. }
  915. )
  916. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  917. # Collect object names
  918. for obj_elem in plate_elem.findall("object"):
  919. obj_name = obj_elem.get("name")
  920. if obj_name and obj_name not in plate_info["objects"]:
  921. plate_info["objects"].append(obj_name)
  922. # Set plate name
  923. if plate_index is not None:
  924. custom_name = plate_names.get(plate_index)
  925. if custom_name:
  926. plate_info["name"] = custom_name
  927. elif plate_info["objects"]:
  928. plate_info["name"] = plate_info["objects"][0]
  929. plate_metadata[plate_index] = plate_info
  930. # Parse plate_*.json for object lists when slice_info is missing
  931. plate_json_objects: dict[int, list[str]] = {}
  932. for name in namelist:
  933. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  934. if not match:
  935. continue
  936. try:
  937. plate_index = int(match.group(1))
  938. except ValueError:
  939. continue
  940. try:
  941. payload = json.loads(zf.read(name).decode())
  942. bbox_objects = payload.get("bbox_objects", [])
  943. names: list[str] = []
  944. for obj in bbox_objects:
  945. obj_name = obj.get("name") if isinstance(obj, dict) else None
  946. if obj_name and obj_name not in names:
  947. names.append(obj_name)
  948. if names:
  949. plate_json_objects[plate_index] = names
  950. except Exception:
  951. continue
  952. # Build plate list
  953. for idx in plate_indices:
  954. meta = plate_metadata.get(idx, {})
  955. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  956. objects = meta.get("objects", [])
  957. if not objects:
  958. objects = plate_json_objects.get(idx, [])
  959. plate_name = meta.get("name")
  960. if not plate_name:
  961. plate_name = plate_names.get(idx)
  962. if not plate_name and objects:
  963. plate_name = objects[0]
  964. plates.append(
  965. {
  966. "index": idx,
  967. "name": plate_name,
  968. "objects": objects,
  969. "object_count": len(objects),
  970. "has_thumbnail": has_thumbnail,
  971. "thumbnail_url": f"/api/v1/printers/{printer_id}/files/plate-thumbnail/{idx}?path={path}",
  972. "print_time_seconds": meta.get("prediction"),
  973. "filament_used_grams": meta.get("weight"),
  974. "filaments": meta.get("filaments", []),
  975. }
  976. )
  977. except Exception as e:
  978. logger.warning("Failed to parse plates from printer file %s: %s", path, e)
  979. return {
  980. "printer_id": printer_id,
  981. "path": path,
  982. "filename": filename,
  983. "plates": plates,
  984. "is_multi_plate": len(plates) > 1,
  985. }
  986. @router.get("/{printer_id}/files/plate-thumbnail/{plate_index}")
  987. async def get_printer_file_plate_thumbnail(
  988. printer_id: int,
  989. plate_index: int,
  990. path: str = Query(..., description="Full path to the 3MF file on the printer"),
  991. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  992. db: AsyncSession = Depends(get_db),
  993. ):
  994. """Get a plate thumbnail image from a printer-stored 3MF file."""
  995. import io
  996. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  997. printer = result.scalar_one_or_none()
  998. if not printer:
  999. raise HTTPException(404, "Printer not found")
  1000. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1001. if data is None:
  1002. raise HTTPException(404, f"File not found: {path}")
  1003. try:
  1004. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  1005. thumb_path = f"Metadata/plate_{plate_index}.png"
  1006. if thumb_path in zf.namelist():
  1007. image_data = zf.read(thumb_path)
  1008. return Response(content=image_data, media_type="image/png")
  1009. except Exception:
  1010. pass # Corrupt or unreadable 3MF; fall through to 404
  1011. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  1012. @router.post("/{printer_id}/files/download-zip")
  1013. async def download_printer_files_as_zip(
  1014. printer_id: int,
  1015. request: dict,
  1016. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1017. db: AsyncSession = Depends(get_db),
  1018. ):
  1019. """Download multiple files from the printer as a ZIP archive."""
  1020. import io
  1021. paths = request.get("paths", [])
  1022. if not paths:
  1023. raise HTTPException(400, "No files specified")
  1024. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1025. printer = result.scalar_one_or_none()
  1026. if not printer:
  1027. raise HTTPException(404, "Printer not found")
  1028. # Create ZIP in memory
  1029. zip_buffer = io.BytesIO()
  1030. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  1031. for path in paths:
  1032. try:
  1033. data = await download_file_bytes_async(
  1034. printer.ip_address, printer.access_code, path, printer_model=printer.model
  1035. )
  1036. if data:
  1037. filename = path.split("/")[-1]
  1038. zf.writestr(filename, data)
  1039. except Exception as e:
  1040. logging.warning("Failed to add %s to ZIP: %s", path, e)
  1041. continue
  1042. zip_buffer.seek(0)
  1043. zip_data = zip_buffer.read()
  1044. if len(zip_data) == 0:
  1045. raise HTTPException(404, "No files could be downloaded")
  1046. return Response(
  1047. content=zip_data,
  1048. media_type="application/zip",
  1049. headers={"Content-Disposition": 'attachment; filename="printer-files.zip"'},
  1050. )
  1051. @router.delete("/{printer_id}/files")
  1052. async def delete_printer_file(
  1053. printer_id: int,
  1054. path: str,
  1055. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1056. db: AsyncSession = Depends(get_db),
  1057. ):
  1058. """Delete a file from the printer."""
  1059. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1060. printer = result.scalar_one_or_none()
  1061. if not printer:
  1062. raise HTTPException(404, "Printer not found")
  1063. success = await delete_file_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1064. if not success:
  1065. raise HTTPException(500, f"Failed to delete file: {path}")
  1066. return {"status": "deleted", "path": path}
  1067. @router.get("/{printer_id}/storage")
  1068. async def get_printer_storage(
  1069. printer_id: int,
  1070. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1071. db: AsyncSession = Depends(get_db),
  1072. ):
  1073. """Get storage information from the printer."""
  1074. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1075. printer = result.scalar_one_or_none()
  1076. if not printer:
  1077. raise HTTPException(404, "Printer not found")
  1078. storage_info = await get_storage_info_async(printer.ip_address, printer.access_code, printer_model=printer.model)
  1079. return storage_info or {"used_bytes": None, "free_bytes": None}
  1080. # ============================================
  1081. # MQTT Debug Logging Endpoints
  1082. # ============================================
  1083. @router.post("/{printer_id}/logging/enable")
  1084. async def enable_mqtt_logging(
  1085. printer_id: int,
  1086. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1087. db: AsyncSession = Depends(get_db),
  1088. ):
  1089. """Enable MQTT message logging for a printer."""
  1090. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1091. printer = result.scalar_one_or_none()
  1092. if not printer:
  1093. raise HTTPException(404, "Printer not found")
  1094. success = printer_manager.enable_logging(printer_id, True)
  1095. if not success:
  1096. raise HTTPException(400, "Printer not connected")
  1097. return {"logging_enabled": True}
  1098. @router.post("/{printer_id}/logging/disable")
  1099. async def disable_mqtt_logging(
  1100. printer_id: int,
  1101. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1102. db: AsyncSession = Depends(get_db),
  1103. ):
  1104. """Disable MQTT message logging for a printer."""
  1105. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1106. printer = result.scalar_one_or_none()
  1107. if not printer:
  1108. raise HTTPException(404, "Printer not found")
  1109. success = printer_manager.enable_logging(printer_id, False)
  1110. if not success:
  1111. raise HTTPException(400, "Printer not connected")
  1112. return {"logging_enabled": False}
  1113. @router.get("/{printer_id}/logging")
  1114. async def get_mqtt_logs(
  1115. printer_id: int,
  1116. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1117. db: AsyncSession = Depends(get_db),
  1118. ):
  1119. """Get MQTT message logs for a printer."""
  1120. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1121. printer = result.scalar_one_or_none()
  1122. if not printer:
  1123. raise HTTPException(404, "Printer not found")
  1124. logs = printer_manager.get_logs(printer_id)
  1125. return {
  1126. "logging_enabled": printer_manager.is_logging_enabled(printer_id),
  1127. "logs": [
  1128. {
  1129. "timestamp": log.timestamp,
  1130. "topic": log.topic,
  1131. "direction": log.direction,
  1132. "payload": log.payload,
  1133. }
  1134. for log in logs
  1135. ],
  1136. }
  1137. @router.delete("/{printer_id}/logging")
  1138. async def clear_mqtt_logs(
  1139. printer_id: int,
  1140. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1141. db: AsyncSession = Depends(get_db),
  1142. ):
  1143. """Clear MQTT message logs for a printer."""
  1144. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1145. printer = result.scalar_one_or_none()
  1146. if not printer:
  1147. raise HTTPException(404, "Printer not found")
  1148. printer_manager.clear_logs(printer_id)
  1149. return {"status": "cleared"}
  1150. # ============================================
  1151. # Print Options (AI Detection) Endpoints
  1152. # ============================================
  1153. @router.post("/{printer_id}/print-options")
  1154. async def set_print_option(
  1155. printer_id: int,
  1156. module_name: str,
  1157. enabled: bool,
  1158. print_halt: bool = True,
  1159. sensitivity: str = "medium",
  1160. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1161. db: AsyncSession = Depends(get_db),
  1162. ):
  1163. """Set an AI detection / print option on the printer.
  1164. Valid module_name values:
  1165. - spaghetti_detector: Spaghetti detection
  1166. - first_layer_inspector: First layer inspection
  1167. - printing_monitor: AI print quality monitoring
  1168. - buildplate_marker_detector: Build plate marker detection
  1169. - allow_skip_parts: Allow skipping failed parts
  1170. """
  1171. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1172. printer = result.scalar_one_or_none()
  1173. if not printer:
  1174. raise HTTPException(404, "Printer not found")
  1175. client = printer_manager.get_client(printer_id)
  1176. if not client or not client.state.connected:
  1177. raise HTTPException(400, "Printer not connected")
  1178. # Validate module_name
  1179. valid_modules = [
  1180. "spaghetti_detector",
  1181. "first_layer_inspector",
  1182. "printing_monitor",
  1183. "buildplate_marker_detector",
  1184. "allow_skip_parts",
  1185. "pileup_detector",
  1186. "clump_detector",
  1187. "airprint_detector",
  1188. "auto_recovery_step_loss",
  1189. ]
  1190. if module_name not in valid_modules:
  1191. raise HTTPException(400, f"Invalid module_name. Must be one of: {valid_modules}")
  1192. # Validate sensitivity
  1193. valid_sensitivities = ["low", "medium", "high", "never_halt"]
  1194. if sensitivity not in valid_sensitivities:
  1195. raise HTTPException(400, f"Invalid sensitivity. Must be one of: {valid_sensitivities}")
  1196. success = client.set_xcam_option(
  1197. module_name=module_name,
  1198. enabled=enabled,
  1199. print_halt=print_halt,
  1200. sensitivity=sensitivity,
  1201. )
  1202. if not success:
  1203. raise HTTPException(500, "Failed to send command to printer")
  1204. return {
  1205. "success": True,
  1206. "module_name": module_name,
  1207. "enabled": enabled,
  1208. "print_halt": print_halt,
  1209. "sensitivity": sensitivity,
  1210. }
  1211. # ============================================
  1212. # Calibration
  1213. # ============================================
  1214. @router.post("/{printer_id}/calibration")
  1215. async def start_calibration(
  1216. printer_id: int,
  1217. bed_leveling: bool = False,
  1218. vibration: bool = False,
  1219. motor_noise: bool = False,
  1220. nozzle_offset: bool = False,
  1221. high_temp_heatbed: bool = False,
  1222. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1223. db: AsyncSession = Depends(get_db),
  1224. ):
  1225. """Start printer calibration with selected options.
  1226. At least one option must be selected.
  1227. Options:
  1228. - bed_leveling: Run bed leveling calibration
  1229. - vibration: Run vibration compensation calibration
  1230. - motor_noise: Run motor noise cancellation calibration
  1231. - nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  1232. - high_temp_heatbed: Run high-temperature heatbed calibration
  1233. """
  1234. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1235. printer = result.scalar_one_or_none()
  1236. if not printer:
  1237. raise HTTPException(404, "Printer not found")
  1238. client = printer_manager.get_client(printer_id)
  1239. if not client or not client.state.connected:
  1240. raise HTTPException(400, "Printer not connected")
  1241. # Check that at least one option is selected
  1242. if not any([bed_leveling, vibration, motor_noise, nozzle_offset, high_temp_heatbed]):
  1243. raise HTTPException(400, "At least one calibration option must be selected")
  1244. success = client.start_calibration(
  1245. bed_leveling=bed_leveling,
  1246. vibration=vibration,
  1247. motor_noise=motor_noise,
  1248. nozzle_offset=nozzle_offset,
  1249. high_temp_heatbed=high_temp_heatbed,
  1250. )
  1251. if not success:
  1252. raise HTTPException(500, "Failed to send calibration command to printer")
  1253. return {
  1254. "success": True,
  1255. "bed_leveling": bed_leveling,
  1256. "vibration": vibration,
  1257. "motor_noise": motor_noise,
  1258. "nozzle_offset": nozzle_offset,
  1259. "high_temp_heatbed": high_temp_heatbed,
  1260. }
  1261. # ============================================================================
  1262. # Slot Preset Mapping Endpoints
  1263. # ============================================================================
  1264. @router.get("/{printer_id}/slot-presets")
  1265. async def get_slot_presets(
  1266. printer_id: int,
  1267. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1268. db: AsyncSession = Depends(get_db),
  1269. ):
  1270. """Get all saved slot-to-preset mappings for a printer."""
  1271. result = await db.execute(select(SlotPresetMapping).where(SlotPresetMapping.printer_id == printer_id))
  1272. mappings = result.scalars().all()
  1273. return {
  1274. mapping.ams_id * 4 + mapping.tray_id: {
  1275. "ams_id": mapping.ams_id,
  1276. "tray_id": mapping.tray_id,
  1277. "preset_id": mapping.preset_id,
  1278. "preset_name": mapping.preset_name,
  1279. }
  1280. for mapping in mappings
  1281. }
  1282. @router.get("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  1283. async def get_slot_preset(
  1284. printer_id: int,
  1285. ams_id: int,
  1286. tray_id: int,
  1287. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1288. db: AsyncSession = Depends(get_db),
  1289. ):
  1290. """Get the saved preset for a specific slot."""
  1291. result = await db.execute(
  1292. select(SlotPresetMapping).where(
  1293. SlotPresetMapping.printer_id == printer_id,
  1294. SlotPresetMapping.ams_id == ams_id,
  1295. SlotPresetMapping.tray_id == tray_id,
  1296. )
  1297. )
  1298. mapping = result.scalar_one_or_none()
  1299. if not mapping:
  1300. return None
  1301. return {
  1302. "ams_id": mapping.ams_id,
  1303. "tray_id": mapping.tray_id,
  1304. "preset_id": mapping.preset_id,
  1305. "preset_name": mapping.preset_name,
  1306. }
  1307. @router.put("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  1308. async def save_slot_preset(
  1309. printer_id: int,
  1310. ams_id: int,
  1311. tray_id: int,
  1312. preset_id: str,
  1313. preset_name: str,
  1314. preset_source: str = "cloud",
  1315. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  1316. db: AsyncSession = Depends(get_db),
  1317. ):
  1318. """Save a preset mapping for a specific slot."""
  1319. # Check printer exists
  1320. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1321. if not result.scalar_one_or_none():
  1322. raise HTTPException(404, "Printer not found")
  1323. # Check for existing mapping
  1324. result = await db.execute(
  1325. select(SlotPresetMapping).where(
  1326. SlotPresetMapping.printer_id == printer_id,
  1327. SlotPresetMapping.ams_id == ams_id,
  1328. SlotPresetMapping.tray_id == tray_id,
  1329. )
  1330. )
  1331. mapping = result.scalar_one_or_none()
  1332. if mapping:
  1333. # Update existing
  1334. mapping.preset_id = preset_id
  1335. mapping.preset_name = preset_name
  1336. mapping.preset_source = preset_source
  1337. else:
  1338. # Create new
  1339. mapping = SlotPresetMapping(
  1340. printer_id=printer_id,
  1341. ams_id=ams_id,
  1342. tray_id=tray_id,
  1343. preset_id=preset_id,
  1344. preset_name=preset_name,
  1345. preset_source=preset_source,
  1346. )
  1347. db.add(mapping)
  1348. await db.commit()
  1349. await db.refresh(mapping)
  1350. return {
  1351. "ams_id": mapping.ams_id,
  1352. "tray_id": mapping.tray_id,
  1353. "preset_id": mapping.preset_id,
  1354. "preset_name": mapping.preset_name,
  1355. "preset_source": mapping.preset_source,
  1356. }
  1357. @router.delete("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  1358. async def delete_slot_preset(
  1359. printer_id: int,
  1360. ams_id: int,
  1361. tray_id: int,
  1362. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  1363. db: AsyncSession = Depends(get_db),
  1364. ):
  1365. """Delete a saved preset mapping for a slot."""
  1366. result = await db.execute(
  1367. select(SlotPresetMapping).where(
  1368. SlotPresetMapping.printer_id == printer_id,
  1369. SlotPresetMapping.ams_id == ams_id,
  1370. SlotPresetMapping.tray_id == tray_id,
  1371. )
  1372. )
  1373. mapping = result.scalar_one_or_none()
  1374. if mapping:
  1375. await db.delete(mapping)
  1376. await db.commit()
  1377. return {"success": True}
  1378. @router.post("/{printer_id}/slots/{ams_id}/{tray_id}/configure")
  1379. async def configure_ams_slot(
  1380. printer_id: int,
  1381. ams_id: int,
  1382. tray_id: int,
  1383. tray_info_idx: str = Query(...),
  1384. tray_type: str = Query(...),
  1385. tray_sub_brands: str = Query(...),
  1386. tray_color: str = Query(...),
  1387. nozzle_temp_min: int = Query(...),
  1388. nozzle_temp_max: int = Query(...),
  1389. cali_idx: int = Query(-1),
  1390. nozzle_diameter: str = Query("0.4"),
  1391. setting_id: str = Query(""),
  1392. kprofile_filament_id: str = Query(""),
  1393. kprofile_setting_id: str = Query(""),
  1394. k_value: float = Query(0.0),
  1395. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1396. ):
  1397. """Configure an AMS slot with a specific filament setting and K profile.
  1398. This sends two commands to the printer:
  1399. 1. ams_filament_setting - sets filament type, color, temperature
  1400. 2. extrusion_cali_sel - sets the K profile (pressure advance value)
  1401. Args:
  1402. printer_id: Database ID of the printer
  1403. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  1404. tray_id: Tray ID within the AMS (0-3)
  1405. tray_info_idx: Filament ID short format (e.g., "GFL05") or user preset ID
  1406. tray_type: Filament type (e.g., "PLA", "PETG")
  1407. tray_sub_brands: Sub-brand/profile name (e.g., "PLA Basic", "PETG HF")
  1408. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  1409. nozzle_temp_min: Minimum nozzle temperature
  1410. nozzle_temp_max: Maximum nozzle temperature
  1411. cali_idx: K profile calibration index (-1 for default 0.020)
  1412. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  1413. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  1414. kprofile_filament_id: K profile's filament_id for proper K profile linking
  1415. k_value: Direct K value to set (0.0 to skip direct K value setting)
  1416. """
  1417. logger = logging.getLogger(__name__)
  1418. logger.info("[configure_ams_slot] printer_id=%s, ams_id=%s, tray_id=%s", printer_id, ams_id, tray_id)
  1419. logger.info(
  1420. f"[configure_ams_slot] tray_info_idx={tray_info_idx!r}, tray_type={tray_type!r}, tray_sub_brands={tray_sub_brands!r}"
  1421. )
  1422. logger.info(
  1423. f"[configure_ams_slot] setting_id={setting_id!r}, kprofile_filament_id={kprofile_filament_id!r}, kprofile_setting_id={kprofile_setting_id!r}"
  1424. )
  1425. # Get MQTT client for this printer
  1426. client = printer_manager.get_client(printer_id)
  1427. if not client:
  1428. raise HTTPException(status_code=400, detail="Printer not connected")
  1429. # Resolve tray_info_idx for the MQTT command.
  1430. # Priority:
  1431. # 1. Use the provided tray_info_idx if set (including cloud-synced
  1432. # custom presets like PFUS* / P*).
  1433. # 2. Reuse the slot's existing tray_info_idx if it's a specific
  1434. # (non-generic) preset for the same material.
  1435. # 3. Fall back to a generic Bambu filament ID.
  1436. _GENERIC_FILAMENT_IDS = {
  1437. "PLA": "GFL99",
  1438. "PETG": "GFG99",
  1439. "ABS": "GFB99",
  1440. "ASA": "GFB98",
  1441. "PC": "GFC99",
  1442. "PA": "GFN99",
  1443. "NYLON": "GFN99",
  1444. "TPU": "GFU99",
  1445. "PVA": "GFS99",
  1446. "HIPS": "GFS98",
  1447. "PLA-CF": "GFL98",
  1448. "PETG-CF": "GFG98",
  1449. "PA-CF": "GFN98",
  1450. "PETG HF": "GFG96",
  1451. }
  1452. _GENERIC_ID_VALUES = set(_GENERIC_FILAMENT_IDS.values())
  1453. effective_tray_info_idx = tray_info_idx
  1454. if not tray_info_idx:
  1455. # No preset provided — try slot reuse or generic fallback
  1456. current_tray_info_idx = ""
  1457. current_tray_type = ""
  1458. state = printer_manager.get_status(printer_id)
  1459. if state and state.raw_data:
  1460. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1461. if ams_id == 255:
  1462. vt_tray = state.raw_data.get("vt_tray") or []
  1463. ext_id = tray_id + 254
  1464. for vt in vt_tray:
  1465. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1466. current_tray_info_idx = vt.get("tray_info_idx", "")
  1467. current_tray_type = vt.get("tray_type", "")
  1468. break
  1469. else:
  1470. ams_data = state.raw_data.get("ams", {})
  1471. ams_list = (
  1472. ams_data.get("ams", [])
  1473. if isinstance(ams_data, dict)
  1474. else ams_data
  1475. if isinstance(ams_data, list)
  1476. else []
  1477. )
  1478. cur_tray = _find_tray_in_ams_data(ams_list, ams_id, tray_id)
  1479. if cur_tray:
  1480. current_tray_info_idx = cur_tray.get("tray_info_idx", "")
  1481. current_tray_type = cur_tray.get("tray_type", "")
  1482. if (
  1483. current_tray_info_idx
  1484. and current_tray_info_idx not in _GENERIC_ID_VALUES
  1485. and current_tray_type
  1486. and current_tray_type.upper() == tray_type.upper()
  1487. ):
  1488. logger.info(
  1489. "[configure_ams_slot] Reusing slot's existing tray_info_idx=%r (same material %r)",
  1490. current_tray_info_idx,
  1491. tray_type,
  1492. )
  1493. effective_tray_info_idx = current_tray_info_idx
  1494. elif tray_type:
  1495. material = tray_type.upper().strip()
  1496. generic = (
  1497. _GENERIC_FILAMENT_IDS.get(material)
  1498. or _GENERIC_FILAMENT_IDS.get(material.split("-")[0].split(" ")[0])
  1499. or ""
  1500. )
  1501. if generic:
  1502. logger.info("[configure_ams_slot] Falling back to generic %r for material %r", generic, tray_type)
  1503. effective_tray_info_idx = generic
  1504. # Send filament setting + K-profile commands
  1505. filament_id_for_kprofile = kprofile_filament_id if kprofile_filament_id else effective_tray_info_idx
  1506. # Always send ams_set_filament_setting — the user explicitly clicked
  1507. # "Configure Slot", so honor that. Previous versions skipped this for
  1508. # RFID-tagged slots to preserve the slicer eye icon, but printers cache
  1509. # stale tag_uid/tray_uuid after a BL spool is removed, causing the check
  1510. # to false-positive on non-RFID slots and silently drop the command.
  1511. success = client.ams_set_filament_setting(
  1512. ams_id=ams_id,
  1513. tray_id=tray_id,
  1514. tray_info_idx=effective_tray_info_idx,
  1515. tray_type=tray_type,
  1516. tray_sub_brands=tray_sub_brands,
  1517. tray_color=tray_color,
  1518. nozzle_temp_min=nozzle_temp_min,
  1519. nozzle_temp_max=nozzle_temp_max,
  1520. setting_id=setting_id,
  1521. )
  1522. if not success:
  1523. raise HTTPException(status_code=500, detail="Failed to send filament configuration command")
  1524. # Method 1: Select existing calibration profile by cali_idx
  1525. # Do NOT include setting_id — BambuStudio never sends it in extrusion_cali_sel,
  1526. # and including it causes the firmware to mislink the profile on X1C/P1S.
  1527. client.extrusion_cali_sel(
  1528. ams_id=ams_id,
  1529. tray_id=tray_id,
  1530. cali_idx=cali_idx,
  1531. filament_id=filament_id_for_kprofile,
  1532. nozzle_diameter=nozzle_diameter,
  1533. )
  1534. # Method 2: Only send extrusion_cali_set when NO existing profile was selected
  1535. # (cali_idx == -1). When cali_idx >= 0, extrusion_cali_sel already selected the
  1536. # correct profile. Sending extrusion_cali_set with the same cali_idx would MODIFY
  1537. # the existing profile's metadata (extruder_id, nozzle_id, name, setting_id),
  1538. # corrupting it — e.g., overwriting a High Flow extruder 1 profile with
  1539. # hardcoded extruder_id=0 and nozzle_id=HS00.
  1540. if k_value > 0 and cali_idx < 0:
  1541. # Calculate global tray ID for extrusion_cali_set
  1542. if ams_id <= 3:
  1543. global_tray_id = ams_id * 4 + tray_id
  1544. elif ams_id >= 128 and ams_id <= 135:
  1545. global_tray_id = (ams_id - 128) * 4 + tray_id
  1546. else:
  1547. global_tray_id = tray_id
  1548. client.extrusion_cali_set(
  1549. tray_id=global_tray_id,
  1550. k_value=k_value,
  1551. nozzle_diameter=nozzle_diameter,
  1552. nozzle_temp=nozzle_temp_max,
  1553. filament_id=filament_id_for_kprofile,
  1554. setting_id=kprofile_setting_id or "",
  1555. name=tray_sub_brands or "",
  1556. cali_idx=cali_idx,
  1557. )
  1558. # Request fresh status push from printer so frontend gets updated data via WebSocket
  1559. logger.info("[configure_ams_slot] Requesting status update from printer")
  1560. update_result = client.request_status_update()
  1561. logger.info("[configure_ams_slot] Status update request result: %s", update_result)
  1562. return {
  1563. "success": True,
  1564. "message": f"Configured AMS {ams_id} tray {tray_id} with {tray_sub_brands}",
  1565. }
  1566. @router.post("/{printer_id}/ams/{ams_id}/tray/{tray_id}/reset")
  1567. async def reset_ams_slot(
  1568. printer_id: int,
  1569. ams_id: int,
  1570. tray_id: int,
  1571. db: AsyncSession = Depends(get_db),
  1572. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1573. ):
  1574. """Reset an AMS slot to empty/unconfigured state.
  1575. This clears the filament configuration from the slot.
  1576. """
  1577. # Get MQTT client for this printer
  1578. client = printer_manager.get_client(printer_id)
  1579. if not client:
  1580. raise HTTPException(status_code=400, detail="Printer not connected")
  1581. # Reset the slot
  1582. success = client.reset_ams_slot(ams_id=ams_id, tray_id=tray_id)
  1583. if not success:
  1584. raise HTTPException(status_code=500, detail="Failed to send reset command")
  1585. # Also delete any saved slot preset mapping
  1586. result = await db.execute(
  1587. select(SlotPresetMapping).where(
  1588. SlotPresetMapping.printer_id == printer_id,
  1589. SlotPresetMapping.ams_id == ams_id,
  1590. SlotPresetMapping.tray_id == tray_id,
  1591. )
  1592. )
  1593. mapping = result.scalar_one_or_none()
  1594. if mapping:
  1595. await db.delete(mapping)
  1596. await db.commit()
  1597. # Request fresh status push from printer so frontend gets updated data via WebSocket
  1598. client.request_status_update()
  1599. return {
  1600. "success": True,
  1601. "message": f"Reset AMS {ams_id} tray {tray_id}",
  1602. }
  1603. @router.post("/{printer_id}/debug/simulate-print-complete")
  1604. async def debug_simulate_print_complete(
  1605. printer_id: int,
  1606. db: AsyncSession = Depends(get_db),
  1607. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1608. ):
  1609. """DEBUG: Simulate print completion to test freeze behavior.
  1610. This triggers the same code path as a real print completion,
  1611. without needing to wait for an actual print to finish.
  1612. """
  1613. from backend.app.main import _active_prints, on_print_complete
  1614. from backend.app.models.archive import PrintArchive
  1615. # Get the most recent archive for this printer
  1616. result = await db.execute(
  1617. select(PrintArchive)
  1618. .where(PrintArchive.printer_id == printer_id)
  1619. .order_by(PrintArchive.created_at.desc())
  1620. .limit(1)
  1621. )
  1622. archive = result.scalar_one_or_none()
  1623. if not archive:
  1624. raise HTTPException(status_code=404, detail="No archives found for this printer")
  1625. # Register this archive as "active" so on_print_complete can find it
  1626. filename = archive.file_path.split("/")[-1] if archive.file_path else "test.3mf"
  1627. subtask_name = archive.print_name or "Test Print"
  1628. _active_prints[(printer_id, filename)] = archive.id
  1629. _active_prints[(printer_id, subtask_name)] = archive.id
  1630. # Simulate print completion data
  1631. data = {
  1632. "status": "completed",
  1633. "filename": filename,
  1634. "subtask_name": subtask_name,
  1635. "timelapse_was_active": False,
  1636. }
  1637. logger.info("Simulating print complete for printer %s, archive %s", printer_id, archive.id)
  1638. # Call the actual on_print_complete handler
  1639. await on_print_complete(printer_id, data)
  1640. return {"success": True, "archive_id": archive.id, "message": "Print completion simulated"}
  1641. # =============================================================================
  1642. # Print Control Endpoints
  1643. # =============================================================================
  1644. @router.post("/{printer_id}/print/stop")
  1645. async def stop_print(
  1646. printer_id: int,
  1647. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1648. db: AsyncSession = Depends(get_db),
  1649. ):
  1650. """Stop/cancel the current print job."""
  1651. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1652. printer = result.scalar_one_or_none()
  1653. if not printer:
  1654. raise HTTPException(404, "Printer not found")
  1655. client = printer_manager.get_client(printer_id)
  1656. if not client:
  1657. raise HTTPException(400, "Printer not connected")
  1658. success = client.stop_print()
  1659. if not success:
  1660. raise HTTPException(500, "Failed to stop print")
  1661. return {"success": True, "message": "Print stop command sent"}
  1662. @router.post("/{printer_id}/clear-plate")
  1663. async def clear_plate(
  1664. printer_id: int,
  1665. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CLEAR_PLATE),
  1666. db: AsyncSession = Depends(get_db),
  1667. ):
  1668. """Acknowledge that the build plate has been cleared after a finished/failed print.
  1669. Sets a plate-cleared flag so the scheduler can start the next queued print.
  1670. No MQTT command is sent to the printer — the scheduler's start_print command
  1671. will override the FINISH/FAILED state when it sends the next job.
  1672. """
  1673. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1674. printer = result.scalar_one_or_none()
  1675. if not printer:
  1676. raise HTTPException(404, "Printer not found")
  1677. if not printer_manager.is_connected(printer_id):
  1678. raise HTTPException(400, "Printer not connected")
  1679. state = printer_manager.get_status(printer_id)
  1680. if not state or state.state not in ("FINISH", "FAILED"):
  1681. raise HTTPException(
  1682. 400, f"Printer is not in FINISH or FAILED state (current: {state.state if state else 'unknown'})"
  1683. )
  1684. printer_manager.set_plate_cleared(printer_id)
  1685. return {"success": True, "message": "Plate cleared, next print will start shortly"}
  1686. @router.post("/{printer_id}/print/pause")
  1687. async def pause_print(
  1688. printer_id: int,
  1689. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1690. db: AsyncSession = Depends(get_db),
  1691. ):
  1692. """Pause the current print job."""
  1693. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1694. printer = result.scalar_one_or_none()
  1695. if not printer:
  1696. raise HTTPException(404, "Printer not found")
  1697. client = printer_manager.get_client(printer_id)
  1698. if not client:
  1699. raise HTTPException(400, "Printer not connected")
  1700. success = client.pause_print()
  1701. if not success:
  1702. raise HTTPException(500, "Failed to pause print")
  1703. return {"success": True, "message": "Print pause command sent"}
  1704. @router.post("/{printer_id}/print/resume")
  1705. async def resume_print(
  1706. printer_id: int,
  1707. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1708. db: AsyncSession = Depends(get_db),
  1709. ):
  1710. """Resume a paused print job."""
  1711. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1712. printer = result.scalar_one_or_none()
  1713. if not printer:
  1714. raise HTTPException(404, "Printer not found")
  1715. client = printer_manager.get_client(printer_id)
  1716. if not client:
  1717. raise HTTPException(400, "Printer not connected")
  1718. success = client.resume_print()
  1719. if not success:
  1720. raise HTTPException(500, "Failed to resume print")
  1721. return {"success": True, "message": "Print resume command sent"}
  1722. @router.post("/{printer_id}/chamber-light")
  1723. async def set_chamber_light(
  1724. printer_id: int,
  1725. on: bool = Query(..., description="True to turn on, False to turn off"),
  1726. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1727. db: AsyncSession = Depends(get_db),
  1728. ):
  1729. """Turn the chamber light on or off."""
  1730. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1731. printer = result.scalar_one_or_none()
  1732. if not printer:
  1733. raise HTTPException(404, "Printer not found")
  1734. client = printer_manager.get_client(printer_id)
  1735. if not client:
  1736. raise HTTPException(400, "Printer not connected")
  1737. success = client.set_chamber_light(on)
  1738. if not success:
  1739. raise HTTPException(500, "Failed to control chamber light")
  1740. return {"success": True, "message": f"Chamber light {'on' if on else 'off'}"}
  1741. @router.post("/{printer_id}/hms/clear")
  1742. async def clear_hms_errors(
  1743. printer_id: int,
  1744. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1745. db: AsyncSession = Depends(get_db),
  1746. ):
  1747. """Clear HMS/print errors on the printer."""
  1748. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1749. printer = result.scalar_one_or_none()
  1750. if not printer:
  1751. raise HTTPException(404, "Printer not found")
  1752. client = printer_manager.get_client(printer_id)
  1753. if not client:
  1754. raise HTTPException(400, "Printer not connected")
  1755. success = client.clear_hms_errors()
  1756. if not success:
  1757. raise HTTPException(500, "Failed to clear HMS errors")
  1758. return {"success": True, "message": "HMS errors cleared"}
  1759. @router.get("/{printer_id}/print/objects")
  1760. async def get_printable_objects(
  1761. printer_id: int,
  1762. reload: bool = False,
  1763. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1764. db: AsyncSession = Depends(get_db),
  1765. ):
  1766. """Get the list of printable objects for the current print.
  1767. Returns a list of objects with id, name, position (if available), and skip status.
  1768. Objects that have already been skipped are marked in the skipped_objects list.
  1769. Args:
  1770. reload: If True, reload objects from the archive file (useful after restart)
  1771. """
  1772. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1773. printer = result.scalar_one_or_none()
  1774. if not printer:
  1775. raise HTTPException(404, "Printer not found")
  1776. client = printer_manager.get_client(printer_id)
  1777. if not client:
  1778. raise HTTPException(400, "Printer not connected")
  1779. # Reload objects from 3MF if requested or no objects loaded
  1780. if reload or not client.state.printable_objects:
  1781. subtask_name = client.state.subtask_name
  1782. if subtask_name:
  1783. from backend.app.services.archive import extract_printable_objects_from_3mf
  1784. from backend.app.services.bambu_ftp import download_file_try_paths_async
  1785. # Build possible 3MF filenames (try both .gcode.3mf and .3mf)
  1786. possible_filenames = []
  1787. if subtask_name.endswith(".3mf"):
  1788. possible_filenames.append(subtask_name)
  1789. else:
  1790. possible_filenames.append(f"{subtask_name}.gcode.3mf")
  1791. possible_filenames.append(f"{subtask_name}.3mf")
  1792. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  1793. if " " in subtask_name:
  1794. normalized = subtask_name.replace(" ", "_")
  1795. if normalized.endswith(".3mf"):
  1796. possible_filenames.append(normalized)
  1797. else:
  1798. possible_filenames.append(f"{normalized}.gcode.3mf")
  1799. possible_filenames.append(f"{normalized}.3mf")
  1800. # Download 3MF from printer
  1801. temp_path = settings.archive_dir / "temp" / f"objects_{printer_id}_{possible_filenames[0]}"
  1802. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1803. # Build list of all remote paths to try
  1804. remote_paths = []
  1805. for filename in possible_filenames:
  1806. remote_paths.extend([f"/{filename}", f"/cache/{filename}", f"/model/{filename}"])
  1807. try:
  1808. downloaded = await download_file_try_paths_async(
  1809. printer.ip_address,
  1810. printer.access_code,
  1811. remote_paths,
  1812. temp_path,
  1813. printer_model=printer.model,
  1814. )
  1815. if downloaded and temp_path.exists():
  1816. with open(temp_path, "rb") as f:
  1817. data = f.read()
  1818. objects, bbox_all = extract_printable_objects_from_3mf(data, include_positions=True)
  1819. if objects:
  1820. client.state.printable_objects = objects
  1821. client.state.printable_objects_bbox_all = bbox_all
  1822. logger.info("Reloaded %s objects for printer %s", len(objects), printer_id)
  1823. except Exception as e:
  1824. logger.debug("Failed to reload objects from printer: %s", e)
  1825. finally:
  1826. if temp_path.exists():
  1827. temp_path.unlink()
  1828. # Return objects with their skip status and position data
  1829. objects = []
  1830. for obj_id, obj_data in client.state.printable_objects.items():
  1831. # Handle both old format (string name) and new format (dict with name, x, y)
  1832. if isinstance(obj_data, dict):
  1833. obj_entry = {
  1834. "id": obj_id,
  1835. "name": obj_data.get("name", f"Object {obj_id}"),
  1836. "x": obj_data.get("x"),
  1837. "y": obj_data.get("y"),
  1838. "skipped": obj_id in client.state.skipped_objects,
  1839. }
  1840. else:
  1841. # Legacy format: obj_data is just the name string
  1842. obj_entry = {
  1843. "id": obj_id,
  1844. "name": obj_data,
  1845. "x": None,
  1846. "y": None,
  1847. "skipped": obj_id in client.state.skipped_objects,
  1848. }
  1849. objects.append(obj_entry)
  1850. return {
  1851. "objects": objects,
  1852. "total": len(objects),
  1853. "skipped_count": len(client.state.skipped_objects),
  1854. "is_printing": client.state.state in ("RUNNING", "PAUSE"),
  1855. "bbox_all": getattr(client.state, "printable_objects_bbox_all", None),
  1856. }
  1857. @router.post("/{printer_id}/print/skip-objects")
  1858. async def skip_objects(
  1859. printer_id: int,
  1860. object_ids: list[int],
  1861. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1862. db: AsyncSession = Depends(get_db),
  1863. ):
  1864. """Skip specific objects during the current print.
  1865. Args:
  1866. object_ids: List of object identify_id values to skip
  1867. """
  1868. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1869. printer = result.scalar_one_or_none()
  1870. if not printer:
  1871. raise HTTPException(404, "Printer not found")
  1872. client = printer_manager.get_client(printer_id)
  1873. if not client:
  1874. raise HTTPException(400, "Printer not connected")
  1875. if not object_ids:
  1876. raise HTTPException(400, "No object IDs provided")
  1877. # Validate object IDs exist in printable_objects
  1878. invalid_ids = [oid for oid in object_ids if oid not in client.state.printable_objects]
  1879. if invalid_ids:
  1880. raise HTTPException(400, f"Invalid object IDs: {invalid_ids}")
  1881. success = client.skip_objects(object_ids)
  1882. if not success:
  1883. raise HTTPException(500, "Failed to skip objects")
  1884. # Get names of skipped objects for response (handle both old and new format)
  1885. skipped_names = []
  1886. for oid in object_ids:
  1887. obj_data = client.state.printable_objects.get(oid, str(oid))
  1888. if isinstance(obj_data, dict):
  1889. skipped_names.append(obj_data.get("name", str(oid)))
  1890. else:
  1891. skipped_names.append(obj_data)
  1892. return {
  1893. "success": True,
  1894. "message": f"Skipped {len(object_ids)} object(s): {', '.join(skipped_names)}",
  1895. "skipped_objects": object_ids,
  1896. }
  1897. # =============================================================================
  1898. # AMS Control Endpoints
  1899. # =============================================================================
  1900. @router.post("/{printer_id}/ams/{ams_id}/slot/{slot_id}/refresh")
  1901. async def refresh_ams_slot(
  1902. printer_id: int,
  1903. ams_id: int,
  1904. slot_id: int,
  1905. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_AMS_RFID),
  1906. db: AsyncSession = Depends(get_db),
  1907. ):
  1908. """Re-read RFID for an AMS slot (triggers filament info refresh)."""
  1909. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1910. printer = result.scalar_one_or_none()
  1911. if not printer:
  1912. raise HTTPException(404, "Printer not found")
  1913. client = printer_manager.get_client(printer_id)
  1914. if not client:
  1915. raise HTTPException(400, "Printer not connected")
  1916. success, message = client.ams_refresh_tray(ams_id, slot_id)
  1917. if not success:
  1918. raise HTTPException(400, message)
  1919. # Apply PA profile after delay (RFID re-read takes a few seconds)
  1920. asyncio.create_task(_apply_pa_after_refresh(printer_id, ams_id, slot_id))
  1921. return {"success": True, "message": message}
  1922. async def _apply_pa_after_refresh(printer_id: int, ams_id: int, slot_id: int):
  1923. """Apply PA profile after RFID re-read completes.
  1924. Waits for the printer to finish processing the RFID data, then selects
  1925. the K-profile via extrusion_cali_sel. Does NOT re-send ams_set_filament_setting
  1926. because that would overwrite the RFID-provided filament data.
  1927. """
  1928. await asyncio.sleep(5)
  1929. try:
  1930. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1931. from backend.app.core.database import async_session
  1932. from backend.app.models.spool import Spool
  1933. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1934. from backend.app.services.spool_tag_matcher import is_bambu_tag
  1935. client = printer_manager.get_client(printer_id)
  1936. if not client:
  1937. return
  1938. state = printer_manager.get_status(printer_id)
  1939. if not state or not state.raw_data:
  1940. return
  1941. # Find current tray data (should have RFID data by now)
  1942. ams_data = state.raw_data.get("ams", {})
  1943. ams_list = (
  1944. ams_data.get("ams", []) if isinstance(ams_data, dict) else ams_data if isinstance(ams_data, list) else []
  1945. )
  1946. tray = _find_tray_in_ams_data(ams_list, ams_id, slot_id)
  1947. if not tray or not tray.get("tray_type"):
  1948. logger.debug("PA re-apply: no tray data for AMS%d-T%d", ams_id, slot_id)
  1949. return
  1950. tag_uid = tray.get("tag_uid", "")
  1951. tray_uuid = tray.get("tray_uuid", "")
  1952. tray_info_idx = tray.get("tray_info_idx", "")
  1953. if not is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  1954. return
  1955. async with async_session() as db:
  1956. from sqlalchemy import select as sa_select
  1957. from sqlalchemy.orm import selectinload
  1958. result = await db.execute(
  1959. sa_select(SA)
  1960. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  1961. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == slot_id)
  1962. )
  1963. assignment = result.scalar_one_or_none()
  1964. if not assignment or not assignment.spool or not assignment.spool.k_profiles:
  1965. return
  1966. spool = assignment.spool
  1967. nozzle_diameter = "0.4"
  1968. if state.nozzles:
  1969. nd = state.nozzles[0].nozzle_diameter
  1970. if nd:
  1971. nozzle_diameter = nd
  1972. # Determine slot's extruder from ams_extruder_map
  1973. slot_extruder = None
  1974. if state.ams_extruder_map:
  1975. if ams_id == 255:
  1976. # External slots: ext-L (tray 0) → extruder 1, ext-R (tray 1) → extruder 0
  1977. slot_extruder = 1 - slot_id # 0→1, 1→0
  1978. else:
  1979. slot_extruder = state.ams_extruder_map.get(str(ams_id))
  1980. matching_kp = None
  1981. for kp in spool.k_profiles:
  1982. if kp.printer_id == printer_id and kp.nozzle_diameter == nozzle_diameter:
  1983. if slot_extruder is not None and kp.extruder_id is not None and kp.extruder_id != slot_extruder:
  1984. continue
  1985. matching_kp = kp
  1986. break
  1987. if not matching_kp or matching_kp.cali_idx is None:
  1988. return
  1989. # The filament_id in extrusion_cali_sel must match the filament preset
  1990. # under which the K-profile was calibrated. Use spool.slicer_filament
  1991. # (the preset assigned in inventory), falling back to tray's RFID value.
  1992. kp_filament_id = spool.slicer_filament or tray_info_idx
  1993. logger.info(
  1994. "PA re-apply AMS%d-T%d: cali_idx=%d, filament_id=%s",
  1995. ams_id,
  1996. slot_id,
  1997. matching_kp.cali_idx,
  1998. kp_filament_id,
  1999. )
  2000. # 1. Select K-profile
  2001. # NOTE: Do NOT send ams_set_filament_setting here — it tells the firmware
  2002. # "this is a manual config" which destroys the RFID-detected spool state
  2003. # (changes eye icon to pen icon in slicer).
  2004. client.extrusion_cali_sel(
  2005. ams_id=ams_id,
  2006. tray_id=slot_id,
  2007. cali_idx=matching_kp.cali_idx,
  2008. filament_id=kp_filament_id,
  2009. nozzle_diameter=nozzle_diameter,
  2010. )
  2011. # NOTE: Do NOT send extrusion_cali_set here. extrusion_cali_sel already
  2012. # selected the correct profile by cali_idx. Sending extrusion_cali_set with
  2013. # the same cali_idx would MODIFY the existing profile's metadata (extruder_id,
  2014. # nozzle_id, name), corrupting it.
  2015. logger.info(
  2016. "Applied PA profile cali_idx=%d k=%.3f to printer %d AMS%d-T%d",
  2017. matching_kp.cali_idx,
  2018. matching_kp.k_value or 0,
  2019. printer_id,
  2020. ams_id,
  2021. slot_id,
  2022. )
  2023. except Exception as e:
  2024. logger.warning("Failed to apply PA profile after RFID re-read: %s", e)
  2025. @router.get("/{printer_id}/runtime-debug")
  2026. async def get_runtime_debug(
  2027. printer_id: int,
  2028. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2029. db: AsyncSession = Depends(get_db),
  2030. ):
  2031. """Debug endpoint: Get runtime tracking status for a printer."""
  2032. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2033. printer = result.scalar_one_or_none()
  2034. if not printer:
  2035. raise HTTPException(404, "Printer not found")
  2036. state = printer_manager.get_status(printer_id)
  2037. return {
  2038. "printer_name": printer.name,
  2039. "runtime_seconds": printer.runtime_seconds,
  2040. "runtime_hours": printer.runtime_seconds / 3600.0 if printer.runtime_seconds else 0,
  2041. "print_hours_offset": printer.print_hours_offset,
  2042. "total_hours": (printer.runtime_seconds / 3600.0 if printer.runtime_seconds else 0)
  2043. + (printer.print_hours_offset or 0),
  2044. "last_runtime_update": printer.last_runtime_update.isoformat() if printer.last_runtime_update else None,
  2045. "mqtt_state": {
  2046. "connected": state.connected if state else False,
  2047. "state": state.state if state else None,
  2048. "progress": state.progress if state else None,
  2049. "gcode_file": state.gcode_file if state else None,
  2050. }
  2051. if state
  2052. else None,
  2053. "is_active": printer.is_active,
  2054. }