bambu-printer-mcp 1.1.61 → 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 +9 -1
- 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 +131 -1
- 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 +123 -1
- 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
|
}
|
|
@@ -1632,6 +1693,8 @@ class BambuPrinterMCPServer {
|
|
|
1632
1693
|
metadata_keys: Object.keys(parsed.metadata),
|
|
1633
1694
|
summary: summarizeSliceSettings(config),
|
|
1634
1695
|
raw_key_count: Object.keys(config).length,
|
|
1696
|
+
// ownProcessTemplate itself, for a call that names no profile or template, so this can't drift from slicing.
|
|
1697
|
+
own_process: (await ownProcessTemplate({}, sourcePath, undefined)) !== undefined,
|
|
1635
1698
|
};
|
|
1636
1699
|
}
|
|
1637
1700
|
const content = fs.readFileSync(sourcePath, "utf8");
|
|
@@ -2043,7 +2106,7 @@ class BambuPrinterMCPServer {
|
|
|
2043
2106
|
},
|
|
2044
2107
|
{
|
|
2045
2108
|
name: "get_slice_settings",
|
|
2046
|
-
description: "Inspect slicer settings from a saved 3MF template or a JSON/config slicer profile without slicing anything.",
|
|
2109
|
+
description: "Inspect slicer settings from a saved 3MF template or a JSON/config slicer profile without slicing anything. For a 3MF, own_process is true when the file carries its own process (a designer's Bambu Studio or Orca project), so slice_stl and print_3mf's auto-slice slice it with that process unless the call names slicer_profile, template_name or template_3mf_path.",
|
|
2047
2110
|
inputSchema: {
|
|
2048
2111
|
type: "object",
|
|
2049
2112
|
properties: {
|
|
@@ -2887,6 +2950,44 @@ class BambuPrinterMCPServer {
|
|
|
2887
2950
|
},
|
|
2888
2951
|
outputSchema: PRINTER_INFO_OUTPUT_SCHEMA
|
|
2889
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
|
+
},
|
|
2890
2991
|
{
|
|
2891
2992
|
name: "counterpart_print_route",
|
|
2892
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.",
|
|
@@ -4076,6 +4177,35 @@ class BambuPrinterMCPServer {
|
|
|
4076
4177
|
case "blender_mcp_edit_model":
|
|
4077
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);
|
|
4078
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
|
+
}
|
|
4079
4209
|
case "counterpart_printer_info":
|
|
4080
4210
|
result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
|
|
4081
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
|
+
};
|