utils.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. import { api } from '../../api/client';
  2. import type { SlicerSetting, LocalPreset, BuiltinFilament, SpoolKProfileInput } from '../../api/client';
  3. import { installedNozzleDiameters } from '../../utils/amsHelpers';
  4. import { filamentIdToSettingId, settingIdToFilamentId } from '../../utils/filamentIds';
  5. import type { CalibrationProfile, ColorPreset, FilamentOption } from './types';
  6. import { KNOWN_VARIANTS, DEFAULT_BRANDS, RECENT_COLORS_KEY, MAX_RECENT_COLORS, STANDARD_NOZZLE_DIAMETERS } from './constants';
  7. /**
  8. * Fetch a printer's K-profiles across every nozzle it actually has installed
  9. * (#2618) and flatten them into CalibrationProfile rows for the PA-Profil
  10. * picker. `getKProfiles` filters strictly by nozzle diameter and defaults to
  11. * "0.4", so a single call hides non-0.4 profiles (e.g. a 0.6mm PAHT-CF K
  12. * value) — the picker then shows only one of two nozzle-specific profiles.
  13. * We query each installed diameter and merge. Falls back to "0.4" when the
  14. * printer hasn't reported nozzle hardware, preserving prior behaviour.
  15. * Per-diameter failures are swallowed (a printer that doesn't support the
  16. * endpoint just yields no rows), matching the callers' previous try/catch.
  17. */
  18. export async function fetchPrinterCalibrations(
  19. printerId: number,
  20. status: { nozzles?: { nozzle_diameter?: string }[] } | null | undefined,
  21. ): Promise<CalibrationProfile[]> {
  22. // Every standard size, plus anything unusual the printer reports as fitted --
  23. // not just the fitted ones. A K profile is stored on the printer per nozzle
  24. // diameter and survives a nozzle swap, so fetching only what is screwed in
  25. // right now made a 0.6 profile invisible until a 0.6 was fitted, and left the
  26. // user unable to prepare a spool for a nozzle they are about to change to.
  27. // A diameter the printer has nothing for answers with an empty list rather
  28. // than timing out, so the extra sizes cost a round trip each, not a stall --
  29. // provided they are sent one at a time, see below.
  30. const installed = installedNozzleDiameters(status);
  31. const toFetch = Array.from(new Set([...STANDARD_NOZZLE_DIAMETERS, ...installed]));
  32. // One diameter at a time, NOT in parallel. H2-series firmware answers only
  33. // the first one or two of a concurrent burst of `extrusion_cali_get` and
  34. // silently drops the rest, so each dropped request costs a 5s timeout before
  35. // it is retried: measured on an H2C and an H2D, four parallel requests took
  36. // 11s and 23s respectively, against ~1s when sent one after another. (An X1C
  37. // answers all four concurrently, which is why this went unnoticed while only
  38. // dual-diameter printers ever sent more than one.) Per-diameter failures are
  39. // still swallowed: a printer that doesn't support the endpoint yields no rows
  40. // rather than losing the diameters that did answer.
  41. const responses = [];
  42. for (const diameter of toFetch) {
  43. responses.push(await api.getKProfiles(printerId, diameter).catch(() => null));
  44. }
  45. const calibrations: CalibrationProfile[] = [];
  46. for (const res of responses) {
  47. if (!res) continue;
  48. for (const p of res.profiles) {
  49. calibrations.push({
  50. cali_idx: p.slot_id,
  51. filament_id: p.filament_id,
  52. setting_id: p.setting_id || '',
  53. name: p.name,
  54. k_value: parseFloat(p.k_value) || 0,
  55. n_coef: parseFloat(p.n_coef) || 0,
  56. extruder_id: p.extruder_id,
  57. nozzle_diameter: p.nozzle_diameter,
  58. nozzle_id: p.nozzle_id,
  59. });
  60. }
  61. }
  62. return calibrations;
  63. }
  64. // Fallback filament presets when cloud is not available. Each code is the
  65. // filament id Bambu gives that name (the table in backend/app/api/routes/cloud.py).
  66. // Most of them used to be wrong -- Bambu PLA-CF was filed under GFS00, which is
  67. // Support W, and the slot it configured would now come out as support (#3559).
  68. const FALLBACK_PRESETS: FilamentOption[] = [
  69. { code: 'GFA00', name: 'Bambu PLA Basic', displayName: 'Bambu PLA Basic', isCustom: false, allCodes: ['GFA00'], source: 'builtin' },
  70. { code: 'GFA01', name: 'Bambu PLA Matte', displayName: 'Bambu PLA Matte', isCustom: false, allCodes: ['GFA01'], source: 'builtin' },
  71. { code: 'GFL99', name: 'Generic PLA', displayName: 'Generic PLA', isCustom: false, allCodes: ['GFL99'], source: 'builtin' },
  72. { code: 'GFG00', name: 'Bambu PETG Basic', displayName: 'Bambu PETG Basic', isCustom: false, allCodes: ['GFG00'], source: 'builtin' },
  73. { code: 'GFG99', name: 'Generic PETG', displayName: 'Generic PETG', isCustom: false, allCodes: ['GFG99'], source: 'builtin' },
  74. { code: 'GFB00', name: 'Bambu ABS', displayName: 'Bambu ABS', isCustom: false, allCodes: ['GFB00'], source: 'builtin' },
  75. { code: 'GFB99', name: 'Generic ABS', displayName: 'Generic ABS', isCustom: false, allCodes: ['GFB99'], source: 'builtin' },
  76. { code: 'GFB01', name: 'Bambu ASA', displayName: 'Bambu ASA', isCustom: false, allCodes: ['GFB01'], source: 'builtin' },
  77. { code: 'GFU01', name: 'Bambu TPU 95A', displayName: 'Bambu TPU 95A', isCustom: false, allCodes: ['GFU01'], source: 'builtin' },
  78. { code: 'GFU99', name: 'Generic TPU', displayName: 'Generic TPU', isCustom: false, allCodes: ['GFU99'], source: 'builtin' },
  79. { code: 'GFC00', name: 'Bambu PC', displayName: 'Bambu PC', isCustom: false, allCodes: ['GFC00'], source: 'builtin' },
  80. { code: 'GFN99', name: 'Generic PA', displayName: 'Generic PA', isCustom: false, allCodes: ['GFN99'], source: 'builtin' },
  81. { code: 'GFA50', name: 'Bambu PLA-CF', displayName: 'Bambu PLA-CF', isCustom: false, allCodes: ['GFA50'], source: 'builtin' },
  82. { code: 'GFG50', name: 'Bambu PETG-CF', displayName: 'Bambu PETG-CF', isCustom: false, allCodes: ['GFG50'], source: 'builtin' },
  83. { code: 'GFN03', name: 'Bambu PA-CF', displayName: 'Bambu PA-CF', isCustom: false, allCodes: ['GFN03'], source: 'builtin' },
  84. { code: 'GFS04', name: 'Bambu PVA', displayName: 'Bambu PVA', isCustom: false, allCodes: ['GFS04'], source: 'builtin' },
  85. ];
  86. // Parse a slicer preset name to extract brand, material, and variant
  87. export function parsePresetName(name: string): { brand: string; material: string; variant: string } {
  88. // Remove @printer suffix (e.g., "@Bambu Lab H2D 0.4 nozzle")
  89. let cleanName = name.replace(/@.*$/, '').trim();
  90. // Remove (Custom) tag
  91. cleanName = cleanName.replace(/\(Custom\)/i, '').trim();
  92. // Remove leading # or * markers
  93. cleanName = cleanName.replace(/^[#*]+\s*/, '').trim();
  94. // Materials list - order matters (longer/more specific first)
  95. const materials = [
  96. 'PLA-CF', 'PETG-CF', 'ABS-GF', 'ASA-CF', 'PA-CF', 'PAHT-CF', 'PA6-CF', 'PA6-GF',
  97. 'PPA-CF', 'PPA-GF', 'PET-CF', 'PPS-CF', 'PC-CF', 'PC-ABS', 'ABS-GF',
  98. 'PCTG', 'PETG', 'PLA', 'ABS', 'ASA', 'PC', 'PA', 'TPU', 'PVA', 'HIPS', 'BVOH', 'PPS', 'PEEK', 'PEI',
  99. ];
  100. // Find material in the name
  101. let material = '';
  102. let materialIdx = -1;
  103. for (const m of materials) {
  104. const idx = cleanName.toUpperCase().indexOf(m.toUpperCase());
  105. if (idx !== -1) {
  106. material = m;
  107. materialIdx = idx;
  108. break;
  109. }
  110. }
  111. // Brand is everything before the material
  112. let brand = '';
  113. if (materialIdx > 0) {
  114. brand = cleanName.substring(0, materialIdx).trim();
  115. brand = brand.replace(/[-_\s]+$/, '');
  116. }
  117. // Everything after material is potential variant
  118. let afterMaterial = '';
  119. if (materialIdx !== -1 && material) {
  120. afterMaterial = cleanName.substring(materialIdx + material.length).trim();
  121. afterMaterial = afterMaterial.replace(/^[-_\s]+/, '');
  122. }
  123. // Check for known variant - could be before OR after material
  124. let variant = '';
  125. // First check after material (most common)
  126. for (const v of KNOWN_VARIANTS) {
  127. if (afterMaterial.toLowerCase().includes(v.toLowerCase())) {
  128. variant = v;
  129. break;
  130. }
  131. }
  132. // If no variant found after material, check if brand contains a known variant
  133. if (!variant && brand) {
  134. for (const v of KNOWN_VARIANTS) {
  135. const variantPattern = new RegExp(`\\s+${v}$`, 'i');
  136. if (variantPattern.test(brand)) {
  137. variant = v;
  138. brand = brand.replace(variantPattern, '').trim();
  139. break;
  140. }
  141. }
  142. }
  143. return { brand, material, variant };
  144. }
  145. // Extract unique brands from cloud presets and local presets
  146. export function extractBrandsFromPresets(presets: SlicerSetting[], localPresets?: LocalPreset[]): string[] {
  147. const brandSet = new Set<string>(DEFAULT_BRANDS);
  148. for (const preset of presets) {
  149. const { brand } = parsePresetName(preset.name);
  150. if (brand && brand.length > 1) {
  151. brandSet.add(brand);
  152. }
  153. }
  154. // Also extract brands from local presets
  155. if (localPresets) {
  156. for (const preset of localPresets) {
  157. if (preset.filament_vendor && preset.filament_vendor.length > 1) {
  158. brandSet.add(preset.filament_vendor);
  159. } else {
  160. const { brand } = parsePresetName(preset.name);
  161. if (brand && brand.length > 1) {
  162. brandSet.add(brand);
  163. }
  164. }
  165. }
  166. }
  167. return Array.from(brandSet).sort((a, b) => a.localeCompare(b));
  168. }
  169. // Build filament options from local presets (OrcaSlicer / BambuStudio imports).
  170. // Each preset gets its own entry — no base-name collapse — so the spool form
  171. // shows all per-printer/per-nozzle variants the user has imported. The spool
  172. // itself is printer-agnostic, so the variant the user picks just becomes the
  173. // stored slicer_filament code (consumed by normalize_slicer_filament during
  174. // slicing — kept as preset.filament_type when available so the existing
  175. // "GFL05"-style normalisation still resolves).
  176. function buildLocalFilamentOptions(localPresets: LocalPreset[]): FilamentOption[] {
  177. const filamentPresets = localPresets.filter(p => p.preset_type === 'filament');
  178. if (filamentPresets.length === 0) return [];
  179. const options: FilamentOption[] = filamentPresets.map(preset => {
  180. // Use the unique preset.id (stringified) as the code so each local preset
  181. // has its own identity. Earlier this was preset.filament_type (e.g. "PLA")
  182. // which collapsed every PLA local preset onto the same code — picking any
  183. // of them saved slicer_filament="PLA", a material name the backend cannot
  184. // resolve back to a specific preset row. The backend handler at
  185. // inventory.py expects numeric IDs for local-preset slicer_filament values.
  186. // allCodes still carries the legacy filament_type so findPresetOption
  187. // resolves existing saved spools that have the old material-name code.
  188. const code = String(preset.id);
  189. const legacyCode = preset.filament_type || code;
  190. const allCodes = Array.from(new Set([code, legacyCode]));
  191. return {
  192. code,
  193. name: preset.name,
  194. displayName: preset.name,
  195. isCustom: false,
  196. allCodes,
  197. source: 'local',
  198. };
  199. });
  200. return options.sort((a, b) => a.displayName.localeCompare(b.displayName));
  201. }
  202. // Build filament options by merging cloud presets, local profiles, and built-in
  203. // filaments — matching the behavior of ConfigureAmsSlotModal and the wiki's
  204. // "Where Presets Come From" section. Earlier versions were precedence-based
  205. // (cloud-only when cloud had any presets), which silently hid Local Profiles
  206. // from users logged into Bambu Cloud — see #1248.
  207. export function buildFilamentOptions(
  208. cloudPresets: SlicerSetting[],
  209. configuredPrinterModels: Set<string>,
  210. localPresets?: LocalPreset[],
  211. builtinFilaments?: BuiltinFilament[],
  212. // Which of the cloud presets came from Orca Cloud rather than Bambu Cloud.
  213. // The two are merged into one list by the callers (OrcaProfileMeta is
  214. // structurally identical to SlicerSetting), so the distinction has to be
  215. // carried in rather than derived -- and it is worth carrying, because the
  216. // origin badge is the only thing telling a user which cloud a preset is in.
  217. orcaSettingIds?: Set<string>,
  218. ): FilamentOption[] {
  219. const customPresets: FilamentOption[] = [];
  220. const defaultPresets: FilamentOption[] = [];
  221. const cloudCodes = new Set<string>();
  222. // 1. Cloud presets — each setting_id gets its own entry. The spool form is
  223. // printer-agnostic so we deliberately do NOT collapse "@P1S" / "@X1C"
  224. // variants into a single row; the user picks the variant they want and
  225. // its setting_id is what gets persisted.
  226. for (const preset of cloudPresets) {
  227. if (preset.is_custom) {
  228. const presetNameUpper = preset.name.toUpperCase();
  229. const matchesPrinter = configuredPrinterModels.size === 0 ||
  230. Array.from(configuredPrinterModels).some(model => presetNameUpper.includes(model)) ||
  231. !presetNameUpper.includes('@');
  232. if (matchesPrinter) {
  233. customPresets.push({
  234. code: preset.setting_id,
  235. name: preset.name,
  236. displayName: `${preset.name} (Custom)`,
  237. isCustom: true,
  238. allCodes: [preset.setting_id],
  239. source: orcaSettingIds?.has(preset.setting_id) ? 'orca_cloud' : 'cloud',
  240. });
  241. cloudCodes.add(preset.setting_id);
  242. }
  243. } else {
  244. defaultPresets.push({
  245. code: preset.setting_id,
  246. name: preset.name,
  247. displayName: preset.name,
  248. isCustom: false,
  249. allCodes: [preset.setting_id],
  250. source: orcaSettingIds?.has(preset.setting_id) ? 'orca_cloud' : 'cloud',
  251. });
  252. cloudCodes.add(preset.setting_id);
  253. }
  254. }
  255. // 2. Local profiles (OrcaSlicer / BambuStudio imports)
  256. const localOptions = localPresets && localPresets.length > 0
  257. ? buildLocalFilamentOptions(localPresets)
  258. : [];
  259. // 3. Built-in filaments — only those not already represented by a cloud preset.
  260. // Cloud setting_ids look like "GFSA00", built-in filament_ids look like "GFA00";
  261. // map between the two so we don't render the same filament twice.
  262. const builtinOptions: FilamentOption[] = [];
  263. if (builtinFilaments && builtinFilaments.length > 0) {
  264. for (const bf of builtinFilaments) {
  265. const settingId = filamentIdToSettingId(bf.filament_id);
  266. if (cloudCodes.has(bf.filament_id) || cloudCodes.has(settingId)) continue;
  267. builtinOptions.push({
  268. code: bf.filament_id,
  269. name: bf.name,
  270. displayName: bf.name,
  271. isCustom: false,
  272. allCodes: [bf.filament_id, settingId],
  273. source: 'builtin',
  274. });
  275. }
  276. }
  277. const merged = [
  278. ...customPresets,
  279. ...defaultPresets,
  280. ...localOptions,
  281. ...builtinOptions,
  282. ];
  283. // 4. Hardcoded fallback only when literally every source is empty.
  284. if (merged.length === 0) return FALLBACK_PRESETS;
  285. return merged.sort((a, b) => a.displayName.localeCompare(b.displayName));
  286. }
  287. // Find selected preset option
  288. export function findPresetOption(
  289. slicerFilament: string,
  290. filamentOptions: FilamentOption[],
  291. ): FilamentOption | undefined {
  292. if (!slicerFilament) return undefined;
  293. // First try exact match on primary code
  294. let option = filamentOptions.find(o => o.code === slicerFilament);
  295. if (!option) {
  296. // Try matching against any code in allCodes
  297. option = filamentOptions.find(o => o.allCodes.includes(slicerFilament));
  298. }
  299. if (!option) {
  300. // Try case-insensitive match
  301. const slicerLower = slicerFilament.toLowerCase();
  302. option = filamentOptions.find(o =>
  303. o.code.toLowerCase() === slicerLower ||
  304. o.allCodes.some(c => c.toLowerCase() === slicerLower),
  305. );
  306. }
  307. return option;
  308. }
  309. // Keep the value a spool already carries selectable in its own dropdown (#1905).
  310. // A brand or material entered as a custom value isn't part of the color catalog
  311. // or any slicer preset, so without this the edit form offered no way back to it
  312. // once the user opened the dropdown.
  313. export function withCurrentValue(options: string[], current: string): string[] {
  314. const trimmed = current.trim();
  315. if (!trimmed || options.some(o => o.toLowerCase() === trimmed.toLowerCase())) return options;
  316. return [...options, trimmed].sort((a, b) => a.localeCompare(b));
  317. }
  318. // Brands/materials the catalog and slicer presets pair with the other field's
  319. // current value (#1905). Used to rank the dropdown, never to filter it — the
  320. // pairs are incomplete (Elegoo ships ASA even though the catalog only knows its
  321. // PLA), and hiding the rest made valid entries look impossible.
  322. export function pairedOptions(
  323. options: string[],
  324. counterpart: string,
  325. pairMap: Map<string, Set<string>>,
  326. ): string[] {
  327. if (!counterpart) return [];
  328. const keys = pairMap.get(counterpart.toLowerCase());
  329. if (!keys || keys.size === 0) return [];
  330. return options.filter(o => keys.has(o.toLowerCase()));
  331. }
  332. // Recent colors management
  333. export function loadRecentColors(): ColorPreset[] {
  334. try {
  335. const stored = localStorage.getItem(RECENT_COLORS_KEY);
  336. if (stored) {
  337. return JSON.parse(stored) as ColorPreset[];
  338. }
  339. } catch {
  340. // Ignore errors
  341. }
  342. return [];
  343. }
  344. export function saveRecentColor(color: ColorPreset, currentRecent: ColorPreset[]): ColorPreset[] {
  345. const filtered = currentRecent.filter(
  346. c => c.hex.toUpperCase() !== color.hex.toUpperCase(),
  347. );
  348. const updated = [color, ...filtered].slice(0, MAX_RECENT_COLORS);
  349. try {
  350. localStorage.setItem(RECENT_COLORS_KEY, JSON.stringify(updated));
  351. } catch {
  352. // Ignore errors
  353. }
  354. return updated;
  355. }
  356. // Normalise a Bambu filament identifier to its bare filament_id form (#1688).
  357. // Spools store ``slicer_filament`` as a setting_id like "GFSG98_09" (the "_NN"
  358. // suffix is the variant, the "S" infix marks it as a setting_id); printer
  359. // K-profiles store ``filament_id`` as "GFG98" (bare). Both shapes need
  360. // normalising before comparison. The rule and its exceptions (SUNLU, a few
  361. // P1/X1 presets, #3387) live in ``utils/filamentIds``.
  362. //
  363. // Non-Bambu IDs (numeric local-preset IDs, Orca UUIDs) are returned unchanged
  364. // uppercase — they won't match any K-profile's filament_id and the caller
  365. // falls through to name-based matching.
  366. export function toFilamentId(id: string | null | undefined): string {
  367. return settingIdToFilamentId((id || '').toUpperCase());
  368. }
  369. // "GFx99" identifiers (GFL99, GFG99, GFB99, ...) are Bambu's *generic* filament
  370. // IDs — one per material, shared across every physical filament the user hasn't
  371. // given a specific preset. They still identify a material unambiguously, so an
  372. // exact generic id match is only ambiguous about *brand*, never about material.
  373. export function isGenericFilamentId(id: string | null | undefined): boolean {
  374. return !!id && /^GF[A-Z]99$/i.test(id);
  375. }
  376. // The material each generic Bambu filament ID stands for. Used to sanity-check
  377. // a generic id-match against the material the caller already knows (#2710): a
  378. // PETG spool must never claim GFL99 (generic PLA) profiles just because both
  379. // sides happen to have stored the same generic id.
  380. const GENERIC_FILAMENT_MATERIALS: Record<string, string> = {
  381. GFB99: 'ABS',
  382. GFC99: 'PC',
  383. GFG99: 'PETG',
  384. GFL99: 'PLA',
  385. GFN99: 'PA',
  386. GFP99: 'PE',
  387. GFR99: 'EVA',
  388. GFS99: 'PVA',
  389. GFU99: 'TPU',
  390. };
  391. // Material a generic filament ID stands for ("GFL99" → "PLA"), or '' when the
  392. // ID isn't a known generic one.
  393. export function materialForGenericFilamentId(id: string | null | undefined): string {
  394. if (!id) return '';
  395. return GENERIC_FILAMENT_MATERIALS[id.toUpperCase()] || '';
  396. }
  397. // Bambu labels nylon "PA"; users routinely type "Nylon". Compare materials
  398. // through this so the two spellings agree.
  399. function normaliseMaterial(material: string): string {
  400. const upper = material.trim().toUpperCase();
  401. return upper === 'NYLON' ? 'PA' : upper;
  402. }
  403. // True when a generic filament ID may stand in for the given material — i.e.
  404. // the ID is generic and describes that same material.
  405. export function genericFilamentIdMatchesMaterial(id: string, material: string): boolean {
  406. const generic = materialForGenericFilamentId(id);
  407. return !!generic && !!material && normaliseMaterial(generic) === normaliseMaterial(material);
  408. }
  409. // Check if a calibration matches based on brand, material, and variant
  410. /**
  411. * Key one hotend's K-profile selection: printer, extruder, nozzle diameter.
  412. *
  413. * All three because that is what both K tables are keyed on -- a K value is
  414. * measured on one individual hotend, and cali_idx alone cannot identify one
  415. * (the printer numbers its calibration table PER NOZZLE, so index 16 exists on
  416. * both hotends of a dual-nozzle machine meaning different things).
  417. */
  418. export function hotendKey(printerId: number, extruder: number, diameter: string): string {
  419. return `${printerId}:${extruder}:${diameter}`;
  420. }
  421. /**
  422. * K profiles picked for a new spool, plus its product's profile default
  423. * (#1326) for every hotend nothing was picked for. For a page that saves a
  424. * new spool's K profiles without showing the default: the save replaces the
  425. * whole list, so the default the create applied would otherwise be lost. A
  426. * failed lookup returns the picks alone.
  427. */
  428. export async function withProductDefaultKProfiles(
  429. picked: SpoolKProfileInput[],
  430. product: { brand: string; material: string; subtype: string; color_name: string },
  431. ): Promise<SpoolKProfileInput[]> {
  432. const keyOf = (k: SpoolKProfileInput) =>
  433. hotendKey(k.printer_id, k.extruder ?? 0, (k.nozzle_diameter || '').trim() || '0.4');
  434. let resolved: Awaited<ReturnType<typeof api.resolveProfileDefault>>;
  435. try {
  436. resolved = await api.resolveProfileDefault({
  437. brand: product.brand.trim(),
  438. material: product.material.trim(),
  439. subtype: product.subtype.trim(),
  440. color_name: product.color_name.trim(),
  441. });
  442. } catch {
  443. return picked;
  444. }
  445. const taken = new Set(picked.map(keyOf));
  446. const merged = [...picked];
  447. for (const k of resolved?.k_profiles ?? []) {
  448. if (taken.has(keyOf(k))) continue;
  449. merged.push(k);
  450. taken.add(keyOf(k));
  451. }
  452. return merged;
  453. }
  454. /**
  455. * The Printers tab's selection, one entry per hotend, from stored K profiles:
  456. * a spool's, or a profile default's. The stored row carries everything the
  457. * picker needs to show the selection before the printer answers, so an
  458. * offline printer still renders what was chosen for it. Rows without a
  459. * calibration slot are skipped -- there is nothing on the printer to select.
  460. */
  461. export function selectionFromKProfiles(rows: SpoolKProfileInput[]): Map<string, CalibrationProfile> {
  462. const chosen = new Map<string, CalibrationProfile>();
  463. for (const p of rows) {
  464. if (p.cali_idx === null || p.cali_idx === undefined) continue;
  465. const diameter = (p.nozzle_diameter || '').trim() || '0.4';
  466. const extruder = p.extruder ?? 0;
  467. chosen.set(hotendKey(p.printer_id, extruder, diameter), {
  468. cali_idx: p.cali_idx,
  469. filament_id: '',
  470. setting_id: p.setting_id || '',
  471. name: p.name || '',
  472. k_value: p.k_value,
  473. n_coef: 0,
  474. extruder_id: extruder,
  475. nozzle_diameter: diameter,
  476. // Stored as the bare flow code; the picker re-derives its label
  477. // from the same field it reads off a live profile.
  478. nozzle_id: p.nozzle_type || '',
  479. });
  480. }
  481. return chosen;
  482. }
  483. /**
  484. * Key one per-printer-model preset override.
  485. *
  486. * Diameter "" is the model's own default and a bare decimal is a per-hotend
  487. * exception, matching the (printer_model, nozzle_diameter) pair the backend
  488. * stores. The separator is a NUL because a model name is free text from the
  489. * printer ("A1 mini") and must never be able to collide with a diameter.
  490. */
  491. export function presetKey(model: string, diameter: string): string {
  492. return `${model}\u0000${diameter}`;
  493. }
  494. /** Split a `presetKey` back into its model and diameter. */
  495. export function parsePresetKey(key: string): { model: string; diameter: string } {
  496. const [model = '', diameter = ''] = key.split('\u0000');
  497. return { model, diameter };
  498. }
  499. export function isMatchingCalibration(
  500. cal: { name?: string; filament_id?: string },
  501. formData: { material: string; brand: string; subtype: string; slicer_filament?: string },
  502. ): boolean {
  503. if (!formData.material) return false;
  504. // Preferred path: exact filament_id match after normalising both sides
  505. // (#1688). When the spool has a non-generic preset assigned and it agrees
  506. // with the K-profile's filament_id, this is unambiguous — no name parsing
  507. // needed. A spool storing "GFSG98_09" matches a K-profile with filament_id
  508. // "GFG98" without going anywhere near parsePresetName.
  509. const spoolFid = toFilamentId(formData.slicer_filament);
  510. const calFid = toFilamentId(cal.filament_id);
  511. if (spoolFid && calFid && spoolFid === calFid) {
  512. if (!isGenericFilamentId(calFid)) {
  513. return true;
  514. }
  515. // Both sides carry the same *generic* id (#2710). That still pins the
  516. // material, so the only thing left ambiguous is brand — a printer holds
  517. // one flat calibration table per generic id and users routinely name
  518. // those entries by colour ("Dark Brown", "Marble"), which no amount of
  519. // name parsing can tie back to a material. Accept the match when the
  520. // material agrees and the spool claims no brand of its own; a spool that
  521. // does name a brand keeps the stricter name-based path below so its
  522. // suggestions stay brand-specific.
  523. const brand = formData.brand.trim();
  524. const brandIsGeneric = !brand || brand.toUpperCase() === 'GENERIC';
  525. if (brandIsGeneric && genericFilamentIdMatchesMaterial(calFid, formData.material)) {
  526. return true;
  527. }
  528. }
  529. const profileName = cal.name || '';
  530. // Remove flow type prefixes
  531. const cleanName = profileName
  532. .replace(/^High Flow[_\s]+/i, '')
  533. .replace(/^Standard[_\s]+/i, '')
  534. .replace(/^HF[_\s]+/i, '')
  535. .replace(/^S[_\s]+/i, '')
  536. .trim();
  537. const parsed = parsePresetName(cleanName);
  538. // Match material (required)
  539. const materialMatch = parsed.material.toUpperCase() === formData.material.toUpperCase();
  540. if (!materialMatch) return false;
  541. // Match brand if specified in form
  542. if (formData.brand) {
  543. const brandMatch = parsed.brand.toLowerCase().includes(formData.brand.toLowerCase()) ||
  544. formData.brand.toLowerCase().includes(parsed.brand.toLowerCase());
  545. if (!brandMatch) return false;
  546. }
  547. // Match variant/subtype if specified in form
  548. if (formData.subtype) {
  549. const variantMatch = parsed.variant.toLowerCase().includes(formData.subtype.toLowerCase()) ||
  550. formData.subtype.toLowerCase().includes(parsed.variant.toLowerCase()) ||
  551. cleanName.toLowerCase().includes(formData.subtype.toLowerCase());
  552. if (!variantMatch) return false;
  553. }
  554. return true;
  555. }