slicer_filament_resolver.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. """Shared spool ``slicer_filament`` → ``(tray_info_idx, setting_id)`` resolver.
  2. The internal-inventory and Spoolman-inventory routes both need to translate
  3. a spool's stored slicer-preset reference (cloud preset ID / local preset ID /
  4. GF-prefix Bambu filament ID / free-text material name) into the two MQTT
  5. fields ``ams_filament_setting`` consumes: the printer-side ``tray_info_idx``
  6. (filament_id) and the slicer-side ``setting_id``. The two routes were drifting
  7. in lockstep before #1713 — internal mode resolved everything, Spoolman mode
  8. silently dropped slicer_filament on the floor and only the generic-material
  9. fallback fired. This module is the single chokepoint so the two flows can't
  10. diverge again.
  11. Resolver outcomes:
  12. - Returns ``("", "", None)`` when ``slicer_filament`` is empty, unresolvable,
  13. or sanitised away as a slicer-rejected value (literal material name,
  14. PFUS / PFCN cloud setting_id). The caller is responsible for the
  15. generic-material fallback when this happens.
  16. - Returns ``(tray_info_idx, setting_id, sub_brand_override)`` otherwise.
  17. The third element is non-empty when a cloud-detail lookup or a local-
  18. preset name provides a more specific brand label than the spool's own
  19. ``"<brand> <material> <subtype>"`` concatenation — the caller should
  20. prefer it over its computed default.
  21. The resolver is async because the GFS / PFUS / PFCN branches need cloud
  22. authentication and the local-preset branch reads ``LocalPreset`` from the
  23. DB. Pass ``current_user=None`` to skip cloud auth (the on_ams_change
  24. replay path uses this); cloud-prefix presets then fall back to a static
  25. ``normalize_slicer_filament`` parse, which is correct when the slot was
  26. already configured by an earlier authenticated assign and the printer's
  27. calibration table preserves the real filament_id.
  28. """
  29. from __future__ import annotations
  30. import json
  31. import logging
  32. from sqlalchemy import select
  33. from sqlalchemy.ext.asyncio import AsyncSession
  34. from backend.app.models.user import User
  35. from backend.app.utils.filament_ids import (
  36. GENERIC_FILAMENT_IDS,
  37. filament_id_to_setting_id,
  38. normalize_slicer_filament,
  39. )
  40. from backend.app.utils.filament_types import is_material_name
  41. logger = logging.getLogger(__name__)
  42. async def resolve_slicer_filament(
  43. *,
  44. db: AsyncSession,
  45. current_user: User | None,
  46. slicer_filament: str | None,
  47. slicer_filament_name: str | None,
  48. material: str | None,
  49. ) -> tuple[str, str, str | None]:
  50. """Resolve a spool's slicer-preset reference to printer-side ids.
  51. ``slicer_filament``: the spool's stored reference (e.g. ``"GFA01"``,
  52. ``"PFUS990b6e19965353"``, ``"38"`` for a numeric LocalPreset id, or
  53. free-text). May be empty or None — returns the empty tuple in that case.
  54. ``slicer_filament_name``: optional builtin-name realignment hint. When
  55. set and the resolved tray_info_idx maps to a different builtin name,
  56. the resolver swaps to the builtin whose name matches (e.g. user picked
  57. "Bambu PLA Matte" but the cloud lookup landed on "Bambu PLA Basic").
  58. ``material``: spool material string for the local-preset fallback
  59. branch when the LocalPreset's setting JSON doesn't carry a filament_id.
  60. Returns ``(tray_info_idx, setting_id, sub_brand_override)`` — all empty
  61. when nothing resolved. ``sub_brand_override`` is non-None when a more
  62. specific brand label is available (cloud detail name or local preset
  63. name); ``None`` means the caller should use its own default.
  64. """
  65. sf = (slicer_filament or "").strip()
  66. if not sf:
  67. return ("", "", None)
  68. tray_info_idx = ""
  69. setting_id = ""
  70. sub_brand_override: str | None = None
  71. base_sf = sf.split("_")[0] if "_" in sf else sf
  72. # Cloud-side preset IDs in three known shapes:
  73. # GFS… — Bambu official cloud preset
  74. # PFUS… — cloud user-created preset
  75. # PFCN… — cloud shared / partner preset (e.g. Polymaker's "(Custom)"
  76. # Bambu Lab H2D variant, #1648)
  77. # All three need a cloud-detail lookup to extract the underlying
  78. # filament_id; without it the raw cloud id ends up in tray_info_idx
  79. # and the printer's calibration table can't resolve it.
  80. if base_sf.startswith("GFS") or base_sf.startswith("PFUS") or base_sf.startswith("PFCN"):
  81. setting_id = base_sf
  82. try:
  83. from backend.app.api.routes.cloud import build_authenticated_cloud
  84. cloud = await build_authenticated_cloud(db, current_user)
  85. if cloud is not None and cloud.is_authenticated:
  86. try:
  87. detail = await cloud.get_setting_detail(base_sf)
  88. if detail.get("filament_id"):
  89. tray_info_idx = detail["filament_id"]
  90. cloud_name = detail.get("name", "")
  91. if cloud_name:
  92. sub_brand_override = cloud_name.replace(r"@.*$", "").split("@")[0].strip()
  93. elif detail.get("base_id"):
  94. bid = detail["base_id"].split("_")[0]
  95. if bid.startswith("GFS") and len(bid) >= 5:
  96. tray_info_idx = f"GF{bid[3:]}"
  97. else:
  98. tray_info_idx = bid
  99. finally:
  100. await cloud.close()
  101. elif cloud is not None:
  102. await cloud.close()
  103. except Exception as e:
  104. logger.warning("Slicer-filament resolve: cloud lookup failed for %r: %s", sf, e)
  105. if not tray_info_idx:
  106. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  107. elif base_sf.startswith("GF"):
  108. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  109. else:
  110. try:
  111. local_id = int(sf)
  112. from backend.app.models.local_preset import LocalPreset as LP
  113. lp_result = await db.execute(select(LP).where(LP.id == local_id, LP.preset_type == "filament"))
  114. lp = lp_result.scalar_one_or_none()
  115. if lp:
  116. # Local preset's setting JSON carries the printer-recognized
  117. # filament_id (e.g. "P4d64437") — use that directly so the
  118. # slicer can resolve the specific preset. Falls through to
  119. # generic material id only when the JSON doesn't carry one.
  120. lp_filament_id = ""
  121. if lp.setting:
  122. try:
  123. setting_data = json.loads(lp.setting)
  124. raw_fid = setting_data.get("filament_id")
  125. if isinstance(raw_fid, str) and raw_fid:
  126. lp_filament_id = raw_fid
  127. except (json.JSONDecodeError, AttributeError):
  128. pass
  129. if lp_filament_id:
  130. tray_info_idx = lp_filament_id
  131. setting_id = filament_id_to_setting_id(lp_filament_id)
  132. else:
  133. # Deliberately not widened to cover product-line materials
  134. # ("PLA+", "HTPLA") the way the callers' own fallbacks were
  135. # (#2902). Returning an id here rather than "" would skip
  136. # the caller's whole no-id block, and with it the slot-reuse
  137. # branch that keeps a printer's calibrated preset -- so the
  138. # widening belongs there, after reuse has had its turn.
  139. mat = (material or lp.filament_type or "").upper().strip()
  140. tray_info_idx = (
  141. GENERIC_FILAMENT_IDS.get(mat) or GENERIC_FILAMENT_IDS.get(mat.split("-")[0].split(" ")[0]) or ""
  142. )
  143. if lp.name:
  144. sub_brand_override = lp.name.split("@")[0].strip()
  145. except (ValueError, TypeError):
  146. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  147. # Realign tray_info_idx to a builtin whose name matches slicer_filament_name
  148. # when the current resolution lands on a builtin with a different name
  149. # (e.g. cloud detail returned PLA Basic but the spool was labelled PLA Matte).
  150. if tray_info_idx and slicer_filament_name:
  151. from backend.app.api.routes.cloud import _BUILTIN_FILAMENT_NAMES
  152. expected_name = _BUILTIN_FILAMENT_NAMES.get(tray_info_idx, "")
  153. if expected_name and expected_name != slicer_filament_name:
  154. for fid, fname in _BUILTIN_FILAMENT_NAMES.items():
  155. if fname == slicer_filament_name:
  156. tray_info_idx = fid
  157. setting_id = filament_id_to_setting_id(fid)
  158. break
  159. # Defend against tray_info_idx values the slicer cannot resolve. Three
  160. # shapes leak through and must be discarded so the caller's generic-
  161. # material fallback can rescue the slot:
  162. # 1. Literal material names ("PLA", "PETG-CF") that pass through
  163. # normalize_slicer_filament unchanged when the spool's slicer_filament
  164. # is free-text rather than a real preset ID. Product lines ("PLA+",
  165. # "HTPLA") count as material names too -- see is_material_name, which
  166. # is shared with the slot-reuse check that must agree with this.
  167. # 2. PFUS-prefix cloud setting_ids — valid as setting_id but rejected
  168. # by the slicer as tray_info_idx (the printer's calibration table
  169. # indexes by filament_id, and a PFUS isn't one). This normally gets
  170. # realigned to a P-prefix local id via the caller's printer_kp
  171. # lookup, but on the replay path in main.py.on_ams_change
  172. # current_user=None skips cloud auth and leaves the raw PFUS in
  173. # tray_info_idx — overwriting the correctly-configured slot from
  174. # the original assign.
  175. # 3. PFCN-prefix cloud shared / partner presets (e.g. Polymaker's
  176. # "(Custom)" H2D variants, #1648) — same shape problem as PFUS.
  177. # Valid tray_info_idx values: "GF" + letter + digits (Bambu official) or
  178. # "P" followed by hex (user/local presets, NOT "PFUS" or "PFCN").
  179. if tray_info_idx and (
  180. is_material_name(tray_info_idx) or tray_info_idx.startswith("PFUS") or tray_info_idx.startswith("PFCN")
  181. ):
  182. tray_info_idx = ""
  183. # Preserve setting_id when it's still a valid slicer reference
  184. # (PFUS / PFCN cloud user/shared preset, or GFS Bambu official
  185. # preset). The slicer accepts these as setting_id even though
  186. # they're rejected as tray_info_idx; without preservation the
  187. # slicer falls back to whatever generic filament the caller's
  188. # tray_info_idx fallback produces and shows "Generic <Material>"
  189. # instead of the user's actual custom preset (#1815). Material-name
  190. # leaks (e.g. setting_id="PETG") are still cleared — those are
  191. # never valid slicer references.
  192. if not (
  193. setting_id
  194. and (setting_id.startswith("PFUS") or setting_id.startswith("PFCN") or setting_id.startswith("GFS"))
  195. ):
  196. setting_id = ""
  197. return (tray_info_idx, setting_id, sub_brand_override)