printers.py 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146
  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", "PAUSED") 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 = None
  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
  274. if "vt_tray" in raw_data:
  275. vt_data = 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. vt_tray = AMSTray(
  289. id=254, # Virtual tray ID
  290. tray_color=vt_data.get("tray_color"),
  291. tray_type=vt_data.get("tray_type"),
  292. tray_sub_brands=vt_data.get("tray_sub_brands"),
  293. tray_id_name=vt_data.get("tray_id_name"),
  294. tray_info_idx=vt_data.get("tray_info_idx"),
  295. remain=vt_data.get("remain", 0),
  296. k=vt_k_value,
  297. cali_idx=vt_cali_idx,
  298. tag_uid=vt_tag_uid,
  299. tray_uuid=vt_tray_uuid,
  300. nozzle_temp_min=vt_data.get("nozzle_temp_min"),
  301. nozzle_temp_max=vt_data.get("nozzle_temp_max"),
  302. )
  303. # Convert nozzle info to response format
  304. nozzles = [
  305. NozzleInfoResponse(
  306. nozzle_type=n.nozzle_type,
  307. nozzle_diameter=n.nozzle_diameter,
  308. )
  309. for n in (state.nozzles or [])
  310. ]
  311. # H2C nozzle rack (tool-changer dock positions)
  312. nozzle_rack = [
  313. NozzleRackSlot(
  314. id=n.get("id", 0),
  315. nozzle_type=n.get("type", ""),
  316. nozzle_diameter=n.get("diameter", ""),
  317. wear=n.get("wear"),
  318. stat=n.get("stat"),
  319. max_temp=n.get("max_temp", 0),
  320. serial_number=n.get("serial_number", ""),
  321. filament_color=n.get("filament_color", ""),
  322. filament_id=n.get("filament_id", ""),
  323. filament_type=n.get("filament_type", ""),
  324. )
  325. for n in (state.nozzle_rack or [])
  326. ]
  327. # Convert print options to response format
  328. print_options = PrintOptionsResponse(
  329. spaghetti_detector=state.print_options.spaghetti_detector,
  330. print_halt=state.print_options.print_halt,
  331. halt_print_sensitivity=state.print_options.halt_print_sensitivity,
  332. first_layer_inspector=state.print_options.first_layer_inspector,
  333. printing_monitor=state.print_options.printing_monitor,
  334. buildplate_marker_detector=state.print_options.buildplate_marker_detector,
  335. allow_skip_parts=state.print_options.allow_skip_parts,
  336. nozzle_clumping_detector=state.print_options.nozzle_clumping_detector,
  337. nozzle_clumping_sensitivity=state.print_options.nozzle_clumping_sensitivity,
  338. pileup_detector=state.print_options.pileup_detector,
  339. pileup_sensitivity=state.print_options.pileup_sensitivity,
  340. airprint_detector=state.print_options.airprint_detector,
  341. airprint_sensitivity=state.print_options.airprint_sensitivity,
  342. auto_recovery_step_loss=state.print_options.auto_recovery_step_loss,
  343. filament_tangle_detect=state.print_options.filament_tangle_detect,
  344. )
  345. # Get AMS mapping from raw_data (which AMS is connected to which nozzle)
  346. ams_mapping = raw_data.get("ams_mapping", [])
  347. # Get per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  348. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  349. logger.debug("API returning ams_mapping: %s, ams_extruder_map: %s", ams_mapping, ams_extruder_map)
  350. # tray_now from MQTT is already a global tray ID: (ams_id * 4) + slot_id
  351. # Per OpenBambuAPI docs: 254 = external spool, 255 = no filament, otherwise global tray ID
  352. # No conversion needed - just use the raw value directly
  353. tray_now = state.tray_now
  354. logger.debug("Using tray_now directly as global ID: %s", tray_now)
  355. # Filter out chamber temp for models that don't have a real sensor
  356. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  357. temperatures = state.temperatures
  358. if not supports_chamber_temp(printer.model):
  359. temperatures = {
  360. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  361. }
  362. return PrinterStatus(
  363. id=printer_id,
  364. name=printer.name,
  365. connected=state.connected,
  366. state=state.state,
  367. current_print=state.current_print,
  368. subtask_name=state.subtask_name,
  369. gcode_file=state.gcode_file,
  370. progress=state.progress,
  371. remaining_time=state.remaining_time,
  372. layer_num=state.layer_num,
  373. total_layers=state.total_layers,
  374. temperatures=temperatures,
  375. cover_url=cover_url,
  376. hms_errors=hms_errors,
  377. ams=ams_units,
  378. ams_exists=ams_exists,
  379. vt_tray=vt_tray,
  380. sdcard=state.sdcard,
  381. store_to_sdcard=state.store_to_sdcard,
  382. timelapse=state.timelapse,
  383. ipcam=state.ipcam,
  384. wifi_signal=state.wifi_signal,
  385. nozzles=nozzles,
  386. nozzle_rack=nozzle_rack,
  387. print_options=print_options,
  388. stg_cur=state.stg_cur,
  389. stg_cur_name=get_derived_status_name(state, printer.model),
  390. stg=state.stg,
  391. airduct_mode=state.airduct_mode,
  392. speed_level=state.speed_level,
  393. chamber_light=state.chamber_light,
  394. active_extruder=state.active_extruder,
  395. ams_mapping=ams_mapping,
  396. ams_extruder_map=ams_extruder_map,
  397. tray_now=tray_now,
  398. ams_status_main=state.ams_status_main,
  399. ams_status_sub=state.ams_status_sub,
  400. mc_print_sub_stage=state.mc_print_sub_stage,
  401. last_ams_update=state.last_ams_update,
  402. printable_objects_count=len(state.printable_objects),
  403. cooling_fan_speed=state.cooling_fan_speed,
  404. big_fan1_speed=state.big_fan1_speed,
  405. big_fan2_speed=state.big_fan2_speed,
  406. heatbreak_fan_speed=state.heatbreak_fan_speed,
  407. firmware_version=state.firmware_version,
  408. )
  409. @router.get("/{printer_id}/current-print-user")
  410. async def get_current_print_user(
  411. printer_id: int,
  412. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  413. db: AsyncSession = Depends(get_db),
  414. ):
  415. """Get the user who started the current print (for reprint tracking).
  416. Returns user info if available, empty object otherwise.
  417. This tracks users for reprints (which bypass the queue).
  418. For queue-based prints, use the queue item's created_by field instead.
  419. """
  420. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  421. printer = result.scalar_one_or_none()
  422. if not printer:
  423. raise HTTPException(404, "Printer not found")
  424. user_info = printer_manager.get_current_print_user(printer_id)
  425. return user_info or {}
  426. @router.post("/{printer_id}/refresh-status")
  427. async def refresh_printer_status(
  428. printer_id: int,
  429. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  430. db: AsyncSession = Depends(get_db),
  431. ):
  432. """Request a full status refresh from the printer (sends pushall command)."""
  433. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  434. printer = result.scalar_one_or_none()
  435. if not printer:
  436. raise HTTPException(404, "Printer not found")
  437. success = printer_manager.request_status_update(printer_id)
  438. if not success:
  439. raise HTTPException(400, "Printer not connected")
  440. return {"status": "refresh_requested"}
  441. @router.post("/{printer_id}/connect")
  442. async def connect_printer(
  443. printer_id: int,
  444. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  445. db: AsyncSession = Depends(get_db),
  446. ):
  447. """Manually connect to a printer."""
  448. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  449. printer = result.scalar_one_or_none()
  450. if not printer:
  451. raise HTTPException(404, "Printer not found")
  452. success = await printer_manager.connect_printer(printer)
  453. return {"connected": success}
  454. @router.post("/{printer_id}/disconnect")
  455. async def disconnect_printer(
  456. printer_id: int,
  457. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  458. db: AsyncSession = Depends(get_db),
  459. ):
  460. """Manually disconnect from a printer."""
  461. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  462. printer = result.scalar_one_or_none()
  463. if not printer:
  464. raise HTTPException(404, "Printer not found")
  465. printer_manager.disconnect_printer(printer_id)
  466. return {"connected": False}
  467. @router.post("/test")
  468. async def test_printer_connection(
  469. ip_address: str,
  470. serial_number: str,
  471. access_code: str,
  472. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CREATE),
  473. ):
  474. """Test connection to a printer without saving."""
  475. result = await printer_manager.test_connection(
  476. ip_address=ip_address,
  477. serial_number=serial_number,
  478. access_code=access_code,
  479. )
  480. return result
  481. # Cache for cover images (printer_id -> {(subtask_name, plate_num, view) -> image_bytes})
  482. _cover_cache: dict[int, dict[tuple[str, str], bytes]] = {}
  483. def clear_cover_cache(printer_id: int) -> None:
  484. """Clear cached cover images for a printer. Call on print start to avoid stale thumbnails."""
  485. _cover_cache.pop(printer_id, None)
  486. @router.get("/{printer_id}/cover")
  487. async def get_printer_cover(
  488. printer_id: int,
  489. view: str | None = None,
  490. db: AsyncSession = Depends(get_db),
  491. ):
  492. # Note: No auth required - this is an image asset loaded via <img src> which can't send auth headers
  493. """Get the cover image for the current print job.
  494. Args:
  495. view: Optional view type. Use "top" for top-down build plate view (useful for skip objects).
  496. Default returns angled 3D perspective view.
  497. """
  498. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  499. printer = result.scalar_one_or_none()
  500. if not printer:
  501. raise HTTPException(404, "Printer not found")
  502. state = printer_manager.get_status(printer_id)
  503. if not state:
  504. raise HTTPException(404, "Printer not connected")
  505. # Use subtask_name as the 3MF filename (gcode_file is the path inside the 3MF)
  506. subtask_name = state.subtask_name
  507. if not subtask_name:
  508. raise HTTPException(404, f"No subtask_name in printer state (state={state.state})")
  509. # Extract plate number from gcode_file (e.g., "/data/Metadata/plate_12.gcode" -> 12)
  510. plate_num = 1
  511. gcode_file = state.gcode_file
  512. if gcode_file:
  513. match = re.search(r"plate_(\d+)\.gcode", gcode_file)
  514. if match:
  515. plate_num = int(match.group(1))
  516. logger.info("Detected plate number %s from gcode_file: %s", plate_num, gcode_file)
  517. # Normalize view parameter
  518. view_key = view or "default"
  519. # Check cache - include plate_num in cache key for multi-plate projects
  520. if printer_id in _cover_cache:
  521. cache_key = (subtask_name, plate_num, view_key)
  522. if cache_key in _cover_cache[printer_id]:
  523. return Response(content=_cover_cache[printer_id][cache_key], media_type="image/png")
  524. # Build possible 3MF filenames from subtask_name
  525. # Bambu printers may store files as "name.gcode.3mf" (sliced via Bambu Studio)
  526. # or just "name.3mf" (uploaded directly)
  527. possible_filenames = []
  528. if subtask_name.endswith(".3mf"):
  529. possible_filenames.append(subtask_name)
  530. else:
  531. # Try both naming patterns
  532. possible_filenames.append(f"{subtask_name}.gcode.3mf")
  533. possible_filenames.append(f"{subtask_name}.3mf")
  534. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  535. if " " in subtask_name:
  536. normalized = subtask_name.replace(" ", "_")
  537. if normalized.endswith(".3mf"):
  538. possible_filenames.append(normalized)
  539. else:
  540. possible_filenames.append(f"{normalized}.gcode.3mf")
  541. possible_filenames.append(f"{normalized}.3mf")
  542. # Build list of all remote paths to try
  543. remote_paths = []
  544. for filename in possible_filenames:
  545. remote_paths.extend(
  546. [
  547. f"/{filename}", # Root directory (most common)
  548. f"/cache/{filename}",
  549. f"/model/{filename}",
  550. f"/data/{filename}",
  551. ]
  552. )
  553. # Use first filename for temp path (will be reused)
  554. temp_filename = possible_filenames[0]
  555. temp_path = settings.archive_dir / "temp" / f"cover_{printer_id}_{temp_filename}"
  556. temp_path.parent.mkdir(parents=True, exist_ok=True)
  557. logger.info(
  558. f"Trying to download cover for '{subtask_name}' from {printer.ip_address} (trying {len(remote_paths)} paths)"
  559. )
  560. # Retry logic for transient FTP failures
  561. max_retries = 2
  562. last_error = None
  563. downloaded = False
  564. for attempt in range(max_retries + 1):
  565. try:
  566. downloaded = await download_file_try_paths_async(
  567. printer.ip_address,
  568. printer.access_code,
  569. remote_paths,
  570. temp_path,
  571. printer_model=printer.model,
  572. )
  573. if downloaded:
  574. break
  575. except Exception as e:
  576. last_error = e
  577. if attempt < max_retries:
  578. logger.warning("FTP download attempt %s failed: %s, retrying...", attempt + 1, e)
  579. await asyncio.sleep(0.5 * (attempt + 1)) # Brief backoff
  580. else:
  581. logger.error("FTP download failed after %s attempts: %s", max_retries + 1, e)
  582. if last_error and not downloaded:
  583. raise HTTPException(503, f"FTP download temporarily unavailable: {last_error}")
  584. if not downloaded:
  585. raise HTTPException(
  586. 404,
  587. f"Could not download 3MF file for '{subtask_name}' from printer {printer.ip_address}. Tried: {possible_filenames}",
  588. )
  589. # Verify file actually exists and has content
  590. if not temp_path.exists():
  591. raise HTTPException(500, f"Download reported success but file not found: {temp_path}")
  592. file_size = temp_path.stat().st_size
  593. logger.info("Downloaded file size: %s bytes", file_size)
  594. if file_size == 0:
  595. temp_path.unlink()
  596. raise HTTPException(500, f"Downloaded file is empty for '{subtask_name}'")
  597. try:
  598. # Extract thumbnail from 3MF (which is a ZIP file)
  599. try:
  600. zf = zipfile.ZipFile(temp_path, "r")
  601. except zipfile.BadZipFile:
  602. raise HTTPException(500, "Downloaded file is not a valid 3MF/ZIP archive")
  603. except OSError as e:
  604. logger.error("Failed to open 3MF file: %s", e, exc_info=True)
  605. raise HTTPException(500, "Failed to open 3MF file. Check server logs for details.")
  606. try:
  607. # Try common thumbnail paths in 3MF files
  608. # Use plate_num to get the correct plate's thumbnail for multi-plate projects
  609. # Use top-down view if requested (better for skip objects modal)
  610. if view == "top":
  611. thumbnail_paths = [
  612. f"Metadata/top_{plate_num}.png",
  613. # Fall back to plate 1 if specific plate not found
  614. "Metadata/top_1.png",
  615. f"Metadata/plate_{plate_num}.png",
  616. "Metadata/plate_1.png",
  617. "Metadata/thumbnail.png",
  618. ]
  619. else:
  620. thumbnail_paths = [
  621. f"Metadata/plate_{plate_num}.png",
  622. # Fall back to plate 1 if specific plate not found
  623. "Metadata/plate_1.png",
  624. "Metadata/thumbnail.png",
  625. f"Metadata/plate_{plate_num}_small.png",
  626. "Metadata/plate_1_small.png",
  627. "Thumbnails/thumbnail.png",
  628. "thumbnail.png",
  629. ]
  630. for thumb_path in thumbnail_paths:
  631. try:
  632. image_data = zf.read(thumb_path)
  633. # Cache the result - include plate_num in cache key
  634. if printer_id not in _cover_cache:
  635. _cover_cache[printer_id] = {}
  636. _cover_cache[printer_id][(subtask_name, plate_num, view_key)] = image_data
  637. return Response(content=image_data, media_type="image/png")
  638. except KeyError:
  639. continue
  640. # If no specific thumbnail found, try any PNG in Metadata
  641. for name in zf.namelist():
  642. if name.startswith("Metadata/") and name.endswith(".png"):
  643. image_data = zf.read(name)
  644. if printer_id not in _cover_cache:
  645. _cover_cache[printer_id] = {}
  646. _cover_cache[printer_id][(subtask_name, plate_num, view_key)] = image_data
  647. return Response(content=image_data, media_type="image/png")
  648. raise HTTPException(404, "No thumbnail found in 3MF file")
  649. finally:
  650. zf.close()
  651. finally:
  652. if temp_path.exists():
  653. temp_path.unlink()
  654. # ============================================
  655. # File Manager Endpoints
  656. # ============================================
  657. @router.get("/{printer_id}/files")
  658. async def list_printer_files(
  659. printer_id: int,
  660. path: str = "/",
  661. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  662. db: AsyncSession = Depends(get_db),
  663. ):
  664. """List files on the printer at the specified path."""
  665. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  666. printer = result.scalar_one_or_none()
  667. if not printer:
  668. raise HTTPException(404, "Printer not found")
  669. files = await list_files_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  670. # Add full path to each file
  671. for f in files:
  672. f["path"] = f"{path.rstrip('/')}/{f['name']}" if path != "/" else f"/{f['name']}"
  673. return {
  674. "path": path,
  675. "files": files,
  676. }
  677. @router.get("/{printer_id}/files/download")
  678. async def download_printer_file(
  679. printer_id: int,
  680. path: str,
  681. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  682. db: AsyncSession = Depends(get_db),
  683. ):
  684. """Download a file from the printer."""
  685. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  686. printer = result.scalar_one_or_none()
  687. if not printer:
  688. raise HTTPException(404, "Printer not found")
  689. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  690. if data is None:
  691. raise HTTPException(404, f"File not found: {path}")
  692. # Determine content type based on extension
  693. filename = path.split("/")[-1]
  694. ext = filename.lower().split(".")[-1] if "." in filename else ""
  695. content_types = {
  696. "3mf": "application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  697. "gcode": "text/plain",
  698. "mp4": "video/mp4",
  699. "avi": "video/x-msvideo",
  700. "png": "image/png",
  701. "jpg": "image/jpeg",
  702. "jpeg": "image/jpeg",
  703. "json": "application/json",
  704. "txt": "text/plain",
  705. }
  706. content_type = content_types.get(ext, "application/octet-stream")
  707. return Response(
  708. content=data,
  709. media_type=content_type,
  710. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  711. )
  712. @router.get("/{printer_id}/files/gcode")
  713. async def get_printer_file_gcode(
  714. printer_id: int,
  715. path: str,
  716. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  717. db: AsyncSession = Depends(get_db),
  718. ):
  719. """Get gcode for a file stored on a printer (for preview)."""
  720. import io
  721. # Validate printer
  722. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  723. printer = result.scalar_one_or_none()
  724. if not printer:
  725. raise HTTPException(404, "Printer not found")
  726. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  727. if data is None:
  728. raise HTTPException(404, f"File not found: {path}")
  729. filename = path.split("/")[-1]
  730. lower = filename.lower()
  731. if lower.endswith(".gcode"):
  732. return Response(content=data, media_type="text/plain")
  733. if lower.endswith(".3mf"):
  734. try:
  735. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  736. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  737. if not gcode_files:
  738. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  739. gcode_content = zf.read(gcode_files[0])
  740. return Response(content=gcode_content, media_type="text/plain")
  741. except zipfile.BadZipFile:
  742. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  743. raise HTTPException(status_code=400, detail="Unsupported file type")
  744. @router.get("/{printer_id}/files/plates")
  745. async def get_printer_file_plates(
  746. printer_id: int,
  747. path: str = Query(..., description="Full path to the 3MF file on the printer"),
  748. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  749. db: AsyncSession = Depends(get_db),
  750. ):
  751. """Get available plates from a multi-plate 3MF file stored on a printer."""
  752. import io
  753. import json
  754. import defusedxml.ElementTree as ET
  755. # Validate printer
  756. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  757. printer = result.scalar_one_or_none()
  758. if not printer:
  759. raise HTTPException(404, "Printer not found")
  760. filename = path.split("/")[-1]
  761. if not filename.lower().endswith(".3mf"):
  762. return {
  763. "printer_id": printer_id,
  764. "path": path,
  765. "filename": filename,
  766. "plates": [],
  767. "is_multi_plate": False,
  768. }
  769. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  770. if data is None:
  771. raise HTTPException(404, f"File not found: {path}")
  772. plates = []
  773. try:
  774. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  775. namelist = zf.namelist()
  776. # Find all plate gcode files to determine available plates
  777. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  778. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  779. plate_indices: list[int] = []
  780. if gcode_files:
  781. for gf in gcode_files:
  782. try:
  783. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  784. plate_indices.append(int(plate_str))
  785. except ValueError:
  786. pass # Skip gcode files with non-numeric plate indices
  787. else:
  788. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  789. plate_png_files = [
  790. n
  791. for n in namelist
  792. if n.startswith("Metadata/plate_")
  793. and n.endswith(".png")
  794. and "_small" not in n
  795. and "no_light" not in n
  796. ]
  797. plate_name_candidates = plate_json_files + plate_png_files
  798. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  799. seen_indices: set[int] = set()
  800. for name in plate_name_candidates:
  801. match = plate_re.match(name)
  802. if match:
  803. try:
  804. index = int(match.group(1))
  805. except ValueError:
  806. continue
  807. if index in seen_indices:
  808. continue
  809. seen_indices.add(index)
  810. plate_indices.append(index)
  811. if not plate_indices:
  812. return {
  813. "printer_id": printer_id,
  814. "path": path,
  815. "filename": filename,
  816. "plates": [],
  817. "is_multi_plate": False,
  818. }
  819. plate_indices.sort()
  820. # Parse model_settings.config for plate names
  821. plate_names = {}
  822. if "Metadata/model_settings.config" in namelist:
  823. try:
  824. model_content = zf.read("Metadata/model_settings.config").decode()
  825. model_root = ET.fromstring(model_content)
  826. for plate_elem in model_root.findall(".//plate"):
  827. plater_id = None
  828. plater_name = None
  829. for meta in plate_elem.findall("metadata"):
  830. key = meta.get("key")
  831. value = meta.get("value")
  832. if key == "plater_id" and value:
  833. try:
  834. plater_id = int(value)
  835. except ValueError:
  836. pass # Skip plate with unparseable ID
  837. elif key == "plater_name" and value:
  838. plater_name = value.strip()
  839. if plater_id is not None and plater_name:
  840. plate_names[plater_id] = plater_name
  841. except Exception:
  842. pass # Plate names are optional; continue without them
  843. # Parse slice_info.config for plate metadata
  844. plate_metadata = {}
  845. if "Metadata/slice_info.config" in namelist:
  846. content = zf.read("Metadata/slice_info.config").decode()
  847. root = ET.fromstring(content)
  848. for plate_elem in root.findall(".//plate"):
  849. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  850. plate_index = None
  851. for meta in plate_elem.findall("metadata"):
  852. key = meta.get("key")
  853. value = meta.get("value")
  854. if key == "index" and value:
  855. try:
  856. plate_index = int(value)
  857. except ValueError:
  858. pass # Skip plate with unparseable index
  859. elif key == "prediction" and value:
  860. try:
  861. plate_info["prediction"] = int(value)
  862. except ValueError:
  863. pass # Skip unparseable prediction; leave as None
  864. elif key == "weight" and value:
  865. try:
  866. plate_info["weight"] = float(value)
  867. except ValueError:
  868. pass # Skip unparseable weight; leave as None
  869. # Get filaments used in this plate
  870. for filament_elem in plate_elem.findall("filament"):
  871. filament_id = filament_elem.get("id")
  872. filament_type = filament_elem.get("type", "")
  873. filament_color = filament_elem.get("color", "")
  874. used_g = filament_elem.get("used_g", "0")
  875. used_m = filament_elem.get("used_m", "0")
  876. try:
  877. used_grams = float(used_g)
  878. except (ValueError, TypeError):
  879. used_grams = 0
  880. if used_grams > 0 and filament_id:
  881. plate_info["filaments"].append(
  882. {
  883. "slot_id": int(filament_id),
  884. "type": filament_type,
  885. "color": filament_color,
  886. "used_grams": round(used_grams, 1),
  887. "used_meters": float(used_m) if used_m else 0,
  888. }
  889. )
  890. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  891. # Collect object names
  892. for obj_elem in plate_elem.findall("object"):
  893. obj_name = obj_elem.get("name")
  894. if obj_name and obj_name not in plate_info["objects"]:
  895. plate_info["objects"].append(obj_name)
  896. # Set plate name
  897. if plate_index is not None:
  898. custom_name = plate_names.get(plate_index)
  899. if custom_name:
  900. plate_info["name"] = custom_name
  901. elif plate_info["objects"]:
  902. plate_info["name"] = plate_info["objects"][0]
  903. plate_metadata[plate_index] = plate_info
  904. # Parse plate_*.json for object lists when slice_info is missing
  905. plate_json_objects: dict[int, list[str]] = {}
  906. for name in namelist:
  907. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  908. if not match:
  909. continue
  910. try:
  911. plate_index = int(match.group(1))
  912. except ValueError:
  913. continue
  914. try:
  915. payload = json.loads(zf.read(name).decode())
  916. bbox_objects = payload.get("bbox_objects", [])
  917. names: list[str] = []
  918. for obj in bbox_objects:
  919. obj_name = obj.get("name") if isinstance(obj, dict) else None
  920. if obj_name and obj_name not in names:
  921. names.append(obj_name)
  922. if names:
  923. plate_json_objects[plate_index] = names
  924. except Exception:
  925. continue
  926. # Build plate list
  927. for idx in plate_indices:
  928. meta = plate_metadata.get(idx, {})
  929. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  930. objects = meta.get("objects", [])
  931. if not objects:
  932. objects = plate_json_objects.get(idx, [])
  933. plate_name = meta.get("name")
  934. if not plate_name:
  935. plate_name = plate_names.get(idx)
  936. if not plate_name and objects:
  937. plate_name = objects[0]
  938. plates.append(
  939. {
  940. "index": idx,
  941. "name": plate_name,
  942. "objects": objects,
  943. "object_count": len(objects),
  944. "has_thumbnail": has_thumbnail,
  945. "thumbnail_url": f"/api/v1/printers/{printer_id}/files/plate-thumbnail/{idx}?path={path}",
  946. "print_time_seconds": meta.get("prediction"),
  947. "filament_used_grams": meta.get("weight"),
  948. "filaments": meta.get("filaments", []),
  949. }
  950. )
  951. except Exception as e:
  952. logger.warning("Failed to parse plates from printer file %s: %s", path, e)
  953. return {
  954. "printer_id": printer_id,
  955. "path": path,
  956. "filename": filename,
  957. "plates": plates,
  958. "is_multi_plate": len(plates) > 1,
  959. }
  960. @router.get("/{printer_id}/files/plate-thumbnail/{plate_index}")
  961. async def get_printer_file_plate_thumbnail(
  962. printer_id: int,
  963. plate_index: int,
  964. path: str = Query(..., description="Full path to the 3MF file on the printer"),
  965. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  966. db: AsyncSession = Depends(get_db),
  967. ):
  968. """Get a plate thumbnail image from a printer-stored 3MF file."""
  969. import io
  970. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  971. printer = result.scalar_one_or_none()
  972. if not printer:
  973. raise HTTPException(404, "Printer not found")
  974. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  975. if data is None:
  976. raise HTTPException(404, f"File not found: {path}")
  977. try:
  978. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  979. thumb_path = f"Metadata/plate_{plate_index}.png"
  980. if thumb_path in zf.namelist():
  981. image_data = zf.read(thumb_path)
  982. return Response(content=image_data, media_type="image/png")
  983. except Exception:
  984. pass # Corrupt or unreadable 3MF; fall through to 404
  985. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  986. @router.post("/{printer_id}/files/download-zip")
  987. async def download_printer_files_as_zip(
  988. printer_id: int,
  989. request: dict,
  990. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  991. db: AsyncSession = Depends(get_db),
  992. ):
  993. """Download multiple files from the printer as a ZIP archive."""
  994. import io
  995. paths = request.get("paths", [])
  996. if not paths:
  997. raise HTTPException(400, "No files specified")
  998. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  999. printer = result.scalar_one_or_none()
  1000. if not printer:
  1001. raise HTTPException(404, "Printer not found")
  1002. # Create ZIP in memory
  1003. zip_buffer = io.BytesIO()
  1004. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  1005. for path in paths:
  1006. try:
  1007. data = await download_file_bytes_async(
  1008. printer.ip_address, printer.access_code, path, printer_model=printer.model
  1009. )
  1010. if data:
  1011. filename = path.split("/")[-1]
  1012. zf.writestr(filename, data)
  1013. except Exception as e:
  1014. logging.warning("Failed to add %s to ZIP: %s", path, e)
  1015. continue
  1016. zip_buffer.seek(0)
  1017. zip_data = zip_buffer.read()
  1018. if len(zip_data) == 0:
  1019. raise HTTPException(404, "No files could be downloaded")
  1020. return Response(
  1021. content=zip_data,
  1022. media_type="application/zip",
  1023. headers={"Content-Disposition": 'attachment; filename="printer-files.zip"'},
  1024. )
  1025. @router.delete("/{printer_id}/files")
  1026. async def delete_printer_file(
  1027. printer_id: int,
  1028. path: str,
  1029. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1030. db: AsyncSession = Depends(get_db),
  1031. ):
  1032. """Delete a file from the printer."""
  1033. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1034. printer = result.scalar_one_or_none()
  1035. if not printer:
  1036. raise HTTPException(404, "Printer not found")
  1037. success = await delete_file_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1038. if not success:
  1039. raise HTTPException(500, f"Failed to delete file: {path}")
  1040. return {"status": "deleted", "path": path}
  1041. @router.get("/{printer_id}/storage")
  1042. async def get_printer_storage(
  1043. printer_id: int,
  1044. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1045. db: AsyncSession = Depends(get_db),
  1046. ):
  1047. """Get storage information from the printer."""
  1048. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1049. printer = result.scalar_one_or_none()
  1050. if not printer:
  1051. raise HTTPException(404, "Printer not found")
  1052. storage_info = await get_storage_info_async(printer.ip_address, printer.access_code, printer_model=printer.model)
  1053. return storage_info or {"used_bytes": None, "free_bytes": None}
  1054. # ============================================
  1055. # MQTT Debug Logging Endpoints
  1056. # ============================================
  1057. @router.post("/{printer_id}/logging/enable")
  1058. async def enable_mqtt_logging(
  1059. printer_id: int,
  1060. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1061. db: AsyncSession = Depends(get_db),
  1062. ):
  1063. """Enable MQTT message logging for a printer."""
  1064. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1065. printer = result.scalar_one_or_none()
  1066. if not printer:
  1067. raise HTTPException(404, "Printer not found")
  1068. success = printer_manager.enable_logging(printer_id, True)
  1069. if not success:
  1070. raise HTTPException(400, "Printer not connected")
  1071. return {"logging_enabled": True}
  1072. @router.post("/{printer_id}/logging/disable")
  1073. async def disable_mqtt_logging(
  1074. printer_id: int,
  1075. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1076. db: AsyncSession = Depends(get_db),
  1077. ):
  1078. """Disable MQTT message logging for a printer."""
  1079. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1080. printer = result.scalar_one_or_none()
  1081. if not printer:
  1082. raise HTTPException(404, "Printer not found")
  1083. success = printer_manager.enable_logging(printer_id, False)
  1084. if not success:
  1085. raise HTTPException(400, "Printer not connected")
  1086. return {"logging_enabled": False}
  1087. @router.get("/{printer_id}/logging")
  1088. async def get_mqtt_logs(
  1089. printer_id: int,
  1090. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1091. db: AsyncSession = Depends(get_db),
  1092. ):
  1093. """Get MQTT message logs for a printer."""
  1094. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1095. printer = result.scalar_one_or_none()
  1096. if not printer:
  1097. raise HTTPException(404, "Printer not found")
  1098. logs = printer_manager.get_logs(printer_id)
  1099. return {
  1100. "logging_enabled": printer_manager.is_logging_enabled(printer_id),
  1101. "logs": [
  1102. {
  1103. "timestamp": log.timestamp,
  1104. "topic": log.topic,
  1105. "direction": log.direction,
  1106. "payload": log.payload,
  1107. }
  1108. for log in logs
  1109. ],
  1110. }
  1111. @router.delete("/{printer_id}/logging")
  1112. async def clear_mqtt_logs(
  1113. printer_id: int,
  1114. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1115. db: AsyncSession = Depends(get_db),
  1116. ):
  1117. """Clear MQTT message logs for a printer."""
  1118. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1119. printer = result.scalar_one_or_none()
  1120. if not printer:
  1121. raise HTTPException(404, "Printer not found")
  1122. printer_manager.clear_logs(printer_id)
  1123. return {"status": "cleared"}
  1124. # ============================================
  1125. # Print Options (AI Detection) Endpoints
  1126. # ============================================
  1127. @router.post("/{printer_id}/print-options")
  1128. async def set_print_option(
  1129. printer_id: int,
  1130. module_name: str,
  1131. enabled: bool,
  1132. print_halt: bool = True,
  1133. sensitivity: str = "medium",
  1134. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1135. db: AsyncSession = Depends(get_db),
  1136. ):
  1137. """Set an AI detection / print option on the printer.
  1138. Valid module_name values:
  1139. - spaghetti_detector: Spaghetti detection
  1140. - first_layer_inspector: First layer inspection
  1141. - printing_monitor: AI print quality monitoring
  1142. - buildplate_marker_detector: Build plate marker detection
  1143. - allow_skip_parts: Allow skipping failed parts
  1144. """
  1145. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1146. printer = result.scalar_one_or_none()
  1147. if not printer:
  1148. raise HTTPException(404, "Printer not found")
  1149. client = printer_manager.get_client(printer_id)
  1150. if not client or not client.state.connected:
  1151. raise HTTPException(400, "Printer not connected")
  1152. # Validate module_name
  1153. valid_modules = [
  1154. "spaghetti_detector",
  1155. "first_layer_inspector",
  1156. "printing_monitor",
  1157. "buildplate_marker_detector",
  1158. "allow_skip_parts",
  1159. "pileup_detector",
  1160. "clump_detector",
  1161. "airprint_detector",
  1162. "auto_recovery_step_loss",
  1163. ]
  1164. if module_name not in valid_modules:
  1165. raise HTTPException(400, f"Invalid module_name. Must be one of: {valid_modules}")
  1166. # Validate sensitivity
  1167. valid_sensitivities = ["low", "medium", "high", "never_halt"]
  1168. if sensitivity not in valid_sensitivities:
  1169. raise HTTPException(400, f"Invalid sensitivity. Must be one of: {valid_sensitivities}")
  1170. success = client.set_xcam_option(
  1171. module_name=module_name,
  1172. enabled=enabled,
  1173. print_halt=print_halt,
  1174. sensitivity=sensitivity,
  1175. )
  1176. if not success:
  1177. raise HTTPException(500, "Failed to send command to printer")
  1178. return {
  1179. "success": True,
  1180. "module_name": module_name,
  1181. "enabled": enabled,
  1182. "print_halt": print_halt,
  1183. "sensitivity": sensitivity,
  1184. }
  1185. # ============================================
  1186. # Calibration
  1187. # ============================================
  1188. @router.post("/{printer_id}/calibration")
  1189. async def start_calibration(
  1190. printer_id: int,
  1191. bed_leveling: bool = False,
  1192. vibration: bool = False,
  1193. motor_noise: bool = False,
  1194. nozzle_offset: bool = False,
  1195. high_temp_heatbed: bool = False,
  1196. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1197. db: AsyncSession = Depends(get_db),
  1198. ):
  1199. """Start printer calibration with selected options.
  1200. At least one option must be selected.
  1201. Options:
  1202. - bed_leveling: Run bed leveling calibration
  1203. - vibration: Run vibration compensation calibration
  1204. - motor_noise: Run motor noise cancellation calibration
  1205. - nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  1206. - high_temp_heatbed: Run high-temperature heatbed calibration
  1207. """
  1208. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1209. printer = result.scalar_one_or_none()
  1210. if not printer:
  1211. raise HTTPException(404, "Printer not found")
  1212. client = printer_manager.get_client(printer_id)
  1213. if not client or not client.state.connected:
  1214. raise HTTPException(400, "Printer not connected")
  1215. # Check that at least one option is selected
  1216. if not any([bed_leveling, vibration, motor_noise, nozzle_offset, high_temp_heatbed]):
  1217. raise HTTPException(400, "At least one calibration option must be selected")
  1218. success = client.start_calibration(
  1219. bed_leveling=bed_leveling,
  1220. vibration=vibration,
  1221. motor_noise=motor_noise,
  1222. nozzle_offset=nozzle_offset,
  1223. high_temp_heatbed=high_temp_heatbed,
  1224. )
  1225. if not success:
  1226. raise HTTPException(500, "Failed to send calibration command to printer")
  1227. return {
  1228. "success": True,
  1229. "bed_leveling": bed_leveling,
  1230. "vibration": vibration,
  1231. "motor_noise": motor_noise,
  1232. "nozzle_offset": nozzle_offset,
  1233. "high_temp_heatbed": high_temp_heatbed,
  1234. }
  1235. # ============================================================================
  1236. # Slot Preset Mapping Endpoints
  1237. # ============================================================================
  1238. @router.get("/{printer_id}/slot-presets")
  1239. async def get_slot_presets(
  1240. printer_id: int,
  1241. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1242. db: AsyncSession = Depends(get_db),
  1243. ):
  1244. """Get all saved slot-to-preset mappings for a printer."""
  1245. result = await db.execute(select(SlotPresetMapping).where(SlotPresetMapping.printer_id == printer_id))
  1246. mappings = result.scalars().all()
  1247. return {
  1248. mapping.ams_id * 4 + mapping.tray_id: {
  1249. "ams_id": mapping.ams_id,
  1250. "tray_id": mapping.tray_id,
  1251. "preset_id": mapping.preset_id,
  1252. "preset_name": mapping.preset_name,
  1253. }
  1254. for mapping in mappings
  1255. }
  1256. @router.get("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  1257. async def get_slot_preset(
  1258. printer_id: int,
  1259. ams_id: int,
  1260. tray_id: int,
  1261. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1262. db: AsyncSession = Depends(get_db),
  1263. ):
  1264. """Get the saved preset for a specific slot."""
  1265. result = await db.execute(
  1266. select(SlotPresetMapping).where(
  1267. SlotPresetMapping.printer_id == printer_id,
  1268. SlotPresetMapping.ams_id == ams_id,
  1269. SlotPresetMapping.tray_id == tray_id,
  1270. )
  1271. )
  1272. mapping = result.scalar_one_or_none()
  1273. if not mapping:
  1274. return None
  1275. return {
  1276. "ams_id": mapping.ams_id,
  1277. "tray_id": mapping.tray_id,
  1278. "preset_id": mapping.preset_id,
  1279. "preset_name": mapping.preset_name,
  1280. }
  1281. @router.put("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  1282. async def save_slot_preset(
  1283. printer_id: int,
  1284. ams_id: int,
  1285. tray_id: int,
  1286. preset_id: str,
  1287. preset_name: str,
  1288. preset_source: str = "cloud",
  1289. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  1290. db: AsyncSession = Depends(get_db),
  1291. ):
  1292. """Save a preset mapping for a specific slot."""
  1293. # Check printer exists
  1294. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1295. if not result.scalar_one_or_none():
  1296. raise HTTPException(404, "Printer not found")
  1297. # Check for existing mapping
  1298. result = await db.execute(
  1299. select(SlotPresetMapping).where(
  1300. SlotPresetMapping.printer_id == printer_id,
  1301. SlotPresetMapping.ams_id == ams_id,
  1302. SlotPresetMapping.tray_id == tray_id,
  1303. )
  1304. )
  1305. mapping = result.scalar_one_or_none()
  1306. if mapping:
  1307. # Update existing
  1308. mapping.preset_id = preset_id
  1309. mapping.preset_name = preset_name
  1310. mapping.preset_source = preset_source
  1311. else:
  1312. # Create new
  1313. mapping = SlotPresetMapping(
  1314. printer_id=printer_id,
  1315. ams_id=ams_id,
  1316. tray_id=tray_id,
  1317. preset_id=preset_id,
  1318. preset_name=preset_name,
  1319. preset_source=preset_source,
  1320. )
  1321. db.add(mapping)
  1322. await db.commit()
  1323. await db.refresh(mapping)
  1324. return {
  1325. "ams_id": mapping.ams_id,
  1326. "tray_id": mapping.tray_id,
  1327. "preset_id": mapping.preset_id,
  1328. "preset_name": mapping.preset_name,
  1329. "preset_source": mapping.preset_source,
  1330. }
  1331. @router.delete("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  1332. async def delete_slot_preset(
  1333. printer_id: int,
  1334. ams_id: int,
  1335. tray_id: int,
  1336. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  1337. db: AsyncSession = Depends(get_db),
  1338. ):
  1339. """Delete a saved preset mapping for a slot."""
  1340. result = await db.execute(
  1341. select(SlotPresetMapping).where(
  1342. SlotPresetMapping.printer_id == printer_id,
  1343. SlotPresetMapping.ams_id == ams_id,
  1344. SlotPresetMapping.tray_id == tray_id,
  1345. )
  1346. )
  1347. mapping = result.scalar_one_or_none()
  1348. if mapping:
  1349. await db.delete(mapping)
  1350. await db.commit()
  1351. return {"success": True}
  1352. @router.post("/{printer_id}/slots/{ams_id}/{tray_id}/configure")
  1353. async def configure_ams_slot(
  1354. printer_id: int,
  1355. ams_id: int,
  1356. tray_id: int,
  1357. tray_info_idx: str = Query(...),
  1358. tray_type: str = Query(...),
  1359. tray_sub_brands: str = Query(...),
  1360. tray_color: str = Query(...),
  1361. nozzle_temp_min: int = Query(...),
  1362. nozzle_temp_max: int = Query(...),
  1363. cali_idx: int = Query(-1),
  1364. nozzle_diameter: str = Query("0.4"),
  1365. setting_id: str = Query(""),
  1366. kprofile_filament_id: str = Query(""),
  1367. kprofile_setting_id: str = Query(""),
  1368. k_value: float = Query(0.0),
  1369. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1370. ):
  1371. """Configure an AMS slot with a specific filament setting and K profile.
  1372. This sends two commands to the printer:
  1373. 1. ams_filament_setting - sets filament type, color, temperature
  1374. 2. extrusion_cali_sel - sets the K profile (pressure advance value)
  1375. Args:
  1376. printer_id: Database ID of the printer
  1377. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  1378. tray_id: Tray ID within the AMS (0-3)
  1379. tray_info_idx: Filament ID short format (e.g., "GFL05") or user preset ID
  1380. tray_type: Filament type (e.g., "PLA", "PETG")
  1381. tray_sub_brands: Sub-brand/profile name (e.g., "PLA Basic", "PETG HF")
  1382. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  1383. nozzle_temp_min: Minimum nozzle temperature
  1384. nozzle_temp_max: Maximum nozzle temperature
  1385. cali_idx: K profile calibration index (-1 for default 0.020)
  1386. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  1387. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  1388. kprofile_filament_id: K profile's filament_id for proper K profile linking
  1389. k_value: Direct K value to set (0.0 to skip direct K value setting)
  1390. """
  1391. logger = logging.getLogger(__name__)
  1392. logger.info("[configure_ams_slot] printer_id=%s, ams_id=%s, tray_id=%s", printer_id, ams_id, tray_id)
  1393. logger.info(
  1394. f"[configure_ams_slot] tray_info_idx={tray_info_idx!r}, tray_type={tray_type!r}, tray_sub_brands={tray_sub_brands!r}"
  1395. )
  1396. logger.info(
  1397. f"[configure_ams_slot] setting_id={setting_id!r}, kprofile_filament_id={kprofile_filament_id!r}, kprofile_setting_id={kprofile_setting_id!r}"
  1398. )
  1399. # Get MQTT client for this printer
  1400. client = printer_manager.get_client(printer_id)
  1401. if not client:
  1402. raise HTTPException(status_code=400, detail="Printer not connected")
  1403. # Send the filament setting command (type, color, temp)
  1404. success = client.ams_set_filament_setting(
  1405. ams_id=ams_id,
  1406. tray_id=tray_id,
  1407. tray_info_idx=tray_info_idx,
  1408. tray_type=tray_type,
  1409. tray_sub_brands=tray_sub_brands,
  1410. tray_color=tray_color,
  1411. nozzle_temp_min=nozzle_temp_min,
  1412. nozzle_temp_max=nozzle_temp_max,
  1413. setting_id=setting_id,
  1414. )
  1415. if not success:
  1416. raise HTTPException(status_code=500, detail="Failed to send filament configuration command")
  1417. # Send the calibration/K-profile commands
  1418. # Use the K profile's filament_id if provided, otherwise use tray_info_idx
  1419. filament_id_for_kprofile = kprofile_filament_id if kprofile_filament_id else tray_info_idx
  1420. # Method 1: Select existing calibration profile by cali_idx
  1421. # IMPORTANT: Only pass setting_id if the K profile itself has one (from kprofile_setting_id)
  1422. # Do NOT use the preset's setting_id as fallback - it breaks the K profile linking in the slicer
  1423. client.extrusion_cali_sel(
  1424. ams_id=ams_id,
  1425. tray_id=tray_id,
  1426. cali_idx=cali_idx,
  1427. filament_id=filament_id_for_kprofile,
  1428. nozzle_diameter=nozzle_diameter,
  1429. setting_id=kprofile_setting_id if kprofile_setting_id else None,
  1430. )
  1431. # Method 2: Also directly set the K value if provided (for better compatibility)
  1432. if k_value > 0:
  1433. # Calculate global tray ID for extrusion_cali_set
  1434. if ams_id <= 3:
  1435. global_tray_id = ams_id * 4 + tray_id
  1436. elif ams_id >= 128 and ams_id <= 135:
  1437. global_tray_id = (ams_id - 128) * 4 + tray_id
  1438. else:
  1439. global_tray_id = tray_id
  1440. client.extrusion_cali_set(
  1441. tray_id=global_tray_id,
  1442. k_value=k_value,
  1443. n_coef=0.0,
  1444. nozzle_diameter=nozzle_diameter,
  1445. bed_temp=60,
  1446. nozzle_temp=nozzle_temp_max,
  1447. max_volumetric_speed=20.0,
  1448. )
  1449. # Request fresh status push from printer so frontend gets updated data via WebSocket
  1450. logger.info("[configure_ams_slot] Requesting status update from printer")
  1451. update_result = client.request_status_update()
  1452. logger.info("[configure_ams_slot] Status update request result: %s", update_result)
  1453. return {
  1454. "success": True,
  1455. "message": f"Configured AMS {ams_id} tray {tray_id} with {tray_sub_brands}",
  1456. }
  1457. @router.post("/{printer_id}/ams/{ams_id}/tray/{tray_id}/reset")
  1458. async def reset_ams_slot(
  1459. printer_id: int,
  1460. ams_id: int,
  1461. tray_id: int,
  1462. db: AsyncSession = Depends(get_db),
  1463. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1464. ):
  1465. """Reset an AMS slot to empty/unconfigured state.
  1466. This clears the filament configuration from the slot.
  1467. """
  1468. # Get MQTT client for this printer
  1469. client = printer_manager.get_client(printer_id)
  1470. if not client:
  1471. raise HTTPException(status_code=400, detail="Printer not connected")
  1472. # Reset the slot
  1473. success = client.reset_ams_slot(ams_id=ams_id, tray_id=tray_id)
  1474. if not success:
  1475. raise HTTPException(status_code=500, detail="Failed to send reset command")
  1476. # Also delete any saved slot preset mapping
  1477. result = await db.execute(
  1478. select(SlotPresetMapping).where(
  1479. SlotPresetMapping.printer_id == printer_id,
  1480. SlotPresetMapping.ams_id == ams_id,
  1481. SlotPresetMapping.tray_id == tray_id,
  1482. )
  1483. )
  1484. mapping = result.scalar_one_or_none()
  1485. if mapping:
  1486. await db.delete(mapping)
  1487. await db.commit()
  1488. # Request fresh status push from printer so frontend gets updated data via WebSocket
  1489. client.request_status_update()
  1490. return {
  1491. "success": True,
  1492. "message": f"Reset AMS {ams_id} tray {tray_id}",
  1493. }
  1494. @router.post("/{printer_id}/debug/simulate-print-complete")
  1495. async def debug_simulate_print_complete(
  1496. printer_id: int,
  1497. db: AsyncSession = Depends(get_db),
  1498. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1499. ):
  1500. """DEBUG: Simulate print completion to test freeze behavior.
  1501. This triggers the same code path as a real print completion,
  1502. without needing to wait for an actual print to finish.
  1503. """
  1504. from backend.app.main import _active_prints, on_print_complete
  1505. from backend.app.models.archive import PrintArchive
  1506. # Get the most recent archive for this printer
  1507. result = await db.execute(
  1508. select(PrintArchive)
  1509. .where(PrintArchive.printer_id == printer_id)
  1510. .order_by(PrintArchive.created_at.desc())
  1511. .limit(1)
  1512. )
  1513. archive = result.scalar_one_or_none()
  1514. if not archive:
  1515. raise HTTPException(status_code=404, detail="No archives found for this printer")
  1516. # Register this archive as "active" so on_print_complete can find it
  1517. filename = archive.file_path.split("/")[-1] if archive.file_path else "test.3mf"
  1518. subtask_name = archive.print_name or "Test Print"
  1519. _active_prints[(printer_id, filename)] = archive.id
  1520. _active_prints[(printer_id, subtask_name)] = archive.id
  1521. # Simulate print completion data
  1522. data = {
  1523. "status": "completed",
  1524. "filename": filename,
  1525. "subtask_name": subtask_name,
  1526. "timelapse_was_active": False,
  1527. }
  1528. logger.info("Simulating print complete for printer %s, archive %s", printer_id, archive.id)
  1529. # Call the actual on_print_complete handler
  1530. await on_print_complete(printer_id, data)
  1531. return {"success": True, "archive_id": archive.id, "message": "Print completion simulated"}
  1532. # =============================================================================
  1533. # Print Control Endpoints
  1534. # =============================================================================
  1535. @router.post("/{printer_id}/print/stop")
  1536. async def stop_print(
  1537. printer_id: int,
  1538. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1539. db: AsyncSession = Depends(get_db),
  1540. ):
  1541. """Stop/cancel the current print job."""
  1542. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1543. printer = result.scalar_one_or_none()
  1544. if not printer:
  1545. raise HTTPException(404, "Printer not found")
  1546. client = printer_manager.get_client(printer_id)
  1547. if not client:
  1548. raise HTTPException(400, "Printer not connected")
  1549. success = client.stop_print()
  1550. if not success:
  1551. raise HTTPException(500, "Failed to stop print")
  1552. return {"success": True, "message": "Print stop command sent"}
  1553. @router.post("/{printer_id}/clear-plate")
  1554. async def clear_plate(
  1555. printer_id: int,
  1556. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1557. db: AsyncSession = Depends(get_db),
  1558. ):
  1559. """Acknowledge that the build plate has been cleared after a finished/failed print.
  1560. Sets a plate-cleared flag so the scheduler can start the next queued print.
  1561. No MQTT command is sent to the printer — the scheduler's start_print command
  1562. will override the FINISH/FAILED state when it sends the next job.
  1563. """
  1564. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1565. printer = result.scalar_one_or_none()
  1566. if not printer:
  1567. raise HTTPException(404, "Printer not found")
  1568. if not printer_manager.is_connected(printer_id):
  1569. raise HTTPException(400, "Printer not connected")
  1570. state = printer_manager.get_status(printer_id)
  1571. if not state or state.state not in ("FINISH", "FAILED"):
  1572. raise HTTPException(
  1573. 400, f"Printer is not in FINISH or FAILED state (current: {state.state if state else 'unknown'})"
  1574. )
  1575. printer_manager.set_plate_cleared(printer_id)
  1576. return {"success": True, "message": "Plate cleared, next print will start shortly"}
  1577. @router.post("/{printer_id}/print/pause")
  1578. async def pause_print(
  1579. printer_id: int,
  1580. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1581. db: AsyncSession = Depends(get_db),
  1582. ):
  1583. """Pause the current print job."""
  1584. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1585. printer = result.scalar_one_or_none()
  1586. if not printer:
  1587. raise HTTPException(404, "Printer not found")
  1588. client = printer_manager.get_client(printer_id)
  1589. if not client:
  1590. raise HTTPException(400, "Printer not connected")
  1591. success = client.pause_print()
  1592. if not success:
  1593. raise HTTPException(500, "Failed to pause print")
  1594. return {"success": True, "message": "Print pause command sent"}
  1595. @router.post("/{printer_id}/print/resume")
  1596. async def resume_print(
  1597. printer_id: int,
  1598. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1599. db: AsyncSession = Depends(get_db),
  1600. ):
  1601. """Resume a paused print job."""
  1602. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1603. printer = result.scalar_one_or_none()
  1604. if not printer:
  1605. raise HTTPException(404, "Printer not found")
  1606. client = printer_manager.get_client(printer_id)
  1607. if not client:
  1608. raise HTTPException(400, "Printer not connected")
  1609. success = client.resume_print()
  1610. if not success:
  1611. raise HTTPException(500, "Failed to resume print")
  1612. return {"success": True, "message": "Print resume command sent"}
  1613. @router.post("/{printer_id}/chamber-light")
  1614. async def set_chamber_light(
  1615. printer_id: int,
  1616. on: bool = Query(..., description="True to turn on, False to turn off"),
  1617. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1618. db: AsyncSession = Depends(get_db),
  1619. ):
  1620. """Turn the chamber light on or off."""
  1621. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1622. printer = result.scalar_one_or_none()
  1623. if not printer:
  1624. raise HTTPException(404, "Printer not found")
  1625. client = printer_manager.get_client(printer_id)
  1626. if not client:
  1627. raise HTTPException(400, "Printer not connected")
  1628. success = client.set_chamber_light(on)
  1629. if not success:
  1630. raise HTTPException(500, "Failed to control chamber light")
  1631. return {"success": True, "message": f"Chamber light {'on' if on else 'off'}"}
  1632. @router.get("/{printer_id}/print/objects")
  1633. async def get_printable_objects(
  1634. printer_id: int,
  1635. reload: bool = False,
  1636. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1637. db: AsyncSession = Depends(get_db),
  1638. ):
  1639. """Get the list of printable objects for the current print.
  1640. Returns a list of objects with id, name, position (if available), and skip status.
  1641. Objects that have already been skipped are marked in the skipped_objects list.
  1642. Args:
  1643. reload: If True, reload objects from the archive file (useful after restart)
  1644. """
  1645. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1646. printer = result.scalar_one_or_none()
  1647. if not printer:
  1648. raise HTTPException(404, "Printer not found")
  1649. client = printer_manager.get_client(printer_id)
  1650. if not client:
  1651. raise HTTPException(400, "Printer not connected")
  1652. # Reload objects from 3MF if requested or no objects loaded
  1653. if reload or not client.state.printable_objects:
  1654. subtask_name = client.state.subtask_name
  1655. if subtask_name:
  1656. from backend.app.services.archive import extract_printable_objects_from_3mf
  1657. from backend.app.services.bambu_ftp import download_file_try_paths_async
  1658. # Build possible 3MF filenames (try both .gcode.3mf and .3mf)
  1659. possible_filenames = []
  1660. if subtask_name.endswith(".3mf"):
  1661. possible_filenames.append(subtask_name)
  1662. else:
  1663. possible_filenames.append(f"{subtask_name}.gcode.3mf")
  1664. possible_filenames.append(f"{subtask_name}.3mf")
  1665. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  1666. if " " in subtask_name:
  1667. normalized = subtask_name.replace(" ", "_")
  1668. if normalized.endswith(".3mf"):
  1669. possible_filenames.append(normalized)
  1670. else:
  1671. possible_filenames.append(f"{normalized}.gcode.3mf")
  1672. possible_filenames.append(f"{normalized}.3mf")
  1673. # Download 3MF from printer
  1674. temp_path = settings.archive_dir / "temp" / f"objects_{printer_id}_{possible_filenames[0]}"
  1675. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1676. # Build list of all remote paths to try
  1677. remote_paths = []
  1678. for filename in possible_filenames:
  1679. remote_paths.extend([f"/{filename}", f"/cache/{filename}", f"/model/{filename}"])
  1680. try:
  1681. downloaded = await download_file_try_paths_async(
  1682. printer.ip_address,
  1683. printer.access_code,
  1684. remote_paths,
  1685. temp_path,
  1686. printer_model=printer.model,
  1687. )
  1688. if downloaded and temp_path.exists():
  1689. with open(temp_path, "rb") as f:
  1690. data = f.read()
  1691. objects, bbox_all = extract_printable_objects_from_3mf(data, include_positions=True)
  1692. if objects:
  1693. client.state.printable_objects = objects
  1694. client.state.printable_objects_bbox_all = bbox_all
  1695. logger.info("Reloaded %s objects for printer %s", len(objects), printer_id)
  1696. except Exception as e:
  1697. logger.debug("Failed to reload objects from printer: %s", e)
  1698. finally:
  1699. if temp_path.exists():
  1700. temp_path.unlink()
  1701. # Return objects with their skip status and position data
  1702. objects = []
  1703. for obj_id, obj_data in client.state.printable_objects.items():
  1704. # Handle both old format (string name) and new format (dict with name, x, y)
  1705. if isinstance(obj_data, dict):
  1706. obj_entry = {
  1707. "id": obj_id,
  1708. "name": obj_data.get("name", f"Object {obj_id}"),
  1709. "x": obj_data.get("x"),
  1710. "y": obj_data.get("y"),
  1711. "skipped": obj_id in client.state.skipped_objects,
  1712. }
  1713. else:
  1714. # Legacy format: obj_data is just the name string
  1715. obj_entry = {
  1716. "id": obj_id,
  1717. "name": obj_data,
  1718. "x": None,
  1719. "y": None,
  1720. "skipped": obj_id in client.state.skipped_objects,
  1721. }
  1722. objects.append(obj_entry)
  1723. return {
  1724. "objects": objects,
  1725. "total": len(objects),
  1726. "skipped_count": len(client.state.skipped_objects),
  1727. "is_printing": client.state.state in ("RUNNING", "PAUSE"),
  1728. "bbox_all": getattr(client.state, "printable_objects_bbox_all", None),
  1729. }
  1730. @router.post("/{printer_id}/print/skip-objects")
  1731. async def skip_objects(
  1732. printer_id: int,
  1733. object_ids: list[int],
  1734. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1735. db: AsyncSession = Depends(get_db),
  1736. ):
  1737. """Skip specific objects during the current print.
  1738. Args:
  1739. object_ids: List of object identify_id values to skip
  1740. """
  1741. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1742. printer = result.scalar_one_or_none()
  1743. if not printer:
  1744. raise HTTPException(404, "Printer not found")
  1745. client = printer_manager.get_client(printer_id)
  1746. if not client:
  1747. raise HTTPException(400, "Printer not connected")
  1748. if not object_ids:
  1749. raise HTTPException(400, "No object IDs provided")
  1750. # Validate object IDs exist in printable_objects
  1751. invalid_ids = [oid for oid in object_ids if oid not in client.state.printable_objects]
  1752. if invalid_ids:
  1753. raise HTTPException(400, f"Invalid object IDs: {invalid_ids}")
  1754. success = client.skip_objects(object_ids)
  1755. if not success:
  1756. raise HTTPException(500, "Failed to skip objects")
  1757. # Get names of skipped objects for response (handle both old and new format)
  1758. skipped_names = []
  1759. for oid in object_ids:
  1760. obj_data = client.state.printable_objects.get(oid, str(oid))
  1761. if isinstance(obj_data, dict):
  1762. skipped_names.append(obj_data.get("name", str(oid)))
  1763. else:
  1764. skipped_names.append(obj_data)
  1765. return {
  1766. "success": True,
  1767. "message": f"Skipped {len(object_ids)} object(s): {', '.join(skipped_names)}",
  1768. "skipped_objects": object_ids,
  1769. }
  1770. # =============================================================================
  1771. # AMS Control Endpoints
  1772. # =============================================================================
  1773. @router.post("/{printer_id}/ams/{ams_id}/slot/{slot_id}/refresh")
  1774. async def refresh_ams_slot(
  1775. printer_id: int,
  1776. ams_id: int,
  1777. slot_id: int,
  1778. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_AMS_RFID),
  1779. db: AsyncSession = Depends(get_db),
  1780. ):
  1781. """Re-read RFID for an AMS slot (triggers filament info refresh)."""
  1782. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1783. printer = result.scalar_one_or_none()
  1784. if not printer:
  1785. raise HTTPException(404, "Printer not found")
  1786. client = printer_manager.get_client(printer_id)
  1787. if not client:
  1788. raise HTTPException(400, "Printer not connected")
  1789. success, message = client.ams_refresh_tray(ams_id, slot_id)
  1790. if not success:
  1791. raise HTTPException(400, message)
  1792. return {"success": True, "message": message}
  1793. @router.get("/{printer_id}/runtime-debug")
  1794. async def get_runtime_debug(
  1795. printer_id: int,
  1796. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1797. db: AsyncSession = Depends(get_db),
  1798. ):
  1799. """Debug endpoint: Get runtime tracking status for a printer."""
  1800. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1801. printer = result.scalar_one_or_none()
  1802. if not printer:
  1803. raise HTTPException(404, "Printer not found")
  1804. state = printer_manager.get_status(printer_id)
  1805. return {
  1806. "printer_name": printer.name,
  1807. "runtime_seconds": printer.runtime_seconds,
  1808. "runtime_hours": printer.runtime_seconds / 3600.0 if printer.runtime_seconds else 0,
  1809. "print_hours_offset": printer.print_hours_offset,
  1810. "total_hours": (printer.runtime_seconds / 3600.0 if printer.runtime_seconds else 0)
  1811. + (printer.print_hours_offset or 0),
  1812. "last_runtime_update": printer.last_runtime_update.isoformat() if printer.last_runtime_update else None,
  1813. "mqtt_state": {
  1814. "connected": state.connected if state else False,
  1815. "state": state.state if state else None,
  1816. "progress": state.progress if state else None,
  1817. "gcode_file": state.gcode_file if state else None,
  1818. }
  1819. if state
  1820. else None,
  1821. "is_active": printer.is_active,
  1822. }