amsHelpers.ts 38 KB

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