amsHelpers.ts 27 KB

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