amsHelpers.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. /**
  2. * AMS (Automatic Material System) helper utilities for Bambu Lab printers.
  3. * These functions handle color normalization, slot labeling, and tray ID calculations
  4. * for AMS, AMS-HT, and external spool configurations.
  5. */
  6. import { parseUTCDate } from './date';
  7. /**
  8. * Normalize color format from various sources for CSS rendering.
  9. * API returns "RRGGBBAA" (8-char), 3MF uses "#RRGGBB" (7-char with hash).
  10. * Result is "#RRGGBB" for opaque colors and "#RRGGBBAA" when alpha < FF —
  11. * CSS accepts both forms on `fill` / `backgroundColor`, and preserving alpha
  12. * lets transparent filaments render translucent instead of collapsing to
  13. * solid black (#1545). Comparison helpers use normalizeColorForCompare which
  14. * still strips alpha, so type/colour matching is unaffected.
  15. */
  16. export function normalizeColor(color: string | null | undefined): string {
  17. if (!color) return '#808080';
  18. const clean = color.replace('#', '');
  19. if (clean.length >= 8 && clean.substring(6, 8).toLowerCase() !== 'ff') {
  20. return `#${clean.substring(0, 8)}`;
  21. }
  22. return `#${clean.substring(0, 6)}`;
  23. }
  24. /**
  25. * Normalize color for comparison (case-insensitive, strip hash and alpha).
  26. */
  27. export function normalizeColorForCompare(color: string | undefined): string {
  28. if (!color) return '';
  29. return color.replace('#', '').toLowerCase().substring(0, 6);
  30. }
  31. /**
  32. * Which side letter stands for a Filament Track Switch inlet: In-A reads as L,
  33. * In-B as R.
  34. *
  35. * This labels the inlet's position, not the nozzle it feeds — the switch can
  36. * route either inlet to either nozzle, and it never reports which pairing is
  37. * live. Anywhere this letter is shown next to a hover target, the tooltip names
  38. * the inlet outright so the two cannot be confused.
  39. */
  40. export const FTS_INLET_SIDE = { A: 'L', B: 'R' } as const;
  41. /**
  42. * Which extruder each switch inlet feeds. Out-A is the left hotend and Out-B the
  43. * right one (measured on an H2C), and the inlet pairs with its own outlet in the
  44. * switch's rest position. Mirrors `backend/app/utils/fts_routing.py`, which
  45. * carries the full reasoning and the reason `fila_switch.out` cannot be used.
  46. */
  47. const FTS_INLET_EXTRUDER: Record<string, number> = { A: 1, B: 0 };
  48. /**
  49. * The extruder an AMS slot feeds, or undefined when it genuinely cannot be told.
  50. *
  51. * Undefined is not the same as extruder 0. K-profiles are per-nozzle, so a slot
  52. * whose nozzle is unknown must not be silently treated as right-hand — that is
  53. * what bound a left-nozzle profile to a slot sitting on the right.
  54. */
  55. export function resolveSlotExtruder(
  56. amsId: number,
  57. trayId: number,
  58. amsExtruderMap: Record<string, number> | undefined,
  59. amsSwitchInlet: Record<string, string> | undefined
  60. ): number | undefined {
  61. // External holder: the tray id names the side. 254/Ext-L feeds extruder 1.
  62. if (amsId === 255) return trayId === 0 || trayId === 1 ? 1 - trayId : undefined;
  63. const mapped = amsExtruderMap?.[String(amsId)];
  64. if (mapped !== undefined) return mapped;
  65. const inlet = amsSwitchInlet?.[String(amsId)];
  66. return inlet ? FTS_INLET_EXTRUDER[inlet.toUpperCase()] : undefined;
  67. }
  68. /**
  69. * AMS unit label using the codebase convention: "AMS-A / AMS-B / ..." for
  70. * regular AMS, "HT-A / HT-B / ..." for AMS-HT (single-tray modules with
  71. * IDs starting at 128). `trayCount` is required because the type can't be
  72. * inferred from the id alone — regular AMS IDs 0-3 can collide with the
  73. * normalized HT range otherwise.
  74. */
  75. export function getAmsLabel(amsId: number | string, trayCount: number): string {
  76. const id = typeof amsId === 'string' ? parseInt(amsId, 10) : amsId;
  77. const safeId = isNaN(id) ? 0 : id;
  78. if (safeId === 255) return 'External';
  79. // A2L "AMS Lite": the backend normalises its physical unit id 16 to 6 at
  80. // ingest (see a2l-am-unit-16). No regular AMS uses id 6, so this is a safe,
  81. // self-scoping label for the Lite's 4-slot unit.
  82. if (safeId === 6) return 'AMS Lite';
  83. const isHt = trayCount === 1;
  84. const normalizedId = safeId >= 128 ? safeId - 128 : safeId;
  85. const letter = String.fromCharCode(65 + normalizedId);
  86. return isHt ? `HT-${letter}` : `AMS-${letter}`;
  87. }
  88. /**
  89. * Filament type equivalence groups.
  90. * Types within the same group are interchangeable on the printer side
  91. * (e.g., Bambu Lab firmware treats PA-CF and PA12-CF as compatible).
  92. */
  93. const FILAMENT_TYPE_GROUPS: string[][] = [
  94. ['PA-CF', 'PA12-CF', 'PAHT-CF'],
  95. ];
  96. const _equivalenceMap: Record<string, string> = {};
  97. for (const group of FILAMENT_TYPE_GROUPS) {
  98. const canonical = group[0];
  99. for (const t of group) {
  100. _equivalenceMap[t.toUpperCase()] = canonical.toUpperCase();
  101. }
  102. }
  103. /**
  104. * Get the canonical filament type for equivalence matching.
  105. * Types in the same group (e.g., PA-CF / PA12-CF / PAHT-CF) return the same canonical type.
  106. */
  107. export function canonicalFilamentType(type: string | undefined): string {
  108. if (!type) return '';
  109. const upper = type.toUpperCase();
  110. return _equivalenceMap[upper] ?? upper;
  111. }
  112. /**
  113. * Check if two filament types are compatible (same type or same equivalence group).
  114. */
  115. export function filamentTypesCompatible(a: string | undefined, b: string | undefined): boolean {
  116. return canonicalFilamentType(a) === canonicalFilamentType(b);
  117. }
  118. /**
  119. * Check if two colors are visually similar within a threshold.
  120. * Uses RGB component comparison with configurable tolerance.
  121. * @param color1 - First hex color
  122. * @param color2 - Second hex color
  123. * @param threshold - Maximum difference per RGB component (default: 40)
  124. */
  125. export function colorsAreSimilar(
  126. color1: string | undefined,
  127. color2: string | undefined,
  128. threshold = 40
  129. ): boolean {
  130. const hex1 = normalizeColorForCompare(color1);
  131. const hex2 = normalizeColorForCompare(color2);
  132. if (!hex1 || !hex2 || hex1.length < 6 || hex2.length < 6) return false;
  133. const r1 = parseInt(hex1.substring(0, 2), 16);
  134. const g1 = parseInt(hex1.substring(2, 4), 16);
  135. const b1 = parseInt(hex1.substring(4, 6), 16);
  136. const r2 = parseInt(hex2.substring(0, 2), 16);
  137. const g2 = parseInt(hex2.substring(2, 4), 16);
  138. const b2 = parseInt(hex2.substring(4, 6), 16);
  139. return (
  140. Math.abs(r1 - r2) <= threshold &&
  141. Math.abs(g1 - g2) <= threshold &&
  142. Math.abs(b1 - b2) <= threshold
  143. );
  144. }
  145. const D65_WHITE: readonly [number, number, number] = [0.95047, 1.0, 1.08883];
  146. const LAB_DELTA = 6 / 29;
  147. /**
  148. * Convert a hex colour to CIE L*a*b* under D65, or null if it is unusable.
  149. *
  150. * Alpha is dropped by `normalizeColorForCompare`, deliberately: the alpha a
  151. * slicer writes for a transparent filament is not a colour the user chose, and
  152. * counting it would stop a transparent filament matching itself.
  153. */
  154. function hexToLab(color: string | undefined): [number, number, number] | null {
  155. const hex = normalizeColorForCompare(color);
  156. if (!hex || hex.length < 6) return null;
  157. const channels = [0, 2, 4].map((i) => parseInt(hex.substring(i, i + 2), 16) / 255);
  158. if (channels.some(Number.isNaN)) return null;
  159. // sRGB gamma -> linear light.
  160. const [r, g, b] = channels.map((c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
  161. const xyz: [number, number, number] = [
  162. 0.4124564 * r + 0.3575761 * g + 0.1804375 * b,
  163. 0.2126729 * r + 0.7151522 * g + 0.072175 * b,
  164. 0.0193339 * r + 0.119192 * g + 0.9503041 * b,
  165. ];
  166. const f = (t: number) =>
  167. t > LAB_DELTA ** 3 ? Math.cbrt(t) : t / (3 * LAB_DELTA * LAB_DELTA) + 4 / 29;
  168. const [fx, fy, fz] = xyz.map((v, i) => f(v / D65_WHITE[i]));
  169. return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];
  170. }
  171. /**
  172. * CIEDE2000 colour difference between two L*a*b* triples.
  173. *
  174. * Straight transcription of the CIE formulation with kL = kC = kH = 1, kept
  175. * structurally identical to `perceptual_color_distance` in
  176. * `backend/app/utils/color_utils.py` so the two can be read side by side. They
  177. * must agree: the dialog must not promise a spool the scheduler would not pick.
  178. */
  179. function ciede2000(lab1: [number, number, number], lab2: [number, number, number]): number {
  180. const [l1, a1, b1] = lab1;
  181. const [l2, a2, b2] = lab2;
  182. const rad = (deg: number) => (deg * Math.PI) / 180;
  183. const c1 = Math.hypot(a1, b1);
  184. const c2 = Math.hypot(a2, b2);
  185. const cBar7 = ((c1 + c2) / 2) ** 7;
  186. const g = 0.5 * (1 - Math.sqrt(cBar7 / (cBar7 + 25 ** 7)));
  187. const a1p = (1 + g) * a1;
  188. const a2p = (1 + g) * a2;
  189. const c1p = Math.hypot(a1p, b1);
  190. const c2p = Math.hypot(a2p, b2);
  191. const hue = (ap: number, bp: number) => {
  192. if (ap === 0 && bp === 0) return 0;
  193. const deg = (Math.atan2(bp, ap) * 180) / Math.PI;
  194. return deg < 0 ? deg + 360 : deg;
  195. };
  196. const h1p = hue(a1p, b1);
  197. const h2p = hue(a2p, b2);
  198. const dlp = l2 - l1;
  199. const dcp = c2p - c1p;
  200. const chromaProduct = c1p * c2p;
  201. let dhp = 0;
  202. if (chromaProduct !== 0) {
  203. dhp = h2p - h1p;
  204. if (dhp > 180) dhp -= 360;
  205. else if (dhp < -180) dhp += 360;
  206. }
  207. const dhpBig = 2 * Math.sqrt(chromaProduct) * Math.sin(rad(dhp) / 2);
  208. const lBar = (l1 + l2) / 2;
  209. const cBar = (c1p + c2p) / 2;
  210. let hBar: number;
  211. if (chromaProduct === 0) hBar = h1p + h2p;
  212. else if (Math.abs(h1p - h2p) <= 180) hBar = (h1p + h2p) / 2;
  213. else if (h1p + h2p < 360) hBar = (h1p + h2p + 360) / 2;
  214. else hBar = (h1p + h2p - 360) / 2;
  215. const t =
  216. 1 -
  217. 0.17 * Math.cos(rad(hBar - 30)) +
  218. 0.24 * Math.cos(rad(2 * hBar)) +
  219. 0.32 * Math.cos(rad(3 * hBar + 6)) -
  220. 0.2 * Math.cos(rad(4 * hBar - 63));
  221. const cBarP7 = cBar ** 7;
  222. const rc = 2 * Math.sqrt(cBarP7 / (cBarP7 + 25 ** 7));
  223. const sl = 1 + (0.015 * (lBar - 50) ** 2) / Math.sqrt(20 + (lBar - 50) ** 2);
  224. const sc = 1 + 0.045 * cBar;
  225. const sh = 1 + 0.015 * cBar * t;
  226. const rt = -Math.sin(rad(2 * (30 * Math.exp(-(((hBar - 275) / 25) ** 2))))) * rc;
  227. const dL = dlp / sl;
  228. const dC = dcp / sc;
  229. const dH = dhpBig / sh;
  230. return Math.sqrt(dL * dL + dC * dC + dH * dH + rt * dC * dH);
  231. }
  232. /**
  233. * Perceptual distance between two hex colours, or null if either is unusable.
  234. *
  235. * Used to rank the candidates `colorsAreSimilar` admits. Eligibility stays the
  236. * per-channel box that shipped; this only decides which of several eligible
  237. * spools is closest, so no spool becomes usable or unusable because of it.
  238. *
  239. * It ranks by how far apart the colours *look*, not how far apart their numbers
  240. * are. RGB distance overweights blue badly enough to invert the answer: against
  241. * a required `#1E4821` green, a purple `#38202F` is the nearer of two eligible
  242. * spools by RGB and four times the further once measured perceptually.
  243. *
  244. * The scale is CIEDE2000 delta-E, where ~1 is a just-noticeable difference —
  245. * far smaller numbers than the RGB distances this replaced, and not comparable
  246. * against an RGB threshold.
  247. */
  248. export function colorDistance(
  249. color1: string | undefined,
  250. color2: string | undefined,
  251. ): number | null {
  252. const lab1 = hexToLab(color1);
  253. const lab2 = hexToLab(color2);
  254. if (!lab1 || !lab2) return null;
  255. return ciede2000(lab1, lab2);
  256. }
  257. /**
  258. * The closest colour match among `candidates`, or undefined if none is similar
  259. * enough to qualify.
  260. *
  261. * Callers pass candidates in the order they already established — slot order,
  262. * or the "prefer lowest remaining" sort. Ties keep the earliest of them, so
  263. * that order survives as the tie-break and Prefer Lowest still decides between
  264. * two equally close spools, which is the case it was actually for.
  265. *
  266. * This exists so the four matchers that pick a spool (`autoMatchFilament`,
  267. * `computeAmsMapping`, `computeMappingWithOverrides`, `computeMatchDetails`)
  268. * share one ranking rule instead of four copies of "first one within
  269. * tolerance", which made the winner depend on AMS slot order.
  270. */
  271. export function findNearestSimilar<T>(
  272. candidates: T[],
  273. requiredColor: string | undefined,
  274. getColor: (candidate: T) => string | undefined,
  275. ): T | undefined {
  276. let best: T | undefined;
  277. let bestDistance = Infinity;
  278. for (const candidate of candidates) {
  279. const color = getColor(candidate);
  280. if (!colorsAreSimilar(color, requiredColor)) continue;
  281. const distance = colorDistance(color, requiredColor);
  282. if (distance === null) continue;
  283. // Strict <: an equally close candidate never displaces an earlier one.
  284. if (distance < bestDistance) {
  285. best = candidate;
  286. bestDistance = distance;
  287. }
  288. }
  289. return best;
  290. }
  291. /**
  292. * Format slot label for display in the UI.
  293. * @param amsId - AMS unit ID (0-3 for regular AMS, 128+ for AMS-HT)
  294. * @param trayId - Tray/slot ID within the AMS unit (0-3)
  295. * @param isHt - Whether this is an AMS-HT unit (single tray)
  296. * @param isExternal - Whether this is the external spool holder
  297. */
  298. export function formatSlotLabel(
  299. amsId: number,
  300. trayId: number,
  301. isHt: boolean,
  302. isExternal: boolean
  303. ): string {
  304. if (isExternal) return 'Ext';
  305. // Convert AMS ID to letter (A, B, C, D)
  306. // AMS-HT uses IDs starting at 128
  307. const letter = String.fromCharCode(65 + (amsId >= 128 ? amsId - 128 : amsId));
  308. if (isHt) return `HT-${letter}`;
  309. return `${letter}${trayId + 1}`;
  310. }
  311. /**
  312. * Calculate global tray ID for MQTT command.
  313. * Used in the ams_mapping array sent to the printer.
  314. * @param amsId - AMS unit ID (0-3 for regular AMS, 128+ for AMS-HT)
  315. * @param trayId - Tray/slot ID within the AMS unit
  316. * @param isExternal - Whether this is the external spool holder
  317. * @returns Global tray ID (0-15 for AMS, 128+ for AMS-HT, 254 for external)
  318. */
  319. export function getGlobalTrayId(
  320. amsId: number,
  321. trayId: number,
  322. isExternal: boolean
  323. ): number {
  324. if (isExternal) return 254 + trayId;
  325. // AMS-HT units have IDs starting at 128 with a single tray — use ID directly
  326. if (amsId >= 128) return amsId;
  327. return amsId * 4 + trayId;
  328. }
  329. /**
  330. * Get fill bar color based on spool fill level.
  331. * Matches PrintersPage thresholds and Bambu Lab brand green.
  332. */
  333. export function getFillBarColor(fillLevel: number): string {
  334. if (fillLevel > 50) return '#00ae42'; // Green - good
  335. if (fillLevel >= 15) return '#f59e0b'; // Amber - warning (<= 50%)
  336. return '#ef4444'; // Red - critical (< 15%)
  337. }
  338. /**
  339. * Calculate fill level from Spoolman weight data.
  340. * Used as the first source in the Spoolman → Inventory → AMS fill chain.
  341. */
  342. export function getSpoolmanFillLevel(
  343. linkedSpool: { remaining_weight: number | null; filament_weight: number | null } | undefined
  344. ): number | null {
  345. if (!linkedSpool?.remaining_weight || !linkedSpool?.filament_weight
  346. || linkedSpool.filament_weight <= 0) return null;
  347. return Math.min(100, Math.round(
  348. (linkedSpool.remaining_weight / linkedSpool.filament_weight) * 100
  349. ));
  350. }
  351. function toFixedHex(value: number, width: number): string {
  352. const safe = Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;
  353. return safe.toString(16).toUpperCase().padStart(width, '0').slice(-width);
  354. }
  355. // 32-bit FNV-1a hash -> 8-char hex (stable for alphanumeric serials)
  356. function hashSerialToHex32(serial: string): string {
  357. const input = (serial || '').trim().toUpperCase();
  358. let hash = 0x811c9dc5;
  359. for (let i = 0; i < input.length; i++) {
  360. hash ^= input.charCodeAt(i);
  361. hash = Math.imul(hash, 0x01000193);
  362. }
  363. return (hash >>> 0).toString(16).toUpperCase().padStart(8, '0');
  364. }
  365. /**
  366. * Generate a stable fallback spool tag for slots without RFID identifiers.
  367. * Returns a 16-char hex string derived from the printer serial + slot position.
  368. */
  369. export function getFallbackSpoolTag(printerSerial: string, amsId: number, trayId: number): string {
  370. return `${hashSerialToHex32(printerSerial)}${toFixedHex(amsId, 4)}${toFixedHex(trayId, 4)}`;
  371. }
  372. /**
  373. * Get minimum datetime for scheduling (now + 1 minute).
  374. * Returns ISO string format for datetime-local input.
  375. */
  376. export function getMinDateTime(): string {
  377. const now = new Date();
  378. now.setMinutes(now.getMinutes() + 1);
  379. return now.toISOString().slice(0, 16);
  380. }
  381. /**
  382. * Check if a scheduled time is a placeholder far-future date.
  383. * Placeholder dates (more than 6 months out) are treated as ASAP.
  384. */
  385. export function isPlaceholderDate(scheduledTime: string | null | undefined): boolean {
  386. if (!scheduledTime) return false;
  387. const sixMonthsFromNow = Date.now() + 180 * 24 * 60 * 60 * 1000;
  388. return (parseUTCDate(scheduledTime)?.getTime() ?? 0) > sixMonthsFromNow;
  389. }
  390. /**
  391. * Banding tie-break for `preferLowestSortKey`, mirroring backend
  392. * `PrintScheduler._slot_priority` so regular AMS < AMS-HT < external on ties
  393. * regardless of the raw `ams_id`. In particular, `ams_id = -1` (VT / external
  394. * in `buildLoadedFilaments`) MUST NOT sort to a negative number or it would
  395. * beat AMS slot 0 — backend clamps to 10_000.
  396. */
  397. function slotPriority(amsId: number | undefined, trayId: number | undefined): number {
  398. if (amsId == null || amsId < 0) return 10_000;
  399. if (amsId >= 128) return 1_000 + (amsId - 128) * 4 + (trayId ?? 0);
  400. return amsId * 4 + (trayId ?? 0);
  401. }
  402. /**
  403. * Two-tier sort key for the "Prefer Lowest Remaining Filament" preference (#1766).
  404. *
  405. * Mirrors backend `_prefer_lowest_sort_key` in `print_scheduler.py:1161` so the
  406. * client-side sort that PrintModal pre-computes lines up with the dispatch-time
  407. * sort. Inventory-bound spools sort before MQTT-only ones (tier 0 vs tier 1) so
  408. * the user's tracked grams beat the printer's per-cent estimate; within each
  409. * tier the lowest value wins, with the slot-position tie-break above so the
  410. * order is deterministic across identical spools.
  411. *
  412. * `inventoryByTrayId` is the `globalTrayId -> grams_remaining` map derived from
  413. * the user's spool assignments. Pass `undefined` to fall back to remain%-only
  414. * sorting (preserves pre-#1766 behaviour for callers that don't yet wire it in).
  415. */
  416. export function preferLowestSortKey(
  417. f: { globalTrayId: number; amsId?: number; trayId?: number; remain?: number },
  418. inventoryByTrayId: Map<number, number> | undefined,
  419. ): [number, number, number] {
  420. const slot = slotPriority(f.amsId, f.trayId);
  421. if (inventoryByTrayId && inventoryByTrayId.has(f.globalTrayId)) {
  422. return [0, inventoryByTrayId.get(f.globalTrayId) ?? 0, slot];
  423. }
  424. const remain = f.remain ?? -1;
  425. return [1, remain >= 0 ? remain : 101, slot];
  426. }
  427. /** Tuple compare for `preferLowestSortKey` outputs. */
  428. export function compareSortKeys(
  429. a: [number, number, number],
  430. b: [number, number, number],
  431. ): number {
  432. return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
  433. }
  434. /**
  435. * Effective "Prefer lowest remaining filament" preference for a given printer,
  436. * gated on its AMS Filament Backup state (#1766).
  437. *
  438. * Without backup, the printer can't switch to a second spool when the picked
  439. * one runs out — so even with the user setting on, sorting toward the lowest
  440. * leaves the print at risk. Mirrors the backend gate in
  441. * `print_scheduler.py::_compute_ams_mapping_for_printer`. `null`/`undefined`
  442. * (unknown state, e.g. A1 family) preserves today's behaviour intentionally.
  443. */
  444. export function effectivePreferLowest(
  445. setting: boolean | undefined,
  446. amsFilamentBackup: boolean | null | undefined,
  447. ): boolean {
  448. if (!setting) return false;
  449. return amsFilamentBackup !== false;
  450. }
  451. /**
  452. * Auto-match a filament requirement to a loaded filament, respecting nozzle constraints.
  453. * Used by both single-printer (FilamentMapping) and multi-printer (InlineMappingEditor) paths.
  454. */
  455. export function autoMatchFilament(
  456. req: { type?: string; color?: string; nozzle_id?: number | null },
  457. loadedFilaments: { globalTrayId: number; amsId?: number; trayId?: number; type?: string; color?: string; extruderId?: number; remain?: number }[],
  458. usedTrayIds: Set<number>,
  459. preferLowest?: boolean,
  460. inventoryByTrayId?: Map<number, number>,
  461. ): typeof loadedFilaments[number] | undefined {
  462. let nozzleFilaments = filterFilamentsByNozzle(loadedFilaments, req.nozzle_id);
  463. if (preferLowest) {
  464. nozzleFilaments = [...nozzleFilaments].sort((a, b) =>
  465. compareSortKeys(
  466. preferLowestSortKey(a, inventoryByTrayId),
  467. preferLowestSortKey(b, inventoryByTrayId),
  468. ),
  469. );
  470. }
  471. const exactMatch = nozzleFilaments.find(
  472. (f) =>
  473. !usedTrayIds.has(f.globalTrayId) &&
  474. filamentTypesCompatible(f.type, req.type) &&
  475. normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color)
  476. );
  477. const similarMatch = exactMatch
  478. ? undefined
  479. : findNearestSimilar(
  480. nozzleFilaments.filter(
  481. (f) => !usedTrayIds.has(f.globalTrayId) && filamentTypesCompatible(f.type, req.type),
  482. ),
  483. req.color,
  484. (f) => f.color,
  485. );
  486. const typeOnlyMatch =
  487. exactMatch || similarMatch
  488. ? undefined
  489. : nozzleFilaments.find(
  490. (f) => !usedTrayIds.has(f.globalTrayId) && filamentTypesCompatible(f.type, req.type)
  491. );
  492. return exactMatch ?? similarMatch ?? typeOnlyMatch;
  493. }
  494. /**
  495. * Filter loaded filaments to those valid for a given nozzle requirement.
  496. * For single-nozzle printers (nozzle_id is null/undefined), returns all filaments.
  497. */
  498. export function filterFilamentsByNozzle<T extends { extruderId?: number }>(
  499. loadedFilaments: T[],
  500. nozzleId: number | undefined | null,
  501. ): T[] {
  502. return loadedFilaments.filter(
  503. (f) => nozzleId == null || f.extruderId === nozzleId
  504. );
  505. }
  506. /**
  507. * List the distinct nozzle diameters the printer actually reports (#2618).
  508. * Mirrors the backend `_installed_nozzle_diameters`: reads each
  509. * `status.nozzles[].nozzle_diameter`, skips the empty-string / non-positive
  510. * defaults that populate a NozzleInfo before MQTT fills it in, and dedupes.
  511. *
  512. * Returns e.g. `['0.4']` (single-nozzle) or `['0.4', '0.6']` (dual-nozzle). An
  513. * empty array means "the printer hasn't told us its nozzle hardware" — callers
  514. * that need to fetch per-nozzle should fall back to their own default rather
  515. * than treating it as "no nozzles". Preserves the bare decimal string form the
  516. * status carries so it can be passed straight to `getKProfiles`.
  517. */
  518. export function installedNozzleDiameters(
  519. status: { nozzles?: { nozzle_diameter?: string }[] } | null | undefined,
  520. ): string[] {
  521. const seen = new Set<string>();
  522. const result: string[] = [];
  523. for (const nozzle of status?.nozzles ?? []) {
  524. const raw = (nozzle?.nozzle_diameter ?? '').trim();
  525. if (!raw || !(parseFloat(raw) > 0) || seen.has(raw)) continue;
  526. seen.add(raw);
  527. result.push(raw);
  528. }
  529. return result;
  530. }
  531. /**
  532. * Resolve the installed nozzle diameter feeding a given AMS unit, so the
  533. * Configure-AMS-Slot picker filters filament presets by the nozzle actually on
  534. * the machine instead of assuming 0.4mm (#1899).
  535. *
  536. * On dual-nozzle printers (H2D) each AMS is bound to one extruder via
  537. * `ams_extruder_map` (amsId → extruder index), so we read that nozzle's
  538. * diameter. `status.nozzles` is indexed by extruder id -- [0] is the RIGHT
  539. * hotend and [1] the left, measured on an H2D fitted with 0.4 left / 0.6 right
  540. * -- so indexing it by the extruder is correct. (This comment used to say
  541. * "0=left/primary, 1=right", which was backwards; the code was always right.)
  542. * Single-nozzle printers have no map entry and fall back to index 0. Returns
  543. * undefined when the printer hasn't reported nozzle hardware yet, letting the
  544. * caller keep its own default.
  545. * Diameter is the bare decimal string the status carries, e.g. "0.4" / "0.6".
  546. */
  547. export function resolveSlotNozzleDiameter(
  548. status: {
  549. nozzles?: { nozzle_diameter?: string }[];
  550. ams_extruder_map?: Record<string, number>;
  551. } | null | undefined,
  552. amsId: number,
  553. ): string | undefined {
  554. const nozzles = status?.nozzles;
  555. if (!nozzles || nozzles.length === 0) return undefined;
  556. const extruderIdx = status?.ams_extruder_map?.[String(amsId)] ?? 0;
  557. const diameter = nozzles[extruderIdx]?.nozzle_diameter || nozzles[0]?.nozzle_diameter;
  558. return diameter || undefined;
  559. }
  560. /**
  561. * Detect Bambu Lab RFID-tagged spool by tray_uuid (32 hex) or tag_uid (16 hex).
  562. *
  563. * Permissive zero-string check: any non-zero non-empty value returns true. The
  564. * function exists to suppress assign/unassign actions on RFID-managed slots
  565. * whose state is owned by the printer firmware — manual changes there would be
  566. * overwritten on the next RFID re-read (eye → pen icon in BambuStudio).
  567. */
  568. export function isBambuLabSpool(tray: {
  569. tray_uuid?: string | null;
  570. tag_uid?: string | null;
  571. } | null | undefined): boolean {
  572. if (!tray) return false;
  573. if (tray.tray_uuid && tray.tray_uuid !== '00000000000000000000000000000000') return true;
  574. if (tray.tag_uid && tray.tag_uid !== '0000000000000000') return true;
  575. return false;
  576. }
  577. /**
  578. * Does a stored slot preset still describe what is in the slot?
  579. *
  580. * `slot_preset_mappings` remembers the preset a slot was last configured with,
  581. * and the AMS slot card shows that name ahead of anything the printer reports —
  582. * which is what lets a slot keep a hand-picked name like "# Bambu PLA Matte
  583. * @BBL H2C 0.4 nozzle (Custom)" instead of the plain catalog one. The cost is
  584. * that a swapped spool leaves the previous spool's name on the card until the
  585. * row is refetched, and until then a cached row outranks live telemetry.
  586. *
  587. * The printer's own `tray_info_idx` settles it, but only for official Bambu
  588. * presets, where the two id forms differ by one letter (setting_id `GFSA01` ↔
  589. * filament_id `GFA01`). A user preset genuinely carries two unrelated ids — a
  590. * slot configured with `PFUSa3b8b0c664c142` reports `tray_info_idx=P8a85d5a` —
  591. * and a local preset (`local_68`) has no printer-side id at all, so neither can
  592. * be checked here and both keep the stored name. Same for a slot reporting no
  593. * id (generic filament with no tag), which is the case the row exists for.
  594. */
  595. export function slotPresetDescribesTray(
  596. presetId: string | null | undefined,
  597. trayInfoIdx: string | null | undefined,
  598. ): boolean {
  599. const preset = (presetId || '').split('_')[0].toUpperCase();
  600. const tray = (trayInfoIdx || '').split('_')[0].toUpperCase();
  601. if (!preset.startsWith('GFS') || !tray.startsWith('GF') || tray.startsWith('GFS')) return true;
  602. return `GF${preset.slice(3)}` === tray;
  603. }
  604. export interface AmsTrayLike {
  605. id: number;
  606. tray_type: string | null | undefined;
  607. tray_sub_brands: string | null | undefined;
  608. tray_color: string | null | undefined;
  609. tray_info_idx: string | null | undefined;
  610. }
  611. export interface AmsUnitLike {
  612. id: number;
  613. tray: AmsTrayLike[];
  614. }
  615. /**
  616. * One row in the AMS Backup modal: a group of slots that back each other up
  617. * (length >= 2), or a single non-empty slot with no peer (length === 1).
  618. */
  619. export interface BackupGroup {
  620. /** Stable key — same across renders for the same material+extruder. */
  621. key: string;
  622. /** Bambu preset ID (tray_info_idx) when matched on preset; null otherwise. */
  623. presetId: string | null;
  624. /** 0 = right / single, 1 = left. Scoping field for dual-nozzle. */
  625. extruder: number;
  626. /** Display name from the first slot's tray_sub_brands (or tray_type). */
  627. displayName: string;
  628. /** Tray colour from the first slot, for the swatch in the modal. */
  629. trayColor: string | null;
  630. /** Member slots, in (ams_id, slot_idx) order. */
  631. members: Array<{ amsId: number; slotIdx: number; globalTrayId: number }>;
  632. }
  633. /**
  634. * Canonicalise a hex colour for identity comparison. Mirrors the backend
  635. * `_normalize_color_for_id`. Strips the leading `#`, uppercases, and drops
  636. * the alpha channel when 8 chars long so `1A1A1AFF` matches `1A1A1A`.
  637. */
  638. function normalizeColorForId(raw: string | null | undefined): string {
  639. let s = (raw || '').trim().replace(/^#/, '').toUpperCase();
  640. if (s.length === 8) s = s.slice(0, 6);
  641. return s;
  642. }
  643. /**
  644. * Compute backup pairs for the AMS Backup modal (#1762).
  645. *
  646. * Strict identity rule (mirrors backend `_material_identity_internal` /
  647. * `_material_identity_spoolman`): slots pair ONLY when they share the same
  648. * Bambu preset ID (`tray_info_idx`, e.g. "GFA00") AND the same colour. The
  649. * preset identifies the filament profile (PETG HF, PLA Basic, etc.); the
  650. * colour pins the variant — three PETG HF spools in different colours
  651. * absolutely don't back each other up. User-tagged spools without a preset
  652. * never pair — Bambu's firmware backup logic relies on the preset, and
  653. * pairing on cosmetic name/colour match alone would let two visually-
  654. * identical but materially-different spools be treated as backups.
  655. *
  656. * Empty slots are skipped entirely. Every non-empty slot is returned — slots
  657. * without a peer come back as 1-member entries so the modal can list them as
  658. * "Slots without a backup peer".
  659. *
  660. * On dual-extruder printers (H2D / H2C / X2D), pairs are scoped per extruder
  661. * side — the firmware can't cross extruders even with the global backup bit
  662. * set.
  663. */
  664. export function computeBackupGroups(
  665. amsUnits: AmsUnitLike[] | undefined,
  666. amsExtruderMap: Record<string, number> | undefined,
  667. isDualNozzle: boolean,
  668. ): BackupGroup[] {
  669. if (!amsUnits || amsUnits.length === 0) return [];
  670. // Defensive dedup: ``status.ams`` is expected to be unique by `ams.id`, but
  671. // observed in the wild to occasionally contain duplicate entries (e.g. on
  672. // VP-aggregated switch printers or during MQTT partial-update merges). A
  673. // duplicate would surface as "AMS-A slot 1" rendered twice with different
  674. // materials, which is impossible physically and visually broken. First
  675. // occurrence per `ams.id` wins.
  676. const seenIds = new Set<number>();
  677. const uniqueAms: AmsUnitLike[] = [];
  678. for (const ams of amsUnits) {
  679. if (seenIds.has(ams.id)) continue;
  680. seenIds.add(ams.id);
  681. uniqueAms.push(ams);
  682. }
  683. const byKey = new Map<string, BackupGroup>();
  684. for (const ams of uniqueAms) {
  685. const extruder = isDualNozzle ? Number(amsExtruderMap?.[String(ams.id)] ?? 0) : 0;
  686. ams.tray.forEach((tray, slotIdx) => {
  687. if (!tray?.tray_type) return; // empty slot
  688. const preset = (tray.tray_info_idx || '').trim();
  689. const globalTrayId = getGlobalTrayId(ams.id, slotIdx, false);
  690. const member = { amsId: ams.id, slotIdx, globalTrayId };
  691. let key: string;
  692. let presetId: string | null;
  693. if (preset) {
  694. // Same Bambu profile is necessary but NOT sufficient — different colours
  695. // of the same PETG HF profile can't back each other up. Bake the colour
  696. // into the identity key, normalised to strip alpha and case.
  697. const color = normalizeColorForId(tray.tray_color);
  698. key = `preset:${preset}|color:${color}#${extruder}`;
  699. presetId = preset;
  700. } else {
  701. // No preset → never group with anything else. Unique-per-slot key.
  702. key = `unmatched:${ams.id}:${slotIdx}#${extruder}`;
  703. presetId = null;
  704. }
  705. const existing = byKey.get(key);
  706. if (existing) {
  707. existing.members.push(member);
  708. } else {
  709. byKey.set(key, {
  710. key,
  711. presetId,
  712. extruder,
  713. displayName: tray.tray_sub_brands || tray.tray_type || '',
  714. trayColor: tray.tray_color ?? null,
  715. members: [member],
  716. });
  717. }
  718. });
  719. }
  720. // Stable sort: extruder first (so the modal can section per side on
  721. // dual-nozzle), then pairs before lone slots, then by name, then by first
  722. // member's global tray id for deterministic rendering.
  723. return Array.from(byKey.values()).sort((a, b) => {
  724. if (a.extruder !== b.extruder) return a.extruder - b.extruder;
  725. const aLone = a.members.length === 1 ? 1 : 0;
  726. const bLone = b.members.length === 1 ? 1 : 0;
  727. if (aLone !== bLone) return aLone - bLone;
  728. if (a.displayName !== b.displayName) return a.displayName.localeCompare(b.displayName);
  729. return a.members[0].globalTrayId - b.members[0].globalTrayId;
  730. });
  731. }