amsHelpers.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  292. *
  293. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  294. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  295. * every empty-by-bitmask slot lands here regardless of firmware payload
  296. * shape.
  297. *
  298. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  299. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  300. * the user cleared with "Reset Slot" where a physical spool may still be
  301. * loaded but unassigned.
  302. *
  303. * Returns null when the slot is loaded (tray_type is present).
  304. */
  305. export function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  306. if (tray?.tray_type) return null;
  307. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  308. // spool the firmware can't identify is physically present (exists === true)
  309. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  310. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  311. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  312. if (tray?.exists === true) return 'reset';
  313. if (tray?.exists === false) return 'physical';
  314. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  315. }
  316. /**
  317. * Format slot label for display in the UI.
  318. * @param amsId - AMS unit ID (0-3 for regular AMS, 128+ for AMS-HT)
  319. * @param trayId - Tray/slot ID within the AMS unit (0-3)
  320. * @param isHt - Whether this is an AMS-HT unit (single tray)
  321. * @param isExternal - Whether this is the external spool holder
  322. */
  323. export function formatSlotLabel(
  324. amsId: number,
  325. trayId: number,
  326. isHt: boolean,
  327. isExternal: boolean
  328. ): string {
  329. if (isExternal) return 'Ext';
  330. // Convert AMS ID to letter (A, B, C, D)
  331. // AMS-HT uses IDs starting at 128
  332. const letter = String.fromCharCode(65 + (amsId >= 128 ? amsId - 128 : amsId));
  333. if (isHt) return `HT-${letter}`;
  334. return `${letter}${trayId + 1}`;
  335. }
  336. /**
  337. * Calculate global tray ID for MQTT command.
  338. * Used in the ams_mapping array sent to the printer.
  339. * @param amsId - AMS unit ID (0-3 for regular AMS, 128+ for AMS-HT)
  340. * @param trayId - Tray/slot ID within the AMS unit
  341. * @param isExternal - Whether this is the external spool holder
  342. * @returns Global tray ID (0-15 for AMS, 128+ for AMS-HT, 254 for external)
  343. */
  344. export function getGlobalTrayId(
  345. amsId: number,
  346. trayId: number,
  347. isExternal: boolean
  348. ): number {
  349. if (isExternal) return 254 + trayId;
  350. // AMS-HT units have IDs starting at 128 with a single tray — use ID directly
  351. if (amsId >= 128) return amsId;
  352. return amsId * 4 + trayId;
  353. }
  354. /**
  355. * Get fill bar color based on spool fill level.
  356. * Matches PrintersPage thresholds and Bambu Lab brand green.
  357. */
  358. export function getFillBarColor(fillLevel: number): string {
  359. if (fillLevel > 50) return '#00ae42'; // Green - good
  360. if (fillLevel >= 15) return '#f59e0b'; // Amber - warning (<= 50%)
  361. return '#ef4444'; // Red - critical (< 15%)
  362. }
  363. /**
  364. * Calculate fill level from Spoolman weight data.
  365. * Used as the first source in the Spoolman → Inventory → AMS fill chain.
  366. */
  367. export function getSpoolmanFillLevel(
  368. linkedSpool: { remaining_weight: number | null; filament_weight: number | null } | undefined
  369. ): number | null {
  370. if (!linkedSpool?.remaining_weight || !linkedSpool?.filament_weight
  371. || linkedSpool.filament_weight <= 0) return null;
  372. return Math.min(100, Math.round(
  373. (linkedSpool.remaining_weight / linkedSpool.filament_weight) * 100
  374. ));
  375. }
  376. function toFixedHex(value: number, width: number): string {
  377. const safe = Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;
  378. return safe.toString(16).toUpperCase().padStart(width, '0').slice(-width);
  379. }
  380. // 32-bit FNV-1a hash -> 8-char hex (stable for alphanumeric serials)
  381. function hashSerialToHex32(serial: string): string {
  382. const input = (serial || '').trim().toUpperCase();
  383. let hash = 0x811c9dc5;
  384. for (let i = 0; i < input.length; i++) {
  385. hash ^= input.charCodeAt(i);
  386. hash = Math.imul(hash, 0x01000193);
  387. }
  388. return (hash >>> 0).toString(16).toUpperCase().padStart(8, '0');
  389. }
  390. /**
  391. * Generate a stable fallback spool tag for slots without RFID identifiers.
  392. * Returns a 16-char hex string derived from the printer serial + slot position.
  393. */
  394. export function getFallbackSpoolTag(printerSerial: string, amsId: number, trayId: number): string {
  395. return `${hashSerialToHex32(printerSerial)}${toFixedHex(amsId, 4)}${toFixedHex(trayId, 4)}`;
  396. }
  397. /**
  398. * Get minimum datetime for scheduling (now + 1 minute).
  399. * Returns ISO string format for datetime-local input.
  400. */
  401. export function getMinDateTime(): string {
  402. const now = new Date();
  403. now.setMinutes(now.getMinutes() + 1);
  404. return now.toISOString().slice(0, 16);
  405. }
  406. /**
  407. * Check if a scheduled time is a placeholder far-future date.
  408. * Placeholder dates (more than 6 months out) are treated as ASAP.
  409. */
  410. export function isPlaceholderDate(scheduledTime: string | null | undefined): boolean {
  411. if (!scheduledTime) return false;
  412. const sixMonthsFromNow = Date.now() + 180 * 24 * 60 * 60 * 1000;
  413. return (parseUTCDate(scheduledTime)?.getTime() ?? 0) > sixMonthsFromNow;
  414. }
  415. /**
  416. * Banding tie-break for `preferLowestSortKey`, mirroring backend
  417. * `PrintScheduler._slot_priority` so regular AMS < AMS-HT < external on ties
  418. * regardless of the raw `ams_id`. In particular, `ams_id = -1` (VT / external
  419. * in `buildLoadedFilaments`) MUST NOT sort to a negative number or it would
  420. * beat AMS slot 0 — backend clamps to 10_000.
  421. */
  422. function slotPriority(amsId: number | undefined, trayId: number | undefined): number {
  423. if (amsId == null || amsId < 0) return 10_000;
  424. if (amsId >= 128) return 1_000 + (amsId - 128) * 4 + (trayId ?? 0);
  425. return amsId * 4 + (trayId ?? 0);
  426. }
  427. /**
  428. * Two-tier sort key for the "Prefer Lowest Remaining Filament" preference (#1766).
  429. *
  430. * Mirrors backend `_prefer_lowest_sort_key` in `print_scheduler.py:1161` so the
  431. * client-side sort that PrintModal pre-computes lines up with the dispatch-time
  432. * sort. Inventory-bound spools sort before MQTT-only ones (tier 0 vs tier 1) so
  433. * the user's tracked grams beat the printer's per-cent estimate; within each
  434. * tier the lowest value wins, with the slot-position tie-break above so the
  435. * order is deterministic across identical spools.
  436. *
  437. * `inventoryByTrayId` is the `globalTrayId -> grams_remaining` map derived from
  438. * the user's spool assignments. Pass `undefined` to fall back to remain%-only
  439. * sorting (preserves pre-#1766 behaviour for callers that don't yet wire it in).
  440. */
  441. export function preferLowestSortKey(
  442. f: { globalTrayId: number; amsId?: number; trayId?: number; remain?: number },
  443. inventoryByTrayId: Map<number, number> | undefined,
  444. ): [number, number, number] {
  445. const slot = slotPriority(f.amsId, f.trayId);
  446. if (inventoryByTrayId && inventoryByTrayId.has(f.globalTrayId)) {
  447. return [0, inventoryByTrayId.get(f.globalTrayId) ?? 0, slot];
  448. }
  449. const remain = f.remain ?? -1;
  450. return [1, remain >= 0 ? remain : 101, slot];
  451. }
  452. /** Tuple compare for `preferLowestSortKey` outputs. */
  453. export function compareSortKeys(
  454. a: [number, number, number],
  455. b: [number, number, number],
  456. ): number {
  457. return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
  458. }
  459. /**
  460. * Effective "Prefer lowest remaining filament" preference for a given printer,
  461. * gated on its AMS Filament Backup state (#1766).
  462. *
  463. * Without backup, the printer can't switch to a second spool when the picked
  464. * one runs out — so even with the user setting on, sorting toward the lowest
  465. * leaves the print at risk. Mirrors the backend gate in
  466. * `print_scheduler.py::_compute_ams_mapping_for_printer`. `null`/`undefined`
  467. * (unknown state, e.g. A1 family) preserves today's behaviour intentionally.
  468. */
  469. export function effectivePreferLowest(
  470. setting: boolean | undefined,
  471. amsFilamentBackup: boolean | null | undefined,
  472. ): boolean {
  473. if (!setting) return false;
  474. return amsFilamentBackup !== false;
  475. }
  476. /**
  477. * Auto-match a filament requirement to a loaded filament, respecting nozzle constraints.
  478. * Used by both single-printer (FilamentMapping) and multi-printer (InlineMappingEditor) paths.
  479. */
  480. export function autoMatchFilament(
  481. req: { type?: string; color?: string; nozzle_id?: number | null },
  482. loadedFilaments: { globalTrayId: number; amsId?: number; trayId?: number; type?: string; color?: string; extruderId?: number; remain?: number }[],
  483. usedTrayIds: Set<number>,
  484. preferLowest?: boolean,
  485. inventoryByTrayId?: Map<number, number>,
  486. ): typeof loadedFilaments[number] | undefined {
  487. let nozzleFilaments = filterFilamentsByNozzle(loadedFilaments, req.nozzle_id);
  488. if (preferLowest) {
  489. nozzleFilaments = [...nozzleFilaments].sort((a, b) =>
  490. compareSortKeys(
  491. preferLowestSortKey(a, inventoryByTrayId),
  492. preferLowestSortKey(b, inventoryByTrayId),
  493. ),
  494. );
  495. }
  496. const exactMatch = nozzleFilaments.find(
  497. (f) =>
  498. !usedTrayIds.has(f.globalTrayId) &&
  499. filamentTypesCompatible(f.type, req.type) &&
  500. normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color)
  501. );
  502. const similarMatch = exactMatch
  503. ? undefined
  504. : findNearestSimilar(
  505. nozzleFilaments.filter(
  506. (f) => !usedTrayIds.has(f.globalTrayId) && filamentTypesCompatible(f.type, req.type),
  507. ),
  508. req.color,
  509. (f) => f.color,
  510. );
  511. const typeOnlyMatch =
  512. exactMatch || similarMatch
  513. ? undefined
  514. : nozzleFilaments.find(
  515. (f) => !usedTrayIds.has(f.globalTrayId) && filamentTypesCompatible(f.type, req.type)
  516. );
  517. return exactMatch ?? similarMatch ?? typeOnlyMatch;
  518. }
  519. /**
  520. * Filter loaded filaments to those valid for a given nozzle requirement.
  521. * For single-nozzle printers (nozzle_id is null/undefined), returns all filaments.
  522. */
  523. export function filterFilamentsByNozzle<T extends { extruderId?: number }>(
  524. loadedFilaments: T[],
  525. nozzleId: number | undefined | null,
  526. ): T[] {
  527. return loadedFilaments.filter(
  528. (f) => nozzleId == null || f.extruderId === nozzleId
  529. );
  530. }
  531. /**
  532. * List the distinct nozzle diameters the printer actually reports (#2618).
  533. * Mirrors the backend `_installed_nozzle_diameters`: reads each
  534. * `status.nozzles[].nozzle_diameter`, skips the empty-string / non-positive
  535. * defaults that populate a NozzleInfo before MQTT fills it in, and dedupes.
  536. *
  537. * Returns e.g. `['0.4']` (single-nozzle) or `['0.4', '0.6']` (dual-nozzle). An
  538. * empty array means "the printer hasn't told us its nozzle hardware" — callers
  539. * that need to fetch per-nozzle should fall back to their own default rather
  540. * than treating it as "no nozzles". Preserves the bare decimal string form the
  541. * status carries so it can be passed straight to `getKProfiles`.
  542. */
  543. export function installedNozzleDiameters(
  544. status: { nozzles?: { nozzle_diameter?: string }[] } | null | undefined,
  545. ): string[] {
  546. const seen = new Set<string>();
  547. const result: string[] = [];
  548. for (const nozzle of status?.nozzles ?? []) {
  549. const raw = (nozzle?.nozzle_diameter ?? '').trim();
  550. if (!raw || !(parseFloat(raw) > 0) || seen.has(raw)) continue;
  551. seen.add(raw);
  552. result.push(raw);
  553. }
  554. return result;
  555. }
  556. /**
  557. * Resolve the installed nozzle diameter feeding a given AMS unit, so the
  558. * Configure-AMS-Slot picker filters filament presets by the nozzle actually on
  559. * the machine instead of assuming 0.4mm (#1899).
  560. *
  561. * On dual-nozzle printers (H2D) each AMS is bound to one extruder via
  562. * `ams_extruder_map` (amsId → extruder index), so we read that nozzle's
  563. * diameter. `status.nozzles` is indexed by extruder id -- [0] is the RIGHT
  564. * hotend and [1] the left, measured on an H2D fitted with 0.4 left / 0.6 right
  565. * -- so indexing it by the extruder is correct. (This comment used to say
  566. * "0=left/primary, 1=right", which was backwards; the code was always right.)
  567. * Single-nozzle printers have no map entry and fall back to index 0. Returns
  568. * undefined when the printer hasn't reported nozzle hardware yet, letting the
  569. * caller keep its own default.
  570. * Diameter is the bare decimal string the status carries, e.g. "0.4" / "0.6".
  571. */
  572. export function resolveSlotNozzleDiameter(
  573. status: {
  574. nozzles?: { nozzle_diameter?: string }[];
  575. ams_extruder_map?: Record<string, number>;
  576. } | null | undefined,
  577. amsId: number,
  578. ): string | undefined {
  579. const nozzles = status?.nozzles;
  580. if (!nozzles || nozzles.length === 0) return undefined;
  581. const extruderIdx = status?.ams_extruder_map?.[String(amsId)] ?? 0;
  582. const diameter = nozzles[extruderIdx]?.nozzle_diameter || nozzles[0]?.nozzle_diameter;
  583. return diameter || undefined;
  584. }
  585. /**
  586. * Detect Bambu Lab RFID-tagged spool by tray_uuid (32 hex) or tag_uid (16 hex).
  587. *
  588. * Permissive zero-string check: any non-zero non-empty value returns true. The
  589. * function exists to suppress assign/unassign actions on RFID-managed slots
  590. * whose state is owned by the printer firmware — manual changes there would be
  591. * overwritten on the next RFID re-read (eye → pen icon in BambuStudio).
  592. */
  593. export function isBambuLabSpool(tray: {
  594. tray_uuid?: string | null;
  595. tag_uid?: string | null;
  596. } | null | undefined): boolean {
  597. if (!tray) return false;
  598. if (tray.tray_uuid && tray.tray_uuid !== '00000000000000000000000000000000') return true;
  599. if (tray.tag_uid && tray.tag_uid !== '0000000000000000') return true;
  600. return false;
  601. }
  602. /**
  603. * Does a stored slot preset still describe what is in the slot?
  604. *
  605. * `slot_preset_mappings` remembers the preset a slot was last configured with,
  606. * and the AMS slot card shows that name ahead of anything the printer reports —
  607. * which is what lets a slot keep a hand-picked name like "# Bambu PLA Matte
  608. * @BBL H2C 0.4 nozzle (Custom)" instead of the plain catalog one. The cost is
  609. * that a swapped spool leaves the previous spool's name on the card until the
  610. * row is refetched, and until then a cached row outranks live telemetry.
  611. *
  612. * The printer's own `tray_info_idx` settles it, but only for official Bambu
  613. * presets, where the two id forms differ by one letter (setting_id `GFSA01` ↔
  614. * filament_id `GFA01`). A user preset genuinely carries two unrelated ids — a
  615. * slot configured with `PFUSa3b8b0c664c142` reports `tray_info_idx=P8a85d5a` —
  616. * and a local preset (`local_68`) has no printer-side id at all, so neither can
  617. * be checked here and both keep the stored name. Same for a slot reporting no
  618. * id (generic filament with no tag), which is the case the row exists for.
  619. *
  620. * Rows written since #3216 also record the filament id the slot was given
  621. * with the preset (`presetTrayInfoIdx`). That settles every kind of preset:
  622. * once the printer reports a different id, something else — the slicer's
  623. * Device tab, the printer's screen — re-configured the slot, and the row no
  624. * longer describes it.
  625. */
  626. export function slotPresetDescribesTray(
  627. presetId: string | null | undefined,
  628. trayInfoIdx: string | null | undefined,
  629. presetTrayInfoIdx?: string | null,
  630. ): boolean {
  631. const preset = (presetId || '').split('_')[0].toUpperCase();
  632. const tray = (trayInfoIdx || '').split('_')[0].toUpperCase();
  633. const recorded = (presetTrayInfoIdx || '').split('_')[0].toUpperCase();
  634. if (recorded && tray) return recorded === tray;
  635. if (!preset.startsWith('GFS') || !tray.startsWith('GF') || tray.startsWith('GFS')) return true;
  636. return `GF${preset.slice(3)}` === tray;
  637. }
  638. export interface AmsTrayLike {
  639. id: number;
  640. tray_type: string | null | undefined;
  641. tray_sub_brands: string | null | undefined;
  642. tray_color: string | null | undefined;
  643. tray_info_idx: string | null | undefined;
  644. }
  645. export interface AmsUnitLike {
  646. id: number;
  647. tray: AmsTrayLike[];
  648. }
  649. /**
  650. * One row in the AMS Backup modal: a group of slots that back each other up
  651. * (length >= 2), or a single non-empty slot with no peer (length === 1).
  652. */
  653. export interface BackupGroup {
  654. /** Stable key — same across renders for the same material+extruder. */
  655. key: string;
  656. /** Bambu preset ID (tray_info_idx) when matched on preset; null otherwise. */
  657. presetId: string | null;
  658. /** 0 = right / single, 1 = left. Scoping field for dual-nozzle. */
  659. extruder: number;
  660. /** Display name from the first slot's tray_sub_brands (or tray_type). */
  661. displayName: string;
  662. /** Tray colour from the first slot, for the swatch in the modal. */
  663. trayColor: string | null;
  664. /** Member slots, in (ams_id, slot_idx) order. */
  665. members: Array<{ amsId: number; slotIdx: number; globalTrayId: number }>;
  666. }
  667. /**
  668. * Canonicalise a hex colour for identity comparison. Mirrors the backend
  669. * `_normalize_color_for_id`. Strips the leading `#`, uppercases, and drops
  670. * the alpha channel when 8 chars long so `1A1A1AFF` matches `1A1A1A`.
  671. */
  672. function normalizeColorForId(raw: string | null | undefined): string {
  673. let s = (raw || '').trim().replace(/^#/, '').toUpperCase();
  674. if (s.length === 8) s = s.slice(0, 6);
  675. return s;
  676. }
  677. /**
  678. * Compute backup pairs for the AMS Backup modal (#1762).
  679. *
  680. * Strict identity rule (mirrors backend `_material_identity_internal` /
  681. * `_material_identity_spoolman`): slots pair ONLY when they share the same
  682. * Bambu preset ID (`tray_info_idx`, e.g. "GFA00") AND the same colour. The
  683. * preset identifies the filament profile (PETG HF, PLA Basic, etc.); the
  684. * colour pins the variant — three PETG HF spools in different colours
  685. * absolutely don't back each other up. User-tagged spools without a preset
  686. * never pair — Bambu's firmware backup logic relies on the preset, and
  687. * pairing on cosmetic name/colour match alone would let two visually-
  688. * identical but materially-different spools be treated as backups.
  689. *
  690. * Empty slots are skipped entirely. Every non-empty slot is returned — slots
  691. * without a peer come back as 1-member entries so the modal can list them as
  692. * "Slots without a backup peer".
  693. *
  694. * On dual-extruder printers (H2D / H2C / X2D), pairs are scoped per extruder
  695. * side — the firmware can't cross extruders even with the global backup bit
  696. * set.
  697. */
  698. export function computeBackupGroups(
  699. amsUnits: AmsUnitLike[] | undefined,
  700. amsExtruderMap: Record<string, number> | undefined,
  701. isDualNozzle: boolean,
  702. ): BackupGroup[] {
  703. if (!amsUnits || amsUnits.length === 0) return [];
  704. // Defensive dedup: ``status.ams`` is expected to be unique by `ams.id`, but
  705. // observed in the wild to occasionally contain duplicate entries (e.g. on
  706. // VP-aggregated switch printers or during MQTT partial-update merges). A
  707. // duplicate would surface as "AMS-A slot 1" rendered twice with different
  708. // materials, which is impossible physically and visually broken. First
  709. // occurrence per `ams.id` wins.
  710. const seenIds = new Set<number>();
  711. const uniqueAms: AmsUnitLike[] = [];
  712. for (const ams of amsUnits) {
  713. if (seenIds.has(ams.id)) continue;
  714. seenIds.add(ams.id);
  715. uniqueAms.push(ams);
  716. }
  717. const byKey = new Map<string, BackupGroup>();
  718. for (const ams of uniqueAms) {
  719. const extruder = isDualNozzle ? Number(amsExtruderMap?.[String(ams.id)] ?? 0) : 0;
  720. ams.tray.forEach((tray, slotIdx) => {
  721. if (!tray?.tray_type) return; // empty slot
  722. const preset = (tray.tray_info_idx || '').trim();
  723. const globalTrayId = getGlobalTrayId(ams.id, slotIdx, false);
  724. const member = { amsId: ams.id, slotIdx, globalTrayId };
  725. let key: string;
  726. let presetId: string | null;
  727. if (preset) {
  728. // Same Bambu profile is necessary but NOT sufficient — different colours
  729. // of the same PETG HF profile can't back each other up. Bake the colour
  730. // into the identity key, normalised to strip alpha and case.
  731. const color = normalizeColorForId(tray.tray_color);
  732. key = `preset:${preset}|color:${color}#${extruder}`;
  733. presetId = preset;
  734. } else {
  735. // No preset → never group with anything else. Unique-per-slot key.
  736. key = `unmatched:${ams.id}:${slotIdx}#${extruder}`;
  737. presetId = null;
  738. }
  739. const existing = byKey.get(key);
  740. if (existing) {
  741. existing.members.push(member);
  742. } else {
  743. byKey.set(key, {
  744. key,
  745. presetId,
  746. extruder,
  747. displayName: tray.tray_sub_brands || tray.tray_type || '',
  748. trayColor: tray.tray_color ?? null,
  749. members: [member],
  750. });
  751. }
  752. });
  753. }
  754. // Stable sort: extruder first (so the modal can section per side on
  755. // dual-nozzle), then pairs before lone slots, then by name, then by first
  756. // member's global tray id for deterministic rendering.
  757. return Array.from(byKey.values()).sort((a, b) => {
  758. if (a.extruder !== b.extruder) return a.extruder - b.extruder;
  759. const aLone = a.members.length === 1 ? 1 : 0;
  760. const bLone = b.members.length === 1 ? 1 : 0;
  761. if (aLone !== bLone) return aLone - bLone;
  762. if (a.displayName !== b.displayName) return a.displayName.localeCompare(b.displayName);
  763. return a.members[0].globalTrayId - b.members[0].globalTrayId;
  764. });
  765. }