slicer_filament_resolver.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. MATERIAL_TEMPS,
  38. filament_id_to_setting_id,
  39. normalize_slicer_filament,
  40. )
  41. logger = logging.getLogger(__name__)
  42. _KNOWN_MATERIALS = set(MATERIAL_TEMPS.keys()) | set(GENERIC_FILAMENT_IDS.keys())
  43. async def resolve_slicer_filament(
  44. *,
  45. db: AsyncSession,
  46. current_user: User | None,
  47. slicer_filament: str | None,
  48. slicer_filament_name: str | None,
  49. material: str | None,
  50. ) -> tuple[str, str, str | None]:
  51. """Resolve a spool's slicer-preset reference to printer-side ids.
  52. ``slicer_filament``: the spool's stored reference (e.g. ``"GFA01"``,
  53. ``"PFUS990b6e19965353"``, ``"38"`` for a numeric LocalPreset id, or
  54. free-text). May be empty or None — returns the empty tuple in that case.
  55. ``slicer_filament_name``: optional builtin-name realignment hint. When
  56. set and the resolved tray_info_idx maps to a different builtin name,
  57. the resolver swaps to the builtin whose name matches (e.g. user picked
  58. "Bambu PLA Matte" but the cloud lookup landed on "Bambu PLA Basic").
  59. ``material``: spool material string for the local-preset fallback
  60. branch when the LocalPreset's setting JSON doesn't carry a filament_id.
  61. Returns ``(tray_info_idx, setting_id, sub_brand_override)`` — all empty
  62. when nothing resolved. ``sub_brand_override`` is non-None when a more
  63. specific brand label is available (cloud detail name or local preset
  64. name); ``None`` means the caller should use its own default.
  65. """
  66. sf = (slicer_filament or "").strip()
  67. if not sf:
  68. return ("", "", None)
  69. tray_info_idx = ""
  70. setting_id = ""
  71. sub_brand_override: str | None = None
  72. base_sf = sf.split("_")[0] if "_" in sf else sf
  73. # Cloud-side preset IDs in three known shapes:
  74. # GFS… — Bambu official cloud preset
  75. # PFUS… — cloud user-created preset
  76. # PFCN… — cloud shared / partner preset (e.g. Polymaker's "(Custom)"
  77. # Bambu Lab H2D variant, #1648)
  78. # All three need a cloud-detail lookup to extract the underlying
  79. # filament_id; without it the raw cloud id ends up in tray_info_idx
  80. # and the printer's calibration table can't resolve it.
  81. if base_sf.startswith("GFS") or base_sf.startswith("PFUS") or base_sf.startswith("PFCN"):
  82. setting_id = base_sf
  83. try:
  84. from backend.app.api.routes.cloud import build_authenticated_cloud
  85. cloud = await build_authenticated_cloud(db, current_user)
  86. if cloud is not None and cloud.is_authenticated:
  87. try:
  88. detail = await cloud.get_setting_detail(base_sf)
  89. if detail.get("filament_id"):
  90. tray_info_idx = detail["filament_id"]
  91. cloud_name = detail.get("name", "")
  92. if cloud_name:
  93. sub_brand_override = cloud_name.replace(r"@.*$", "").split("@")[0].strip()
  94. elif detail.get("base_id"):
  95. bid = detail["base_id"].split("_")[0]
  96. if bid.startswith("GFS") and len(bid) >= 5:
  97. tray_info_idx = f"GF{bid[3:]}"
  98. else:
  99. tray_info_idx = bid
  100. finally:
  101. await cloud.close()
  102. elif cloud is not None:
  103. await cloud.close()
  104. except Exception as e:
  105. logger.warning("Slicer-filament resolve: cloud lookup failed for %r: %s", sf, e)
  106. if not tray_info_idx:
  107. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  108. elif base_sf.startswith("GF"):
  109. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  110. else:
  111. try:
  112. local_id = int(sf)
  113. from backend.app.models.local_preset import LocalPreset as LP
  114. lp_result = await db.execute(select(LP).where(LP.id == local_id, LP.preset_type == "filament"))
  115. lp = lp_result.scalar_one_or_none()
  116. if lp:
  117. # Local preset's setting JSON carries the printer-recognized
  118. # filament_id (e.g. "P4d64437") — use that directly so the
  119. # slicer can resolve the specific preset. Falls through to
  120. # generic material id only when the JSON doesn't carry one.
  121. lp_filament_id = ""
  122. if lp.setting:
  123. try:
  124. setting_data = json.loads(lp.setting)
  125. raw_fid = setting_data.get("filament_id")
  126. if isinstance(raw_fid, str) and raw_fid:
  127. lp_filament_id = raw_fid
  128. except (json.JSONDecodeError, AttributeError):
  129. pass
  130. if lp_filament_id:
  131. tray_info_idx = lp_filament_id
  132. setting_id = filament_id_to_setting_id(lp_filament_id)
  133. else:
  134. mat = (material or lp.filament_type or "").upper().strip()
  135. tray_info_idx = (
  136. GENERIC_FILAMENT_IDS.get(mat) or GENERIC_FILAMENT_IDS.get(mat.split("-")[0].split(" ")[0]) or ""
  137. )
  138. if lp.name:
  139. sub_brand_override = lp.name.split("@")[0].strip()
  140. except (ValueError, TypeError):
  141. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  142. # Realign tray_info_idx to a builtin whose name matches slicer_filament_name
  143. # when the current resolution lands on a builtin with a different name
  144. # (e.g. cloud detail returned PLA Basic but the spool was labelled PLA Matte).
  145. if tray_info_idx and slicer_filament_name:
  146. from backend.app.api.routes.cloud import _BUILTIN_FILAMENT_NAMES
  147. expected_name = _BUILTIN_FILAMENT_NAMES.get(tray_info_idx, "")
  148. if expected_name and expected_name != slicer_filament_name:
  149. for fid, fname in _BUILTIN_FILAMENT_NAMES.items():
  150. if fname == slicer_filament_name:
  151. tray_info_idx = fid
  152. setting_id = filament_id_to_setting_id(fid)
  153. break
  154. # Defend against tray_info_idx values the slicer cannot resolve. Three
  155. # shapes leak through and must be discarded so the caller's generic-
  156. # material fallback can rescue the slot:
  157. # 1. Literal material names ("PLA", "PETG-CF") that pass through
  158. # normalize_slicer_filament unchanged when the spool's slicer_filament
  159. # is free-text rather than a real preset ID.
  160. # 2. PFUS-prefix cloud setting_ids — valid as setting_id but rejected
  161. # by the slicer as tray_info_idx (the printer's calibration table
  162. # indexes by filament_id, and a PFUS isn't one). This normally gets
  163. # realigned to a P-prefix local id via the caller's printer_kp
  164. # lookup, but on the replay path in main.py.on_ams_change
  165. # current_user=None skips cloud auth and leaves the raw PFUS in
  166. # tray_info_idx — overwriting the correctly-configured slot from
  167. # the original assign.
  168. # 3. PFCN-prefix cloud shared / partner presets (e.g. Polymaker's
  169. # "(Custom)" H2D variants, #1648) — same shape problem as PFUS.
  170. # Valid tray_info_idx values: "GF" + letter + digits (Bambu official) or
  171. # "P" followed by hex (user/local presets, NOT "PFUS" or "PFCN").
  172. if tray_info_idx and (
  173. tray_info_idx.upper() in _KNOWN_MATERIALS
  174. or tray_info_idx.startswith("PFUS")
  175. or tray_info_idx.startswith("PFCN")
  176. ):
  177. tray_info_idx = ""
  178. # Preserve setting_id when it's still a valid slicer reference
  179. # (PFUS / PFCN cloud user/shared preset, or GFS Bambu official
  180. # preset). The slicer accepts these as setting_id even though
  181. # they're rejected as tray_info_idx; without preservation the
  182. # slicer falls back to whatever generic filament the caller's
  183. # tray_info_idx fallback produces and shows "Generic <Material>"
  184. # instead of the user's actual custom preset (#1815). Material-name
  185. # leaks (e.g. setting_id="PETG") are still cleared — those are
  186. # never valid slicer references.
  187. if not (
  188. setting_id
  189. and (setting_id.startswith("PFUS") or setting_id.startswith("PFCN") or setting_id.startswith("GFS"))
  190. ):
  191. setting_id = ""
  192. return (tray_info_idx, setting_id, sub_brand_override)