bambu-printer-mcp 1.1.62 → 1.1.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/counterpart/discovery.d.ts +85 -0
- package/dist/counterpart/discovery.js +119 -0
- package/dist/counterpart/filaments.d.ts +307 -0
- package/dist/counterpart/filaments.js +273 -0
- package/dist/counterpart/setup.d.ts +292 -0
- package/dist/counterpart/setup.js +91 -0
- package/dist/index.js +128 -0
- package/dist/safety/printer-state.d.ts +1 -0
- package/dist/safety/printer-state.js +1 -1
- package/dist/tool-annotations.js +3 -0
- package/package.json +1 -1
- package/src/counterpart/discovery.ts +111 -0
- package/src/counterpart/filaments.ts +297 -0
- package/src/counterpart/setup.ts +127 -0
- package/src/index.ts +120 -0
- package/src/safety/printer-state.ts +1 -1
- package/src/tool-annotations.ts +3 -0
package/dist/index.js
CHANGED
|
@@ -30,6 +30,9 @@ import { isDualNozzleModel } from "./safety/limits.js";
|
|
|
30
30
|
import { withPrinterOperation, withPrintSnapshot, uniquePrintName } from "./safety/artifact.js";
|
|
31
31
|
import { detectProfilesRoot } from "./slicer/profile-flatten.js";
|
|
32
32
|
import { bambuPrinterInfo, bambuSliceCapabilities } from "./counterpart/info.js";
|
|
33
|
+
import { DISCOVER_OUTPUT_SCHEMA, discoverBambu } from "./counterpart/discovery.js";
|
|
34
|
+
import { SETUP_FIELDS_OUTPUT_SCHEMA, bambuSetupFields, slicerSetup } from "./counterpart/setup.js";
|
|
35
|
+
import { PROPOSE_FILAMENTS_INPUT_PROPERTIES, PROPOSE_FILAMENTS_OUTPUT_SCHEMA, NO_COLOUR_NAMES, bambuTrayLabel, loadColourNames, proposeFilaments, spoolName } from "./counterpart/filaments.js";
|
|
33
36
|
import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, SERVER_INSTRUCTIONS } from "./design-guidance.js";
|
|
34
37
|
import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
|
|
35
38
|
import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
|
|
@@ -100,6 +103,7 @@ const SERVER_INFO = {
|
|
|
100
103
|
/** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
|
|
101
104
|
const OUTPUT_SCHEMA_TOOLS = new Set([
|
|
102
105
|
"counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
|
|
106
|
+
"counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
|
|
103
107
|
"fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
|
|
104
108
|
"camera_stream_start", "camera_frame", "camera_stream_stop",
|
|
105
109
|
]);
|
|
@@ -241,6 +245,61 @@ const FILAMENT_MODEL_CODES = {
|
|
|
241
245
|
};
|
|
242
246
|
const COLLAR_CHARM_POLICY = getCollarCharmRolePolicy();
|
|
243
247
|
let filamentProfileIndexCache = null;
|
|
248
|
+
/** The configured slicer's BBL filament profile folder, when the slicer configuration resolves. */
|
|
249
|
+
function filamentProfileDirectory() {
|
|
250
|
+
try {
|
|
251
|
+
const { slicerType, slicerPath } = resolveSlicerConfig(undefined);
|
|
252
|
+
return path.join(detectProfilesRoot(slicerPath, slicerType), "BBL", "filament");
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/** An executable path, or a bare command found on PATH. */
|
|
259
|
+
function executableExists(command) {
|
|
260
|
+
if (!command)
|
|
261
|
+
return false;
|
|
262
|
+
if (command.includes("/") || command.includes("\\"))
|
|
263
|
+
return fs.existsSync(command);
|
|
264
|
+
return (process.env.PATH ?? "").split(path.delimiter).some(dir => dir && fs.existsSync(path.join(dir, command)));
|
|
265
|
+
}
|
|
266
|
+
/** A Bambu profile tree: BBL's machine profiles, or Orca's packed BBL.opc. */
|
|
267
|
+
function bblProfilesAt(root) {
|
|
268
|
+
return fs.existsSync(path.join(root, "BBL", "machine")) || fs.existsSync(path.join(root, "BBL.opc"));
|
|
269
|
+
}
|
|
270
|
+
/** The slicer this server would run now and the settings that choose it, for counterpart_setup_fields. */
|
|
271
|
+
function slicerSetupNow() {
|
|
272
|
+
let config;
|
|
273
|
+
try {
|
|
274
|
+
config = resolveSlicerConfig(undefined);
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
config = { slicerType: String(DEFAULT_SLICER_TYPE), slicerPath: "" };
|
|
278
|
+
}
|
|
279
|
+
if (config.slicerType === "orca-slicer-api")
|
|
280
|
+
return slicerSetup({ types: SLICER_TYPES, type: config.slicerType, found: Boolean(process.env.SLICER_API_URL), remote: true });
|
|
281
|
+
const bbl = ["bambustudio", "orcaslicer", "orcaslicer-bambulab"].includes(config.slicerType);
|
|
282
|
+
let profilesRoot;
|
|
283
|
+
try {
|
|
284
|
+
profilesRoot = bbl ? detectProfilesRoot(config.slicerPath, config.slicerType) : undefined;
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
profilesRoot = undefined;
|
|
288
|
+
}
|
|
289
|
+
return slicerSetup({ types: SLICER_TYPES, type: config.slicerType, path: config.slicerPath, found: executableExists(config.slicerPath),
|
|
290
|
+
...(bbl ? { profilesFound: Boolean(profilesRoot && bblProfilesAt(profilesRoot)), ...(profilesRoot ? { profilesRoot } : {}) } : {}) });
|
|
291
|
+
}
|
|
292
|
+
let colourNamesCache = null;
|
|
293
|
+
/** Bambu Studio's own colour names for its filaments, read once from the configured slicer's profiles. */
|
|
294
|
+
function colourNames() {
|
|
295
|
+
if (colourNamesCache)
|
|
296
|
+
return colourNamesCache;
|
|
297
|
+
const names = loadColourNames(filamentProfileDirectory());
|
|
298
|
+
// A slicer installed later still names its colours: only a table that loaded is kept.
|
|
299
|
+
if (names !== NO_COLOUR_NAMES)
|
|
300
|
+
colourNamesCache = names;
|
|
301
|
+
return names;
|
|
302
|
+
}
|
|
244
303
|
function buildFilamentProfileIndex() {
|
|
245
304
|
const byName = new Map();
|
|
246
305
|
const baseNameByFilamentId = new Map();
|
|
@@ -380,6 +439,8 @@ function normalizePrinterFilamentInventory(status, bambuModel, nozzleDiameter) {
|
|
|
380
439
|
profile_resolution: profileResolution.resolution,
|
|
381
440
|
match_confidence: matchConfidence,
|
|
382
441
|
display_name: displayParts.length > 0 ? displayParts.join(" ") : "empty/unknown",
|
|
442
|
+
label: amsId !== null && trayId !== null ? bambuTrayLabel(amsId, trayId) : null,
|
|
443
|
+
spool_name: trayType ? spoolName(traySubBrands || trayType, trayInfoIdx && trayColor ? colourNames().spool(trayInfoIdx, trayColor) : undefined) : null,
|
|
383
444
|
profile_candidates: profileResolution.paths,
|
|
384
445
|
});
|
|
385
446
|
}
|
|
@@ -2889,6 +2950,44 @@ class BambuPrinterMCPServer {
|
|
|
2889
2950
|
},
|
|
2890
2951
|
outputSchema: PRINTER_INFO_OUTPUT_SCHEMA
|
|
2891
2952
|
},
|
|
2953
|
+
{
|
|
2954
|
+
name: "counterpart_discover_printers",
|
|
2955
|
+
description: "Counterpart contract (counterpart/1): Bambu printers on the local network, from their own SSDP announcements (UDP 2021), with serial, model (as bambu_model names it), name and firmware. Listens for duration_ms (default 4000). network is \"unavailable\" when another app holds the port. Never connects to or authenticates with a printer.",
|
|
2956
|
+
inputSchema: {
|
|
2957
|
+
type: "object",
|
|
2958
|
+
properties: { duration_ms: { type: "integer", minimum: 500, maximum: 15000, description: "How long to listen (default 4000)." } },
|
|
2959
|
+
additionalProperties: false
|
|
2960
|
+
},
|
|
2961
|
+
outputSchema: DISCOVER_OUTPUT_SCHEMA
|
|
2962
|
+
},
|
|
2963
|
+
{
|
|
2964
|
+
name: "counterpart_setup_fields",
|
|
2965
|
+
description: "Counterpart contract (counterpart/1): the printers this server drives and the settings it reads for each, by .env variable name (first canonical, then aliases): label, hint, whether required, the model choices and the model each serial-number prefix names. Pass serial to get the model it names. Sends nothing to a printer and returns no configured values.",
|
|
2966
|
+
inputSchema: {
|
|
2967
|
+
type: "object",
|
|
2968
|
+
properties: { serial: { type: "string", maxLength: 64, description: "A Bambu serial number: model is the one it names, when known." } },
|
|
2969
|
+
additionalProperties: false
|
|
2970
|
+
},
|
|
2971
|
+
outputSchema: SETUP_FIELDS_OUTPUT_SCHEMA
|
|
2972
|
+
},
|
|
2973
|
+
{
|
|
2974
|
+
name: "counterpart_propose_filaments",
|
|
2975
|
+
description: "Counterpart contract (counterpart/1): which loaded AMS spool prints each of a model's colours, before slicing. Reads the live AMS once. trays lists the spools a person may choose (label like \"A2\", a person-readable name, colour, material, feed). proposal gives each filament its nearest spool in OKLab colour with the asked-for material preferred, and a verdict: same-colour, closest (that colour isn't loaded; note says so), no-colour or none. One print feeds from one source. Pass chosen to check the person's spools against what is loaded now; mapping then lists every filament slot's spool (painted slots included), and problems says why a choice can't print.",
|
|
2976
|
+
inputSchema: {
|
|
2977
|
+
type: "object",
|
|
2978
|
+
properties: {
|
|
2979
|
+
...PROPOSE_FILAMENTS_INPUT_PROPERTIES,
|
|
2980
|
+
bambu_model: { type: "string", description: "Printer model; defaults to BAMBU_MODEL. Selects the filament profiles that decide which spools can slice." },
|
|
2981
|
+
nozzle_diameter: { type: "string", description: "Nozzle diameter (default NOZZLE_DIAMETER or 0.4)." },
|
|
2982
|
+
host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
|
|
2983
|
+
bambu_serial: { type: "string", description: "Serial number (default: value from env)" },
|
|
2984
|
+
bambu_token: { type: "string", description: "Access token (default: value from env); never returned." }
|
|
2985
|
+
},
|
|
2986
|
+
required: ["filaments"],
|
|
2987
|
+
additionalProperties: false
|
|
2988
|
+
},
|
|
2989
|
+
outputSchema: PROPOSE_FILAMENTS_OUTPUT_SCHEMA
|
|
2990
|
+
},
|
|
2892
2991
|
{
|
|
2893
2992
|
name: "counterpart_print_route",
|
|
2894
2993
|
description: "Counterpart contract (counterpart/1): how this server reaches the printer for prints and for Stop/Pause/Resume. route is \"lan\" (the local network through FULU's BambuNetwork bridge, or the configured X2D native or Bambu Connect mode), \"cloud\" (Bambu Cloud through FULU's bridge) or \"developer\" (the local network straight to a printer in LAN Only + Developer Mode, whose Pause, Resume and Stop need no Bambu app). options lists each with its label, whether it can be chosen here (and why not) and what controls do on it; choices lists the ids that can be chosen. mode and type are BAMBU_DEFAULT_CONNECTION_MODE and BAMBU_DEFAULT_CONNECTION_TYPE as resolved. Pass route to change it: the change applies to the next print and control at once, and is saved to the .env file in this server's working directory when that file exists (savedTo; null otherwise). Sends nothing to the printer.",
|
|
@@ -4078,6 +4177,35 @@ class BambuPrinterMCPServer {
|
|
|
4078
4177
|
case "blender_mcp_edit_model":
|
|
4079
4178
|
result = await this.blender.edit(args ?? {}, this.resolveExecutableSelectorArg(args?.bridge_command, "blender_mcp_edit_model", "bridge_command", true) ?? (!process.env.BLENDER_MCP_COMMAND?.trim() ? this.runtimeConfig.blenderBridgeCommand : undefined), extra.signal);
|
|
4080
4179
|
break;
|
|
4180
|
+
case "counterpart_discover_printers": {
|
|
4181
|
+
const requested = Number(args?.duration_ms);
|
|
4182
|
+
const found = await discoverBambu(Number.isFinite(requested) ? requested : 4000);
|
|
4183
|
+
// Only models bambu_model accepts: the X1 (serial 00W) has none, so it stays unset.
|
|
4184
|
+
result = { contract: "counterpart/1", network: found.state, printers: found.printers.map(({ model, ...printer }) => ({ ...printer, ...(model && VALID_BAMBU_MODELS.includes(model) ? { model } : {}) })) };
|
|
4185
|
+
break;
|
|
4186
|
+
}
|
|
4187
|
+
case "counterpart_setup_fields":
|
|
4188
|
+
result = bambuSetupFields({ server: SERVER_INFO, models: VALID_BAMBU_MODELS, slicer: slicerSetupNow(), ...(typeof args?.serial === "string" ? { serial: args.serial } : {}) });
|
|
4189
|
+
break;
|
|
4190
|
+
case "counterpart_propose_filaments": {
|
|
4191
|
+
const requestedModel = (String(args?.bambu_model ?? DEFAULT_BAMBU_MODEL ?? "")).trim().toLowerCase();
|
|
4192
|
+
const normalizedModel = requestedModel ? validateBambuModel(requestedModel) : undefined;
|
|
4193
|
+
const inventory = await this.getResolvedPrinterFilamentInventory(host, bambuSerial, bambuToken, normalizedModel, String(args?.nozzle_diameter || DEFAULT_NOZZLE_DIAMETER));
|
|
4194
|
+
const trays = inventory.trays.flatMap(tray => {
|
|
4195
|
+
const colour = normalizeRgbColor(tray.tray_color);
|
|
4196
|
+
if (!tray.loaded || tray.slot === null || !colour || !tray.tray_type || !tray.label)
|
|
4197
|
+
return [];
|
|
4198
|
+
// print_3mf's tray value: an AMS-HT unit (id 128 and up, one tray) is its unit id, not ams_id × 4 + tray.
|
|
4199
|
+
const slot = tray.ams_id !== null && tray.ams_id >= 128 ? tray.ams_id : tray.slot;
|
|
4200
|
+
return [{ slot, label: tray.label, name: tray.spool_name ?? tray.tray_type, colour: `#${colour.toUpperCase()}`,
|
|
4201
|
+
material: tray.tray_type, filamentId: tray.tray_info_idx ?? "", feed: "ams", sliceable: Boolean(tray.resolved_profile_path),
|
|
4202
|
+
...(tray.resolved_profile_path ? { profile: tray.resolved_profile_path } : {}) }];
|
|
4203
|
+
});
|
|
4204
|
+
result = proposeFilaments({ trays, filaments: Array.isArray(args?.filaments) ? args.filaments : [],
|
|
4205
|
+
...(Array.isArray(args?.painted) ? { painted: args.painted } : {}), ...(Array.isArray(args?.chosen) ? { chosen: args.chosen } : {}),
|
|
4206
|
+
sliced: args?.sliced === true, names: colourNames() });
|
|
4207
|
+
break;
|
|
4208
|
+
}
|
|
4081
4209
|
case "counterpart_printer_info":
|
|
4082
4210
|
result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
|
|
4083
4211
|
break;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BambuClient } from "bambu-node";
|
|
2
|
+
export declare const MODEL_IDS: Record<string, string>;
|
|
2
3
|
export declare const SERIAL_MODELS: Record<string, string>;
|
|
3
4
|
/** Only raw reports received after this request are evidence. Never read printer.data here. */
|
|
4
5
|
export declare function readFreshPrinterStatus(printer: BambuClient, serial: string, timeoutMs?: number): Promise<any>;
|
|
@@ -3,7 +3,7 @@ import { HIDDEN_HMS } from "./hidden-hms.js";
|
|
|
3
3
|
import { GetVersionCommand, PushAllCommand } from "bambu-node";
|
|
4
4
|
import { isDualNozzleModel, normalizeMaterial, normalizeModel } from "./limits.js";
|
|
5
5
|
const MAX_REPORT_AGE_MS = 15000;
|
|
6
|
-
const MODEL_IDS = {
|
|
6
|
+
export const MODEL_IDS = {
|
|
7
7
|
O1C: "H2C", O1C2: "H2C", O1D: "H2D", O1E: "H2D Pro", O1S: "H2S", N6: "X2D",
|
|
8
8
|
N2S: "A1", A1M: "A1 Mini", C11: "P1P", C12: "P1S", C13: "X1E", "BL-P001": "X1C", "BL-P002": "X1",
|
|
9
9
|
};
|
package/dist/tool-annotations.js
CHANGED
|
@@ -18,6 +18,8 @@ export const TOOL_ANNOTATIONS = {
|
|
|
18
18
|
resolve_3mf_ams_slots: READ_OUTSIDE, // reads the live AMS inventory
|
|
19
19
|
list_printer_files: READ_OUTSIDE,
|
|
20
20
|
counterpart_print_progress: READ_OUTSIDE,
|
|
21
|
+
counterpart_discover_printers: READ_OUTSIDE, // listens for the printers' own SSDP announcements
|
|
22
|
+
counterpart_propose_filaments: READ_OUTSIDE, // reads the live AMS inventory
|
|
21
23
|
// connect: true starts the bridge agent, which writes its configuration and device identity and can replace certificates.
|
|
22
24
|
bambu_network_bridge_status: hints(false, true, true, true),
|
|
23
25
|
camera_frame: READ_OUTSIDE,
|
|
@@ -33,6 +35,7 @@ export const TOOL_ANNOTATIONS = {
|
|
|
33
35
|
list_templates: READ_LOCAL,
|
|
34
36
|
get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory
|
|
35
37
|
counterpart_printer_info: READ_LOCAL, // configuration and capabilities; sends nothing to the printer
|
|
38
|
+
counterpart_setup_fields: READ_LOCAL, // the settings this server reads; no configured values
|
|
36
39
|
// Local outputs in the server's temporary directory
|
|
37
40
|
extend_stl_base: LOCAL_OUTPUT,
|
|
38
41
|
scale_stl: LOCAL_OUTPUT,
|
package/package.json
CHANGED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* counterpart_discover_printers (counterpart/1): Bambu printers on the local network, from their own SSDP
|
|
3
|
+
* announcements (NOTIFY on UDP 2021, and the answers to one M-SEARCH). Bounded and never failing: a port another app
|
|
4
|
+
* holds (Bambu Studio) is "unavailable", not "none found". Never fetches a URL, connects to or authenticates with a printer.
|
|
5
|
+
*/
|
|
6
|
+
import { createSocket, type Socket } from "node:dgram";
|
|
7
|
+
import { isIPv4 } from "node:net";
|
|
8
|
+
import { networkInterfaces } from "node:os";
|
|
9
|
+
import { normalizeModel } from "../safety/limits.js";
|
|
10
|
+
import { MODEL_IDS, SERIAL_MODELS } from "../safety/printer-state.js";
|
|
11
|
+
import { COUNTERPART_CONTRACT, PRINTER_KINDS } from "./schemas.js";
|
|
12
|
+
|
|
13
|
+
export type FoundPrinter = {
|
|
14
|
+
kind: typeof PRINTER_KINDS[number]; source: "ssdp" | "bonjour"; name: string; host: string;
|
|
15
|
+
port?: number; serial?: string; model?: string; firmware?: string;
|
|
16
|
+
};
|
|
17
|
+
export type Discovery = { contract: typeof COUNTERPART_CONTRACT; network: "complete" | "unavailable"; printers: FoundPrinter[] };
|
|
18
|
+
|
|
19
|
+
/** This server's model value (bambu_model) for a serial number's first three characters, when it has one. */
|
|
20
|
+
export function modelFromSerial(serial: string | undefined): string | undefined {
|
|
21
|
+
return serial ? normalizeModel(SERIAL_MODELS[serial.trim().slice(0, 3).toUpperCase()] ?? "") : undefined;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* DevModel ids Bambu Studio's machine definitions (profiles/BBL/machine/*.json `model_id`) use that the safety identity
|
|
25
|
+
* table doesn't list, for naming a found printer only. Never identity evidence for a print.
|
|
26
|
+
*/
|
|
27
|
+
const ANNOUNCED_MODEL_IDS: Record<string, string> = { N1: "A1 Mini", N7: "P2S" };
|
|
28
|
+
/** This server's model value for a DevModel id Bambu Studio's printer definitions use (C12 is the P1S). */
|
|
29
|
+
export function modelFromDevModel(id: string | undefined): string | undefined {
|
|
30
|
+
const key = id?.trim().toUpperCase();
|
|
31
|
+
return key ? normalizeModel(MODEL_IDS[key] ?? ANNOUNCED_MODEL_IDS[key] ?? "") : undefined;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function privateIPv4(value: string): boolean {
|
|
35
|
+
if (!isIPv4(value)) return false;
|
|
36
|
+
const [a, b] = value.split(".").map(Number) as [number, number];
|
|
37
|
+
return a === 10 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** One SSDP packet from a Bambu printer. The sender must be the printer itself (Location equals its address). */
|
|
41
|
+
export function parseBambuAdvert(packet: Buffer, address: string): FoundPrinter | undefined {
|
|
42
|
+
if (packet.length > 8192 || !privateIPv4(address)) return undefined;
|
|
43
|
+
const lines = packet.toString("utf8").split("\r\n");
|
|
44
|
+
if (!["NOTIFY * HTTP/1.1", "HTTP/1.1 200 OK"].includes(lines.shift() ?? "")) return undefined;
|
|
45
|
+
const headers = new Map<string, string>();
|
|
46
|
+
for (const line of lines) {
|
|
47
|
+
if (!line) continue;
|
|
48
|
+
const at = line.indexOf(":");
|
|
49
|
+
if (at < 1) return undefined;
|
|
50
|
+
const key = line.slice(0, at).trim().toLowerCase(), value = line.slice(at + 1).trim();
|
|
51
|
+
if (headers.has(key) || /[\x00-\x1f\x7f]/.test(value)) return undefined;
|
|
52
|
+
headers.set(key, value);
|
|
53
|
+
}
|
|
54
|
+
if (headers.get("location") !== address) return undefined;
|
|
55
|
+
const serial = headers.get("usn"), devModel = headers.get("devmodel.bambu.com");
|
|
56
|
+
if (!serial || !/^[A-Za-z0-9]{1,64}$/.test(serial) || !devModel || devModel.length > 64) return undefined;
|
|
57
|
+
const firmware = headers.get("devversion.bambu.com");
|
|
58
|
+
const model = modelFromDevModel(devModel) ?? modelFromSerial(serial);
|
|
59
|
+
return { kind: "bambu", source: "ssdp", host: address, serial: serial.toUpperCase(), ...(model ? { model } : {}),
|
|
60
|
+
name: (headers.get("devname.bambu.com") || devModel).slice(0, 128),
|
|
61
|
+
...(firmware && /^\d{2}\.\d{2}\.\d{2}\.\d{2}$/.test(firmware) ? { firmware } : {}) };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A send completes before the next interface: dgram resolves addresses asynchronously even for IP literals. */
|
|
65
|
+
export async function sendDiscoveryProbes(socket: Pick<Socket, "addMembership" | "setMulticastInterface" | "setMulticastTTL" | "send">, addresses: string[], active: () => boolean) {
|
|
66
|
+
for (const address of addresses) {
|
|
67
|
+
if (!active()) return;
|
|
68
|
+
try {
|
|
69
|
+
socket.addMembership("239.255.255.250", address);
|
|
70
|
+
socket.setMulticastInterface(address); socket.setMulticastTTL(1);
|
|
71
|
+
await new Promise<void>((resolve, reject) => socket.send("M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:2021\r\nMAN: \"ssdp:discover\"\r\nMX: 1\r\nST: urn:bambulab-com:device:3dprinter:1\r\n\r\n",
|
|
72
|
+
2021, "239.255.255.250", error => error ? reject(error) : resolve()));
|
|
73
|
+
} catch { /* Other interfaces can still answer. */ }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Listens on UDP 2021 for `durationMs` (bounded 500–15000 ms). */
|
|
78
|
+
export function discoverBambu(durationMs = 4000): Promise<{ state: "complete" | "unavailable"; printers: FoundPrinter[] }> {
|
|
79
|
+
const ms = Number.isFinite(durationMs) ? Math.max(500, Math.min(15_000, Math.round(durationMs))) : 4000;
|
|
80
|
+
return new Promise(resolve => {
|
|
81
|
+
const socket = createSocket({ type: "udp4", reuseAddr: true }), found = new Map<string, FoundPrinter>();
|
|
82
|
+
let finished = false;
|
|
83
|
+
const finish = (state: "complete" | "unavailable") => {
|
|
84
|
+
if (finished) return; finished = true; clearTimeout(timer);
|
|
85
|
+
try { socket.close(); } catch { /* not bound yet */ }
|
|
86
|
+
resolve({ state, printers: [...found.values()].sort((a, b) => (a.serial ?? "").localeCompare(b.serial ?? "")) });
|
|
87
|
+
};
|
|
88
|
+
const timer = setTimeout(() => finish("complete"), ms);
|
|
89
|
+
socket.on("error", () => finish("unavailable"));
|
|
90
|
+
socket.on("message", (data, peer) => { const value = parseBambuAdvert(data, peer.address); if (value && found.size < 64) found.set(`${value.serial}@${value.host}`, value); });
|
|
91
|
+
try {
|
|
92
|
+
socket.bind(2021, "0.0.0.0", () => {
|
|
93
|
+
const interfaces = Object.values(networkInterfaces()).flat().filter(nic => nic && !nic.internal && nic.family === "IPv4" && privateIPv4(nic.address));
|
|
94
|
+
void sendDiscoveryProbes(socket, interfaces.map(nic => nic!.address), () => !finished);
|
|
95
|
+
});
|
|
96
|
+
} catch { finish("unavailable"); }
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export const DISCOVER_OUTPUT_SCHEMA = {
|
|
101
|
+
type: "object" as const,
|
|
102
|
+
properties: {
|
|
103
|
+
contract: { type: "string", const: COUNTERPART_CONTRACT },
|
|
104
|
+
network: { type: "string", enum: ["complete", "unavailable"] },
|
|
105
|
+
printers: { type: "array", items: { type: "object", properties: {
|
|
106
|
+
kind: { type: "string", enum: [...PRINTER_KINDS] }, source: { type: "string", enum: ["ssdp", "bonjour"] }, name: { type: "string" },
|
|
107
|
+
host: { type: "string" }, port: { type: "integer" }, serial: { type: "string" }, model: { type: "string" }, firmware: { type: "string" },
|
|
108
|
+
}, required: ["kind", "source", "name", "host"] } },
|
|
109
|
+
},
|
|
110
|
+
required: ["contract", "network", "printers"],
|
|
111
|
+
};
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* counterpart_propose_filaments (counterpart/1): which loaded spool prints each of a model's colours, proposed before
|
|
3
|
+
* slicing. Nearest colour in OKLab with the asked-for material preferred; one print feeds from one source. Each spool
|
|
4
|
+
* carries the words a person reads ("A2", "Sunflower Yellow PLA Basic") and every part an explicit verdict, so a client
|
|
5
|
+
* renders the result instead of re-deriving it. Pure: the server supplies the live trays.
|
|
6
|
+
*/
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { COUNTERPART_CONTRACT } from "./schemas.js";
|
|
10
|
+
|
|
11
|
+
/** One loaded spool as a client shows it. `feed` groups the spools that can feed one print together. */
|
|
12
|
+
export type ProposalTray = {
|
|
13
|
+
slot: number; label: string; name: string; colour: string; material: string; filamentId: string; feed: string;
|
|
14
|
+
/** This server can slice with it (a filament profile is resolved for it). */
|
|
15
|
+
sliceable: boolean;
|
|
16
|
+
/** The resolved slicer filament profile (absolute path), the one slice_stl takes in load_filaments. */
|
|
17
|
+
profile?: string;
|
|
18
|
+
};
|
|
19
|
+
export type ProposalFilament = { index: number; name?: string; colour?: string; material?: string };
|
|
20
|
+
/** A filament slot no part names (a painted region): it follows the chosen spools' feed. `prints` false: not on this plate. */
|
|
21
|
+
export type PaintedFilament = { index: number; colour?: string; material?: string; prints?: boolean };
|
|
22
|
+
export type ChosenSpool = { index: number; slot: number; colour?: string; material?: string; filamentId?: string };
|
|
23
|
+
export type Verdict = "same-colour" | "closest" | "no-colour" | "none";
|
|
24
|
+
export type ProposalRow = {
|
|
25
|
+
index: number; slot?: number; verdict: Verdict; distance?: number; materialMismatch?: boolean;
|
|
26
|
+
/** What the person should know about this suggestion, in their words. */
|
|
27
|
+
note?: string;
|
|
28
|
+
};
|
|
29
|
+
export type ProposalProblem = { code: string; message: string; index?: number };
|
|
30
|
+
export type FilamentProposal = {
|
|
31
|
+
contract: typeof COUNTERPART_CONTRACT;
|
|
32
|
+
/** The spools a person may choose from: every loaded one for a sliced file, the sliceable ones otherwise. */
|
|
33
|
+
trays: ProposalTray[];
|
|
34
|
+
proposal: ProposalRow[];
|
|
35
|
+
/** Every filament slot (parts and painted) to its spool, when the proposal or the person's choice is printable. */
|
|
36
|
+
mapping?: Array<{ index: number; slot: number }>;
|
|
37
|
+
problems: ProposalProblem[];
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** A colour this close (OKLab) to the asked-for one is the same colour to a person. */
|
|
41
|
+
export const SAME_COLOUR = 0.08;
|
|
42
|
+
const MATERIAL_PENALTY = 0.15;
|
|
43
|
+
const REUSE_PENALTY = 0.1;
|
|
44
|
+
const DISTINCT = 0.05;
|
|
45
|
+
|
|
46
|
+
function oklab(hex: string): [number, number, number] | undefined {
|
|
47
|
+
const match = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(hex.trim());
|
|
48
|
+
if (!match) return undefined;
|
|
49
|
+
const value = Number.parseInt(match[1]!, 16);
|
|
50
|
+
const linear = (channel: number) => { const s = channel / 255; return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; };
|
|
51
|
+
const r = linear(value >> 16 & 255), g = linear(value >> 8 & 255), b = linear(value & 255);
|
|
52
|
+
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
|
|
53
|
+
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
|
|
54
|
+
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
|
|
55
|
+
return [0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s, 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
|
|
56
|
+
0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Perceptual distance between two `#RRGGBB` colours (0 identical, about 1 black to white). Alpha is ignored. */
|
|
60
|
+
export function colourDistance(a: string, b: string): number {
|
|
61
|
+
const left = oklab(a), right = oklab(b);
|
|
62
|
+
if (!left || !right) return Number.POSITIVE_INFINITY;
|
|
63
|
+
return Math.hypot(left[0] - right[0], left[1] - right[1], left[2] - right[2]);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
type Match = { slot: number; distance?: number; materialMismatch?: boolean; guessed?: boolean };
|
|
67
|
+
const materialOf = (value: string | undefined) => value?.trim().toUpperCase() || undefined;
|
|
68
|
+
|
|
69
|
+
function pick(filament: { colour?: string; material?: string }, loaded: ProposalTray[], assigned: Map<number, string[]>, requireMaterial: boolean): Match | undefined {
|
|
70
|
+
if (!loaded.length) return undefined;
|
|
71
|
+
const wanted = materialOf(filament.material);
|
|
72
|
+
const mismatch = (tray: ProposalTray) => wanted !== undefined && materialOf(tray.material) !== wanted;
|
|
73
|
+
const eligible = requireMaterial && wanted ? loaded.filter(tray => !mismatch(tray)) : loaded;
|
|
74
|
+
if (!eligible.length) return undefined;
|
|
75
|
+
const target = filament.colour ? oklab(filament.colour) : undefined;
|
|
76
|
+
if (!target) {
|
|
77
|
+
const free = eligible.filter(tray => !assigned.has(tray.slot));
|
|
78
|
+
const pool = free.length ? free : eligible;
|
|
79
|
+
const chosen = pool.find(tray => !mismatch(tray)) ?? pool[0]!;
|
|
80
|
+
assigned.set(chosen.slot, [...(assigned.get(chosen.slot) ?? [])]);
|
|
81
|
+
return { slot: chosen.slot, guessed: true, ...(mismatch(chosen) ? { materialMismatch: true } : {}) };
|
|
82
|
+
}
|
|
83
|
+
let best: { tray: ProposalTray; distance: number; score: number } | undefined;
|
|
84
|
+
for (const tray of eligible) {
|
|
85
|
+
const distance = colourDistance(filament.colour!, tray.colour);
|
|
86
|
+
const shared = (assigned.get(tray.slot) ?? []).some(colour => colourDistance(colour, filament.colour!) > DISTINCT);
|
|
87
|
+
const score = distance + (mismatch(tray) ? MATERIAL_PENALTY : 0) + (shared ? REUSE_PENALTY : 0);
|
|
88
|
+
if (!best || score < best.score || (score === best.score && tray.slot < best.tray.slot)) best = { tray, distance, score };
|
|
89
|
+
}
|
|
90
|
+
assigned.set(best!.tray.slot, [...(assigned.get(best!.tray.slot) ?? []), filament.colour!]);
|
|
91
|
+
return { slot: best!.tray.slot, distance: best!.distance, ...(mismatch(best!.tray) ? { materialMismatch: true } : {}) };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* One match per filament, in order; undefined where nothing can serve it. Several filaments of one colour may share a
|
|
96
|
+
* spool. With `requireMaterial` (an already-sliced file) only spools of the asked-for material qualify. Automatic matches
|
|
97
|
+
* never mix feeds: the first feed listed (the AMS) is preferred, another feed only when it alone serves every colour.
|
|
98
|
+
*/
|
|
99
|
+
export function matchColours(model: Array<{ colour?: string; material?: string }>, trays: ProposalTray[], options: { requireMaterial?: boolean } = {}): (Match | undefined)[] {
|
|
100
|
+
const loaded = trays.filter(tray => oklab(tray.colour));
|
|
101
|
+
const run = (pool: ProposalTray[]) => { const assigned = new Map<number, string[]>(); return model.map(filament => pick(filament, pool, assigned, !!options.requireMaterial)); };
|
|
102
|
+
const matches = run(loaded);
|
|
103
|
+
const feedOf = new Map(loaded.map(tray => [tray.slot, tray.feed]));
|
|
104
|
+
const feeds = [...new Set(loaded.map(tray => tray.feed))];
|
|
105
|
+
if (new Set(matches.flatMap(match => match ? [feedOf.get(match.slot)] : [])).size <= 1) return matches;
|
|
106
|
+
const perFeed = feeds.map(feed => run(loaded.filter(tray => tray.feed === feed)));
|
|
107
|
+
return perFeed.find(result => result.every(match => match)) ?? perFeed[0]!;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The colour names Bambu Studio itself uses for its filaments (profiles/BBL/filament/filaments_color_codes.json). */
|
|
111
|
+
export type ColourNames = { spool(filamentId: string, colour: string): string | undefined; colour(colour: string): string | undefined };
|
|
112
|
+
export const NO_COLOUR_NAMES: ColourNames = { spool: () => undefined, colour: () => undefined };
|
|
113
|
+
|
|
114
|
+
export function loadColourNames(filamentProfileDir: string | undefined): ColourNames {
|
|
115
|
+
if (!filamentProfileDir) return NO_COLOUR_NAMES;
|
|
116
|
+
let data: unknown;
|
|
117
|
+
try {
|
|
118
|
+
const file = path.join(filamentProfileDir, "filaments_color_codes.json");
|
|
119
|
+
if (fs.statSync(file).size > 8 * 1024 * 1024) return NO_COLOUR_NAMES;
|
|
120
|
+
data = (JSON.parse(fs.readFileSync(file, "utf8")) as { data?: unknown }).data;
|
|
121
|
+
} catch { return NO_COLOUR_NAMES; }
|
|
122
|
+
if (!Array.isArray(data)) return NO_COLOUR_NAMES;
|
|
123
|
+
const byId = new Map<string, string>(), byColour = new Map<string, string>();
|
|
124
|
+
for (const entry of data) {
|
|
125
|
+
const colours = Array.isArray(entry?.fila_color) ? entry.fila_color : [];
|
|
126
|
+
const name = typeof entry?.fila_color_name?.en === "string" ? entry.fila_color_name.en.trim().slice(0, 64) : "";
|
|
127
|
+
const id = typeof entry?.fila_id === "string" ? entry.fila_id.trim().toUpperCase() : "";
|
|
128
|
+
// Single colours only: a gradient or multi-colour spool's first colour is not its name.
|
|
129
|
+
if (colours.length !== 1 || typeof colours[0] !== "string" || !name || !/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(colours[0])) continue;
|
|
130
|
+
const hex8 = (colours[0].slice(1) + "FF").slice(0, 8).toUpperCase();
|
|
131
|
+
if (id && !byId.has(`${id}#${hex8}`)) byId.set(`${id}#${hex8}`, name);
|
|
132
|
+
if (id && !byId.has(`${id}#${hex8.slice(0, 6)}`)) byId.set(`${id}#${hex8.slice(0, 6)}`, name);
|
|
133
|
+
// A bare colour's name: the shortest Bambu uses for exactly that opaque colour ("White", not "Jade White").
|
|
134
|
+
if (hex8.endsWith("FF")) {
|
|
135
|
+
const key = hex8.slice(0, 6), known = byColour.get(key);
|
|
136
|
+
if (!known || name.length < known.length) byColour.set(key, name);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const hex = (value: string) => value.replace(/^#/, "").toUpperCase();
|
|
140
|
+
return {
|
|
141
|
+
spool: (filamentId, colour) => byId.get(`${filamentId.toUpperCase()}#${hex(colour)}`) ?? byId.get(`${filamentId.toUpperCase()}#${hex(colour).slice(0, 6)}`),
|
|
142
|
+
colour: colour => byColour.get(hex(colour).slice(0, 6)),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Where a Bambu tray sits, as Bambu Studio labels it: AMS units A–D with trays 1–4, AMS HT units by letter. */
|
|
147
|
+
export function bambuTrayLabel(amsId: number, trayId: number): string {
|
|
148
|
+
const letter = (n: number) => String.fromCharCode(65 + Math.max(0, Math.min(n, 25)));
|
|
149
|
+
return amsId >= 128 ? `AMS HT ${letter(amsId - 128)}` : `${letter(amsId)}${trayId + 1}`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A spool's name: its colour name (when Bambu names it) and product ("Sunflower Yellow PLA Basic"), else the product. */
|
|
153
|
+
export function spoolName(product: string, colourName: string | undefined): string {
|
|
154
|
+
return (colourName ? `${colourName} ${product}` : product).trim().slice(0, 128);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const partName = (filament: ProposalFilament) => filament.name?.trim() || `Part ${filament.index}`;
|
|
158
|
+
|
|
159
|
+
export function proposeFilaments(input: {
|
|
160
|
+
trays: ProposalTray[]; filaments: ProposalFilament[]; painted?: PaintedFilament[]; chosen?: ChosenSpool[]; sliced?: boolean; names?: ColourNames;
|
|
161
|
+
}): FilamentProposal {
|
|
162
|
+
const names = input.names ?? NO_COLOUR_NAMES;
|
|
163
|
+
const sliced = !!input.sliced;
|
|
164
|
+
const live = input.trays;
|
|
165
|
+
const menu = sliced ? live : live.filter(tray => tray.sliceable);
|
|
166
|
+
const problems: ProposalProblem[] = [];
|
|
167
|
+
const result = (proposal: ProposalRow[], mapping?: Array<{ index: number; slot: number }>): FilamentProposal =>
|
|
168
|
+
({ contract: COUNTERPART_CONTRACT, trays: menu, proposal, ...(mapping && !problems.length ? { mapping } : {}), problems });
|
|
169
|
+
const describe = (tray: ProposalTray) => `${tray.label} ${tray.name}`;
|
|
170
|
+
const colourWords = (colour: string) => names.colour(colour) ?? colour.toUpperCase();
|
|
171
|
+
|
|
172
|
+
// A sliced file's painted slots need their material on the same feed: they take part in choosing the feed,
|
|
173
|
+
// so the proposal never picks a feed that can't print them when another one can.
|
|
174
|
+
const required = sliced ? (input.painted ?? []).filter(slot => slot.material && slot.prints !== false
|
|
175
|
+
&& !input.filaments.some(filament => filament.index === slot.index)) : [];
|
|
176
|
+
const matches = matchColours([...input.filaments, ...required], menu, { requireMaterial: sliced }).slice(0, input.filaments.length);
|
|
177
|
+
const proposal: ProposalRow[] = input.filaments.map((filament, i) => {
|
|
178
|
+
const match = matches[i];
|
|
179
|
+
if (!match) return { index: filament.index, verdict: "none" as const };
|
|
180
|
+
const tray = menu.find(item => item.slot === match.slot)!;
|
|
181
|
+
const row: ProposalRow = { index: filament.index, slot: match.slot,
|
|
182
|
+
verdict: match.guessed ? "no-colour" : (match.distance ?? 0) <= SAME_COLOUR ? "same-colour" : "closest",
|
|
183
|
+
...(match.distance !== undefined ? { distance: match.distance } : {}), ...(match.materialMismatch ? { materialMismatch: true } : {}) };
|
|
184
|
+
if (row.verdict === "no-colour") row.note = "The model doesn’t say this part’s colour — pick its spool.";
|
|
185
|
+
else if (row.verdict === "closest") {
|
|
186
|
+
// The colour may be loaded but not chosen: on another feed (one print feeds from one source), in another
|
|
187
|
+
// material, or on a spool another colour of this model already prints from. Say which, never "isn't loaded".
|
|
188
|
+
const words = colourWords(filament.colour!);
|
|
189
|
+
const loaded = menu.find(item => item.slot !== tray.slot && colourDistance(item.colour, filament.colour!) <= SAME_COLOUR);
|
|
190
|
+
const wanted = materialOf(filament.material);
|
|
191
|
+
row.note = !loaded ? `${words} isn’t loaded. Closest loaded: ${describe(tray)}.`
|
|
192
|
+
: loaded.feed !== tray.feed ? `${words} is loaded on ${loaded.label}, but one print feeds from one source. Closest here: ${describe(tray)}.`
|
|
193
|
+
: wanted && materialOf(loaded.material) !== wanted ? `${words} is loaded on ${loaded.label} in ${loaded.material}, not ${filament.material}. Closest in ${filament.material}: ${describe(tray)}.`
|
|
194
|
+
: `${words} is on ${loaded.label}, which another colour of this model already prints from. Closest other spool: ${describe(tray)}.`;
|
|
195
|
+
}
|
|
196
|
+
if (match.materialMismatch) row.note = `${row.note ? row.note + " " : ""}Prints in ${tray.material}, not ${filament.material}.`;
|
|
197
|
+
return row;
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
if (!input.filaments.length) return result(proposal);
|
|
201
|
+
// The spools that will print, in filament order: the person's choices, validated, or the proposal.
|
|
202
|
+
let chosen: ProposalTray[];
|
|
203
|
+
if (input.chosen) {
|
|
204
|
+
if (input.chosen.length !== input.filaments.length || input.filaments.some((filament, i) => input.chosen![i]!.index !== filament.index)) {
|
|
205
|
+
problems.push({ code: "choices-incomplete", message: "Choose a spool for every colour in this model, then try again." });
|
|
206
|
+
return result(proposal);
|
|
207
|
+
}
|
|
208
|
+
chosen = [];
|
|
209
|
+
for (const [i, choice] of input.chosen.entries()) {
|
|
210
|
+
const tray = live.find(item => item.slot === choice.slot);
|
|
211
|
+
const filament = input.filaments[i]!;
|
|
212
|
+
if (!tray || (choice.colour !== undefined && choice.colour.toUpperCase() !== tray.colour.toUpperCase())
|
|
213
|
+
|| (choice.material !== undefined && materialOf(choice.material) !== materialOf(tray.material)) || (choice.filamentId !== undefined && choice.filamentId !== tray.filamentId)) {
|
|
214
|
+
problems.push({ code: "spool-changed", index: filament.index, message: "A chosen filament changed. Choose the current spools and try again." });
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (sliced && filament.material && materialOf(tray.material) !== materialOf(filament.material))
|
|
218
|
+
problems.push({ code: "sliced-material", index: filament.index, message: `“${partName(filament)}” was sliced for ${filament.material}, so it can only print from a ${filament.material} spool. Choose one, or share the designer’s editable 3MF to change material.` });
|
|
219
|
+
if (!sliced && !tray.sliceable)
|
|
220
|
+
problems.push({ code: "no-profile", index: filament.index, message: `The ${tray.material} spool you chose has no slicing profile on this computer. Choose another spool.` });
|
|
221
|
+
chosen.push(tray);
|
|
222
|
+
}
|
|
223
|
+
if (problems.length) return result(proposal);
|
|
224
|
+
if (new Set(chosen.map(tray => tray.feed)).size > 1) {
|
|
225
|
+
problems.push({ code: "mixed-feeds", message: "One print feeds from one source: put every colour on AMS spools, or every colour on the external spool." });
|
|
226
|
+
return result(proposal);
|
|
227
|
+
}
|
|
228
|
+
} else {
|
|
229
|
+
const missing = matches.findIndex(match => !match);
|
|
230
|
+
if (!menu.length) { problems.push({ code: "nothing-loaded", message: "No filament is loaded. Load a spool in the AMS, then try again." }); return result(proposal); }
|
|
231
|
+
if (missing >= 0) {
|
|
232
|
+
const filament = input.filaments[missing]!;
|
|
233
|
+
const elsewhere = sliced && filament.material && live.some(tray => materialOf(tray.material) === materialOf(filament.material));
|
|
234
|
+
problems.push({ code: elsewhere ? "material-on-another-feed" : "material-not-loaded", index: filament.index, message: elsewhere
|
|
235
|
+
? `“${partName(filament)}” needs ${filament.material}, but one print feeds from one source and no single source holds every colour’s material. Load the spools on one source, then try again.`
|
|
236
|
+
: sliced && filament.material
|
|
237
|
+
? `No ${filament.material} spool is loaded for “${partName(filament)}”, and this file was sliced for ${filament.material}. Load one, then try again.`
|
|
238
|
+
: "No filament is loaded. Load a spool in the AMS, then try again." });
|
|
239
|
+
return result(proposal);
|
|
240
|
+
}
|
|
241
|
+
chosen = matches.map(match => menu.find(tray => tray.slot === match!.slot)!);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const mapping = new Map(input.filaments.map((filament, i) => [filament.index, chosen[i]!.slot]));
|
|
245
|
+
const feed = chosen[0]!.feed;
|
|
246
|
+
const chosenSlots = new Set(chosen.map(tray => tray.slot));
|
|
247
|
+
const primary = live[0]?.feed;
|
|
248
|
+
// A painted slot follows the chosen feed: on the external spool(s) exactly those chosen; on the AMS any AMS spool.
|
|
249
|
+
const fillerPool = menu.filter(tray => feed === primary ? tray.feed === feed : chosenSlots.has(tray.slot));
|
|
250
|
+
for (const painted of input.painted ?? []) {
|
|
251
|
+
if (mapping.has(painted.index)) continue;
|
|
252
|
+
const [match] = matchColours([painted], fillerPool, { requireMaterial: sliced });
|
|
253
|
+
if (match) mapping.set(painted.index, match.slot);
|
|
254
|
+
else if (sliced && painted.material && painted.prints !== false)
|
|
255
|
+
problems.push({ code: "painted-material", index: painted.index, message: `A painted part of this file was sliced for ${painted.material}, and no ${painted.material} spool on the chosen feed source can print it. Load one, then try again.` });
|
|
256
|
+
else mapping.set(painted.index, chosen[0]!.slot);
|
|
257
|
+
}
|
|
258
|
+
return result(proposal, [...mapping.entries()].sort((a, b) => a[0] - b[0]).map(([index, slot]) => ({ index, slot })));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const colour = { type: "string", pattern: "^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$" };
|
|
262
|
+
export const PROPOSE_FILAMENTS_INPUT_PROPERTIES = {
|
|
263
|
+
filaments: {
|
|
264
|
+
type: "array", maxItems: 64,
|
|
265
|
+
description: "The model's filaments a person sees, in project order: 1-based index, part name, the colour it belongs in and its material when known.",
|
|
266
|
+
items: { type: "object", properties: { index: { type: "integer", minimum: 1, maximum: 64 }, name: { type: "string", maxLength: 256 }, colour, material: { type: "string", maxLength: 64 } }, required: ["index"], additionalProperties: false },
|
|
267
|
+
},
|
|
268
|
+
painted: {
|
|
269
|
+
type: "array", maxItems: 64,
|
|
270
|
+
description: "Filament slots no part names (painted regions). Each follows the chosen spools' feed; prints false when the selected plate never uses it.",
|
|
271
|
+
items: { type: "object", properties: { index: { type: "integer", minimum: 1, maximum: 64 }, colour, material: { type: "string", maxLength: 64 }, prints: { type: "boolean" } }, required: ["index"], additionalProperties: false },
|
|
272
|
+
},
|
|
273
|
+
chosen: {
|
|
274
|
+
type: "array", maxItems: 64,
|
|
275
|
+
description: "The person's spool for each filament, in the same order: checked against what is loaded now. Omit for the proposal alone.",
|
|
276
|
+
items: { type: "object", properties: { index: { type: "integer", minimum: 1, maximum: 64 }, slot: { type: "integer", minimum: 0, maximum: 4095 }, colour, material: { type: "string", maxLength: 128 }, filamentId: { type: "string", maxLength: 128 } }, required: ["index", "slot"], additionalProperties: false },
|
|
277
|
+
},
|
|
278
|
+
sliced: { type: "boolean", description: "The file is already sliced: its materials are fixed, so only spools of the same material qualify." },
|
|
279
|
+
} as const;
|
|
280
|
+
|
|
281
|
+
export const PROPOSE_FILAMENTS_OUTPUT_SCHEMA = {
|
|
282
|
+
type: "object" as const,
|
|
283
|
+
properties: {
|
|
284
|
+
contract: { type: "string", const: COUNTERPART_CONTRACT },
|
|
285
|
+
trays: { type: "array", items: { type: "object", properties: {
|
|
286
|
+
slot: { type: "integer" }, label: { type: "string" }, name: { type: "string" }, colour: { type: "string" }, material: { type: "string" },
|
|
287
|
+
filamentId: { type: "string" }, feed: { type: "string" }, sliceable: { type: "boolean" }, profile: { type: "string" },
|
|
288
|
+
}, required: ["slot", "label", "name", "colour", "material", "filamentId", "feed", "sliceable"] } },
|
|
289
|
+
proposal: { type: "array", items: { type: "object", properties: {
|
|
290
|
+
index: { type: "integer" }, slot: { type: "integer" }, verdict: { type: "string", enum: ["same-colour", "closest", "no-colour", "none"] },
|
|
291
|
+
distance: { type: "number" }, materialMismatch: { type: "boolean" }, note: { type: "string" },
|
|
292
|
+
}, required: ["index", "verdict"] } },
|
|
293
|
+
mapping: { type: "array", items: { type: "object", properties: { index: { type: "integer" }, slot: { type: "integer" } }, required: ["index", "slot"] } },
|
|
294
|
+
problems: { type: "array", items: { type: "object", properties: { code: { type: "string" }, message: { type: "string" }, index: { type: "integer" } }, required: ["code", "message"] } },
|
|
295
|
+
},
|
|
296
|
+
required: ["contract", "trays", "proposal", "problems"],
|
|
297
|
+
};
|