printers.py 111 KB

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