printers.py 75 KB

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