kprofiles.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. """API routes for K-profile (pressure advance) management."""
  2. import asyncio
  3. import logging
  4. from fastapi import APIRouter, Depends, HTTPException
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.core.auth import RequirePrinterPermissionIfAuthEnabled
  8. from backend.app.core.database import get_db
  9. from backend.app.core.permissions import Permission
  10. from backend.app.models.kprofile_note import KProfileNote as KProfileNoteModel
  11. from backend.app.models.printer import Printer
  12. from backend.app.models.user import User
  13. from backend.app.schemas.kprofile import (
  14. KProfile,
  15. KProfileCreate,
  16. KProfileDelete,
  17. KProfileNote,
  18. KProfileNoteResponse,
  19. KProfilesResponse,
  20. )
  21. from backend.app.services.bambu_mqtt import CALI_ACK_UNCONFIRMED
  22. from backend.app.services.printer_manager import printer_manager
  23. logger = logging.getLogger(__name__)
  24. router = APIRouter(prefix="/printers/{printer_id}/kprofiles", tags=["kprofiles"])
  25. @router.get("/", response_model=KProfilesResponse)
  26. async def get_kprofiles(
  27. printer_id: int,
  28. nozzle_diameter: str = "0.4",
  29. db: AsyncSession = Depends(get_db),
  30. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.KPROFILES_READ),
  31. ):
  32. """Get K-profiles from a printer.
  33. Args:
  34. printer_id: ID of the printer
  35. nozzle_diameter: Filter by nozzle diameter (default: "0.4")
  36. """
  37. # Check printer exists
  38. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  39. printer = result.scalar_one_or_none()
  40. if not printer:
  41. raise HTTPException(404, "Printer not found")
  42. # Get MQTT client for printer
  43. client = printer_manager.get_client(printer_id)
  44. if not client or not client.state.connected:
  45. raise HTTPException(400, "Printer not connected")
  46. # Request K-profiles from printer
  47. profiles = await client.get_kprofiles(nozzle_diameter=nozzle_diameter)
  48. # Convert from MQTT dataclass to Pydantic schema
  49. return KProfilesResponse(
  50. profiles=[
  51. KProfile(
  52. slot_id=p.slot_id,
  53. extruder_id=p.extruder_id,
  54. nozzle_id=p.nozzle_id,
  55. nozzle_diameter=p.nozzle_diameter,
  56. filament_id=p.filament_id,
  57. name=p.name,
  58. k_value=p.k_value,
  59. n_coef=p.n_coef,
  60. ams_id=p.ams_id,
  61. tray_id=p.tray_id,
  62. setting_id=p.setting_id,
  63. )
  64. for p in profiles
  65. ],
  66. nozzle_diameter=nozzle_diameter,
  67. )
  68. @router.post("/", response_model=dict)
  69. async def set_kprofile(
  70. printer_id: int,
  71. profile: KProfileCreate,
  72. db: AsyncSession = Depends(get_db),
  73. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.KPROFILES_UPDATE),
  74. ):
  75. """Create or update a K-profile on the printer.
  76. For H2D edits (slot_id > 0), this performs an in-place edit using cali_idx.
  77. For other printers or new profiles, this adds a new profile.
  78. Args:
  79. printer_id: ID of the printer
  80. profile: K-profile data to set
  81. """
  82. is_edit = profile.slot_id > 0
  83. operation = "edit" if is_edit else "add"
  84. logger.info(
  85. f"[API] set_kprofile ({operation}): printer={printer_id}, slot_id={profile.slot_id}, "
  86. f"extruder_id={profile.extruder_id}, nozzle_id={profile.nozzle_id}, "
  87. f"name={profile.name}, filament_id={profile.filament_id}, k_value={profile.k_value}"
  88. )
  89. # Check printer exists
  90. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  91. printer = result.scalar_one_or_none()
  92. if not printer:
  93. raise HTTPException(404, "Printer not found")
  94. # Get MQTT client for printer
  95. client = printer_manager.get_client(printer_id)
  96. if not client or not client.state.connected:
  97. raise HTTPException(400, "Printer not connected")
  98. # Detect dual-nozzle for the in-place edit format. Runtime detection from
  99. # device.extruder.info beats serial-prefix heuristics — H2S shares prefix
  100. # "094" with H2D but is single-nozzle (#1386). Model name is the fallback
  101. # for the brief window after connect before push data arrives.
  102. from backend.app.utils.printer_models import is_dual_nozzle_model
  103. is_dual_nozzle = client._is_dual_nozzle or is_dual_nozzle_model(printer.model)
  104. # Whether the printer answered the delete of a delete-and-add edit.
  105. delete_confirmed = True
  106. if is_edit and is_dual_nozzle:
  107. # Dual-nozzle in-place edit: use cali_idx with slot_id=0 and empty setting_id
  108. logger.info("[API] Dual-nozzle in-place edit: cali_idx=%s", profile.slot_id)
  109. success = client.set_kprofile(
  110. filament_id=profile.filament_id,
  111. name=profile.name,
  112. k_value=profile.k_value,
  113. nozzle_diameter=profile.nozzle_diameter,
  114. nozzle_id=profile.nozzle_id,
  115. extruder_id=profile.extruder_id,
  116. setting_id=None,
  117. slot_id=0,
  118. cali_idx=profile.slot_id, # Pass the original slot for in-place edit
  119. )
  120. elif is_edit:
  121. # Single-nozzle edit: use delete + add approach
  122. logger.info("[API] Edit: deleting existing profile slot_id=%s", profile.slot_id)
  123. delete_success = client.delete_kprofile(
  124. cali_idx=profile.slot_id,
  125. filament_id=profile.filament_id,
  126. nozzle_id=profile.nozzle_id,
  127. nozzle_diameter=profile.nozzle_diameter,
  128. extruder_id=profile.extruder_id,
  129. setting_id=profile.setting_id,
  130. )
  131. if not delete_success:
  132. raise HTTPException(500, "Failed to delete existing K-profile for edit")
  133. ok, detail = await client.await_cali_ack(delete_success)
  134. if not ok:
  135. raise HTTPException(500, f"Printer rejected the K-profile edit: {detail}")
  136. delete_confirmed = detail != CALI_ACK_UNCONFIRMED
  137. # Wait for printer to process the delete before adding
  138. await asyncio.sleep(0.5)
  139. logger.info("[API] Edit: delete complete, now adding updated profile")
  140. success = client.set_kprofile(
  141. filament_id=profile.filament_id,
  142. name=profile.name,
  143. k_value=profile.k_value,
  144. nozzle_diameter=profile.nozzle_diameter,
  145. nozzle_id=profile.nozzle_id,
  146. extruder_id=profile.extruder_id,
  147. setting_id=None, # Generate new setting_id for add
  148. slot_id=0, # Always 0 for add (new profile)
  149. )
  150. else:
  151. # New profile: add with slot_id=0
  152. success = client.set_kprofile(
  153. filament_id=profile.filament_id,
  154. name=profile.name,
  155. k_value=profile.k_value,
  156. nozzle_diameter=profile.nozzle_diameter,
  157. nozzle_id=profile.nozzle_id,
  158. extruder_id=profile.extruder_id,
  159. setting_id=None, # Generate new setting_id for add
  160. slot_id=0, # Always 0 for add (new profile)
  161. )
  162. if not success:
  163. raise HTTPException(500, "Failed to send K-profile command")
  164. # The printer answers extrusion_cali_set with result/reason, echoing our
  165. # sequence_id. Until #2718 that answer was logged at DEBUG and discarded,
  166. # so a rejected write was reported to the user as saved.
  167. ok, detail = await client.await_cali_ack(success)
  168. if not ok:
  169. raise HTTPException(500, f"Printer rejected the K-profile: {detail}")
  170. confirmed = detail != CALI_ACK_UNCONFIRMED
  171. if is_edit and not is_dual_nozzle:
  172. # The edit deleted the profile and added it again: read the table back
  173. # to see the edited one landed. An empty table is also what a read that
  174. # timed out returns, so only a table without it is proof. Same pause as
  175. # before the add.
  176. await asyncio.sleep(0.5)
  177. table = await client.get_kprofiles(nozzle_diameter=profile.nozzle_diameter)
  178. if table:
  179. if not any(_is_saved_profile(stored, profile) for stored in table):
  180. raise HTTPException(
  181. 502,
  182. "The edited K-profile is not in the printer's table. Check the list before adding it again.",
  183. )
  184. # The old one may still be there when its delete went unanswered.
  185. confirmed = delete_confirmed
  186. if not confirmed:
  187. message = "K-profile sent; the printer did not confirm it"
  188. else:
  189. message = "K-profile updated successfully" if is_edit else "K-profile added successfully"
  190. return {"success": True, "confirmed": confirmed, "message": message}
  191. def _is_saved_profile(stored, profile: KProfileCreate) -> bool:
  192. """Whether a profile read from the printer is the one just written."""
  193. try:
  194. same_k = abs(float(stored.k_value) - float(profile.k_value)) < 1e-6
  195. except (TypeError, ValueError):
  196. return False
  197. return (
  198. same_k
  199. and stored.name == profile.name
  200. and stored.filament_id == profile.filament_id
  201. and stored.extruder_id == profile.extruder_id
  202. )
  203. @router.post("/batch", response_model=dict)
  204. async def set_kprofiles_batch(
  205. printer_id: int,
  206. profiles: list[KProfileCreate],
  207. db: AsyncSession = Depends(get_db),
  208. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.KPROFILES_UPDATE),
  209. ):
  210. """Create multiple K-profiles in a single command (for dual-nozzle).
  211. This sends all profiles in one MQTT command, which is more reliable
  212. for dual-nozzle printers that may not handle sequential commands well.
  213. Args:
  214. printer_id: ID of the printer
  215. profiles: List of K-profiles to set
  216. """
  217. if not profiles:
  218. raise HTTPException(400, "No profiles provided")
  219. logger.info("[API] set_kprofiles_batch: printer=%s, %s profiles", printer_id, len(profiles))
  220. for p in profiles:
  221. logger.info(" - extruder_id=%s, name=%s, k_value=%s", p.extruder_id, p.name, p.k_value)
  222. # Check printer exists
  223. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  224. printer = result.scalar_one_or_none()
  225. if not printer:
  226. raise HTTPException(404, "Printer not found")
  227. # Get MQTT client for printer
  228. client = printer_manager.get_client(printer_id)
  229. if not client or not client.state.connected:
  230. raise HTTPException(400, "Printer not connected")
  231. # Build list of profile dicts for batch command
  232. profile_dicts = [
  233. {
  234. "filament_id": p.filament_id,
  235. "name": p.name,
  236. "k_value": p.k_value,
  237. "nozzle_id": p.nozzle_id,
  238. "extruder_id": p.extruder_id,
  239. "setting_id": p.setting_id,
  240. "slot_id": p.slot_id,
  241. }
  242. for p in profiles
  243. ]
  244. # Get nozzle_diameter from first profile (all should have same)
  245. nozzle_diameter = profiles[0].nozzle_diameter
  246. success = client.set_kprofiles_batch(profile_dicts, nozzle_diameter)
  247. if not success:
  248. raise HTTPException(500, "Failed to send K-profiles batch command")
  249. ok, detail = await client.await_cali_ack(success)
  250. if not ok:
  251. raise HTTPException(500, f"Printer rejected the K-profiles: {detail}")
  252. return {
  253. "success": True,
  254. "confirmed": detail != CALI_ACK_UNCONFIRMED,
  255. "message": f"Added {len(profiles)} K-profiles",
  256. }
  257. @router.delete("/", response_model=dict)
  258. async def delete_kprofile(
  259. printer_id: int,
  260. profile: KProfileDelete,
  261. db: AsyncSession = Depends(get_db),
  262. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.KPROFILES_DELETE),
  263. ):
  264. """Delete a K-profile from the printer.
  265. Args:
  266. printer_id: ID of the printer
  267. profile: K-profile identification data for deletion
  268. """
  269. # Check printer exists
  270. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  271. printer = result.scalar_one_or_none()
  272. if not printer:
  273. raise HTTPException(404, "Printer not found")
  274. # Get MQTT client for printer
  275. client = printer_manager.get_client(printer_id)
  276. if not client or not client.state.connected:
  277. raise HTTPException(400, "Printer not connected")
  278. # Send the delete command to printer
  279. logger.info(
  280. f"[API] delete_kprofile: printer={printer_id}, slot_id={profile.slot_id}, "
  281. f"setting_id={profile.setting_id}, filament_id={profile.filament_id}"
  282. )
  283. success = client.delete_kprofile(
  284. cali_idx=profile.slot_id,
  285. filament_id=profile.filament_id,
  286. nozzle_id=profile.nozzle_id,
  287. nozzle_diameter=profile.nozzle_diameter,
  288. extruder_id=profile.extruder_id,
  289. setting_id=profile.setting_id,
  290. )
  291. if not success:
  292. raise HTTPException(500, "Failed to send K-profile delete command")
  293. ok, detail = await client.await_cali_ack(success)
  294. if not ok:
  295. raise HTTPException(500, f"Printer rejected the delete: {detail}")
  296. # Wait for printer to process the delete before frontend refetches
  297. await asyncio.sleep(0.5)
  298. return {"success": True, "confirmed": detail != CALI_ACK_UNCONFIRMED, "message": "K-profile deleted successfully"}
  299. @router.get("/notes", response_model=KProfileNoteResponse)
  300. async def get_kprofile_notes(
  301. printer_id: int,
  302. db: AsyncSession = Depends(get_db),
  303. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.KPROFILES_READ),
  304. ):
  305. """Get all K-profile notes for a printer.
  306. Notes are stored locally since printers don't support notes.
  307. Args:
  308. printer_id: ID of the printer
  309. """
  310. # Check printer exists
  311. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  312. printer = result.scalar_one_or_none()
  313. if not printer:
  314. raise HTTPException(404, "Printer not found")
  315. # Get all notes for this printer
  316. result = await db.execute(select(KProfileNoteModel).where(KProfileNoteModel.printer_id == printer_id))
  317. notes = result.scalars().all()
  318. # Return as a dictionary mapping setting_id -> note
  319. return KProfileNoteResponse(notes={note.setting_id: note.note for note in notes})
  320. @router.put("/notes", response_model=dict)
  321. async def set_kprofile_note(
  322. printer_id: int,
  323. note_data: KProfileNote,
  324. db: AsyncSession = Depends(get_db),
  325. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.KPROFILES_UPDATE),
  326. ):
  327. """Set or update a note for a K-profile.
  328. Args:
  329. printer_id: ID of the printer
  330. note_data: The note data (setting_id and note content)
  331. """
  332. # Check printer exists
  333. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  334. printer = result.scalar_one_or_none()
  335. if not printer:
  336. raise HTTPException(404, "Printer not found")
  337. # Find existing note or create new one
  338. result = await db.execute(
  339. select(KProfileNoteModel).where(
  340. KProfileNoteModel.printer_id == printer_id,
  341. KProfileNoteModel.setting_id == note_data.setting_id,
  342. )
  343. )
  344. existing_note = result.scalar_one_or_none()
  345. if note_data.note.strip():
  346. # Save or update note
  347. if existing_note:
  348. existing_note.note = note_data.note
  349. else:
  350. new_note = KProfileNoteModel(
  351. printer_id=printer_id,
  352. setting_id=note_data.setting_id,
  353. note=note_data.note,
  354. )
  355. db.add(new_note)
  356. await db.commit()
  357. return {"success": True, "message": "Note saved"}
  358. else:
  359. # Delete note if empty
  360. if existing_note:
  361. await db.delete(existing_note)
  362. await db.commit()
  363. return {"success": True, "message": "Note deleted"}
  364. @router.delete("/notes/{setting_id}", response_model=dict)
  365. async def delete_kprofile_note(
  366. printer_id: int,
  367. setting_id: str,
  368. db: AsyncSession = Depends(get_db),
  369. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.KPROFILES_DELETE),
  370. ):
  371. """Delete a note for a K-profile.
  372. Args:
  373. printer_id: ID of the printer
  374. setting_id: The setting_id of the K-profile
  375. """
  376. # Check printer exists
  377. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  378. printer = result.scalar_one_or_none()
  379. if not printer:
  380. raise HTTPException(404, "Printer not found")
  381. # Find and delete the note
  382. result = await db.execute(
  383. select(KProfileNoteModel).where(
  384. KProfileNoteModel.printer_id == printer_id,
  385. KProfileNoteModel.setting_id == setting_id,
  386. )
  387. )
  388. existing_note = result.scalar_one_or_none()
  389. if existing_note:
  390. await db.delete(existing_note)
  391. await db.commit()
  392. return {"success": True, "message": "Note deleted"}