printers.py 110 KB

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