printers.py 89 KB

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