bambu-printer-mcp 1.1.50 → 1.1.52

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.
Files changed (54) hide show
  1. package/README.md +33 -8
  2. package/dist/ams-mapping.d.ts +19 -0
  3. package/dist/ams-mapping.js +49 -0
  4. package/dist/bambu-network-bridge.d.ts +86 -9
  5. package/dist/bambu-network-bridge.js +284 -4
  6. package/dist/control-reply.d.ts +21 -0
  7. package/dist/control-reply.js +44 -0
  8. package/dist/counterpart/info.js +1 -0
  9. package/dist/counterpart/route.d.ts +37 -0
  10. package/dist/counterpart/route.js +78 -0
  11. package/dist/counterpart/schemas.d.ts +4 -0
  12. package/dist/counterpart/schemas.js +1 -0
  13. package/dist/design-guidance.d.ts +26 -0
  14. package/dist/design-guidance.js +177 -0
  15. package/dist/fusion-mcp-bridge.d.ts +8 -4
  16. package/dist/fusion-mcp-bridge.js +36 -10
  17. package/dist/index.js +219 -54
  18. package/dist/printers/bambu.d.ts +38 -13
  19. package/dist/printers/bambu.js +204 -69
  20. package/dist/printers/camera-sources.d.ts +8 -0
  21. package/dist/printers/camera-sources.js +66 -0
  22. package/dist/printers/camera-stream.d.ts +65 -0
  23. package/dist/printers/camera-stream.js +227 -0
  24. package/dist/printers/camera-tools.d.ts +192 -0
  25. package/dist/printers/camera-tools.js +29 -0
  26. package/dist/printers/camera-wire.d.ts +7 -0
  27. package/dist/printers/camera-wire.js +40 -0
  28. package/dist/safety/print-file.d.ts +3 -0
  29. package/dist/safety/print-file.js +11 -2
  30. package/dist/safety/printer-state.d.ts +7 -0
  31. package/dist/safety/printer-state.js +11 -1
  32. package/dist/slicer/layer-pauses.d.ts +47 -0
  33. package/dist/slicer/layer-pauses.js +130 -0
  34. package/dist/stl/stl-manipulator.d.ts +40 -1
  35. package/dist/stl/stl-manipulator.js +253 -83
  36. package/package.json +2 -1
  37. package/src/ams-mapping.ts +52 -0
  38. package/src/bambu-network-bridge.ts +311 -8
  39. package/src/control-reply.ts +41 -0
  40. package/src/counterpart/info.ts +1 -0
  41. package/src/counterpart/route.ts +91 -0
  42. package/src/counterpart/schemas.ts +2 -0
  43. package/src/design-guidance.ts +188 -0
  44. package/src/fusion-mcp-bridge.ts +30 -10
  45. package/src/index.ts +213 -57
  46. package/src/printers/bambu.ts +194 -60
  47. package/src/printers/camera-sources.ts +53 -0
  48. package/src/printers/camera-stream.ts +165 -0
  49. package/src/printers/camera-tools.ts +29 -0
  50. package/src/printers/camera-wire.ts +39 -0
  51. package/src/safety/print-file.ts +12 -2
  52. package/src/safety/printer-state.ts +11 -1
  53. package/src/slicer/layer-pauses.ts +143 -0
  54. package/src/stl/stl-manipulator.ts +298 -93
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Split the A1/P1 camera stream on port 6000 into JPEG frames. Each frame is
3
+ * a 16-byte header (payload size LE, itrack, flags, reserved) and the JPEG.
4
+ */
5
+ export function cameraFrameParser(onFrame: (jpeg: Buffer) => void, onError: (error: Error) => void): (chunk: Buffer) => void {
6
+ let buffered = Buffer.alloc(0);
7
+ let failed = false;
8
+ return chunk => {
9
+ if (failed) return;
10
+ buffered = Buffer.concat([buffered, chunk]);
11
+ while (buffered.length >= 16) {
12
+ const payloadSize = buffered.readUInt32LE(0);
13
+ if (payloadSize <= 0 || payloadSize > 5_000_000) {
14
+ failed = true;
15
+ onError(new Error(`camera_snapshot: unreasonable payload size ${payloadSize} from header; auth likely failed.`));
16
+ return;
17
+ }
18
+ if (buffered.length < 16 + payloadSize) return;
19
+ const jpeg = buffered.subarray(16, 16 + payloadSize);
20
+ buffered = buffered.subarray(16 + payloadSize);
21
+ if (jpeg[0] !== 0xff || jpeg[1] !== 0xd8) {
22
+ failed = true;
23
+ onError(new Error(`camera_snapshot: payload does not start with JPEG SOI (FF D8); got ${jpeg[0].toString(16)} ${jpeg[1].toString(16)}.`));
24
+ return;
25
+ }
26
+ onFrame(Buffer.from(jpeg));
27
+ }
28
+ };
29
+ }
30
+
31
+
32
+ /** The existing Bambu camera authentication packet, shared by snapshots and streams. */
33
+ export function cameraAuth(token: string): Buffer {
34
+ const auth = Buffer.alloc(80, 0);
35
+ auth.writeUInt32LE(0x40, 0); auth.writeUInt32LE(0x3000, 4);
36
+ auth.write("bblp", 16, 4, "ascii");
37
+ auth.write(token, 48, Math.min(32, Buffer.byteLength(token, "ascii")), "ascii");
38
+ return auth;
39
+ }
@@ -1,5 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { readBoundedPrintFile, loadSafe3mfArchive } from './archive.js';
3
+ import { projectFilaments, type ProjectFilament } from "../ams-mapping.js";
3
4
  import { MACHINE_LIMITS, isDualNozzleModel, normalizeMaterial, normalizeModel, validateStartupPurgeTemperature, validateTemperature } from './limits.js';
4
5
 
5
6
  export interface PrintFileInspection {
@@ -18,6 +19,8 @@ export interface PrintFileInspection {
18
19
  nozzleFlows?: string[];
19
20
  /** Physical nozzle index for each declared filament, composed from the selected plate headers. */
20
21
  filamentNozzleIndices?: number[];
22
+ /** Every project filament as project_settings.config declares it, for PrintParams.ams_mapping_info. */
23
+ projectFilaments?: ProjectFilament[];
21
24
  }
22
25
  type Metadata = Record<string, unknown>;
23
26
  const NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
@@ -405,7 +408,14 @@ export async function inspectPrintFile(filePath: string, options: {model:string;
405
408
  continue;
406
409
  }
407
410
  if(['M104','M109','M140','M190','M141','M191'].includes(code)) {
408
- const args=parameters(argumentsText,'A');
411
+ const args=parameters(argumentsText,code==='M104'?'AM':'A');
412
+ // Studio 2.9's GCodeWriter marks layer-temperature changes with bare M.
413
+ // Accept only its exact S-target / optional T form; targets and tool
414
+ // selectors still pass through the independent thermal checks below.
415
+ if(args.has('M')) {
416
+ if(!Number.isNaN(args.get('M')!) || !args.has('S') || [...args.keys()].some(key=>!'MST'.includes(key))) fail('unsupported M104 layer-change temperature parameters');
417
+ args.delete('M');
418
+ }
409
419
  // Official A1 and A1 mini start G-code waits with M109 S<target> H<limit>
410
420
  // (S25 H140, S100 H170, S220 H300). H is not a heater target: S stays the
411
421
  // checked target, so H is accepted only within those vendor bounds.
@@ -548,5 +558,5 @@ export async function inspectPrintFile(filePath: string, options: {model:string;
548
558
  }
549
559
  if(!commandCount) return fail('selected G-code contains no printable commands');
550
560
  if(!used.size) materials.forEach((_,index)=>used.add(index));
551
- return {model,nozzleDiameters,materials,usedFilamentPositions:[...used].sort((a,b)=>a-b),plateInternalPath,sha256,maxNozzleTemperature,maxBedTemperature,maxChamberTemperature,bedType,selectsAms,nozzleTypes,nozzleFlows,filamentNozzleIndices};
561
+ return {model,nozzleDiameters,materials,usedFilamentPositions:[...used].sort((a,b)=>a-b),plateInternalPath,sha256,maxNozzleTemperature,maxBedTemperature,maxChamberTemperature,bedType,selectsAms,nozzleTypes,nozzleFlows,filamentNozzleIndices,...(Array.isArray(project.filament_type)?{projectFilaments:projectFilaments(project)}:{})};
552
562
  }
@@ -325,12 +325,22 @@ function logHiddenNotices(raw: Record<string, any>, serial: string, model: strin
325
325
  }
326
326
  }
327
327
 
328
+ /**
329
+ * 0300_8013, "Printing was paused by the user" / "paused due to the pause command added to the
330
+ * printing file" (hms-messages.ts): the printer's report of a deliberate pause, which Resume clears.
331
+ * A paused P1S reports it as print_error, so it is not an error for resuming a paused job.
332
+ */
333
+ export const PAUSE_NOTICE = 0x03008013;
334
+ export function isPauseNotice(raw: Record<string, any>, requireIdle: boolean): boolean {
335
+ const state = typeof raw?.gcode_state === "string" ? raw.gcode_state.toUpperCase() : "";
336
+ return !requireIdle && state === "PAUSE" && finiteNumber(raw?.print_error) === PAUSE_NOTICE;
337
+ }
328
338
  function validateErrors(raw: Record<string,any>, requireIdle: boolean, serial: string, model: string) {
329
339
  const state = typeof raw.gcode_state === "string" ? raw.gcode_state.toUpperCase() : "UNKNOWN";
330
340
  const terminal = isCancelledX2DJob(raw, model) || isFinishedP1SJob(raw, model);
331
341
  if (requireIdle && !["IDLE","FINISH"].includes(state) && !terminal) throw new Error(`Printer state ${state} is not safely idle.`);
332
342
  if (!requireIdle && !["IDLE","FINISH","RUNNING","PAUSE"].includes(state) && !terminal) throw new Error(`Printer state ${state} is unknown or failed.`);
333
- if (finiteNumber(raw.print_error) !== 0) throw new Error("Printer reports a print error or did not report its error state.");
343
+ if (finiteNumber(raw.print_error) !== 0 && !isPauseNotice(raw, requireIdle)) throw new Error("Printer reports a print error or did not report its error state.");
334
344
  if (!Array.isArray(raw.hms)) throw new Error("Printer HMS error state is missing or malformed.");
335
345
  for (const reported of raw.hms) {
336
346
  const entry = hmsCode(reported);
@@ -0,0 +1,143 @@
1
+ import fs from "node:fs";
2
+ import JSZip from "jszip";
3
+
4
+ /**
5
+ * Pause-at-layer for Bambu-compatible slicer CLIs ("Add pause" in Bambu Studio
6
+ * and OrcaSlicer). The slicer writes the machine's own machine_pause_gcode
7
+ * (M400 U1 on Bambu printers) before the chosen layer, so the printer pauses
8
+ * by itself there and waits for Resume; no remote command is involved.
9
+ *
10
+ * The CLI takes these as --load-custom-gcodes <json> (CustomGCode::Info). It
11
+ * does not apply the pauses a project 3MF already carries in
12
+ * Metadata/custom_gcode_per_print_z.xml, so those are read here and passed the
13
+ * same way. A pause's print_z must be the exact top of its layer: a height
14
+ * between layers lands on the layer below.
15
+ */
16
+
17
+ /** CustomGCode::Type, in the order bbs_3mf.cpp writes it as an integer. */
18
+ const CUSTOM_GCODE_TYPES = ["ColorChange", "PausePrint", "ToolChange", "Template", "Custom", "Unknown"] as const;
19
+ export type CustomGcodeType = (typeof CUSTOM_GCODE_TYPES)[number];
20
+
21
+ export interface CustomGcodeItem {
22
+ type: CustomGcodeType;
23
+ print_z: number;
24
+ color: string;
25
+ extruder: number;
26
+ extra: string;
27
+ }
28
+
29
+ export interface CustomGcodeInfo {
30
+ mode: string;
31
+ gcodes: CustomGcodeItem[];
32
+ }
33
+
34
+ /** 1-based layer numbers, as Bambu Studio's and OrcaSlicer's preview slider count them. */
35
+ export function parsePauseLayers(value: unknown): number[] | undefined {
36
+ if (value === undefined || value === null || value === "") return undefined;
37
+ const raw = Array.isArray(value) ? value : String(value).split(/[\s,;]+/).filter(Boolean);
38
+ const layers = raw.map(entry => Number(entry));
39
+ for (const layer of layers) {
40
+ if (!Number.isInteger(layer) || layer < 2) {
41
+ throw new Error(`pause_at_layers takes whole layer numbers of 2 or more (the printer cannot pause before layer 1), not ${JSON.stringify(value)}.`);
42
+ }
43
+ }
44
+ const unique = [...new Set(layers)].sort((a, b) => a - b);
45
+ return unique.length ? unique : undefined;
46
+ }
47
+
48
+ function xmlAttr(tag: string, name: string): string | undefined {
49
+ const match = new RegExp(`\\b${name}="([^"]*)"`).exec(tag);
50
+ return match ? match[1].replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&") : undefined;
51
+ }
52
+
53
+ /**
54
+ * The custom G-codes (pauses, colour changes, ...) a project 3MF stores for
55
+ * one plate (1-based), as Bambu Studio and OrcaSlicer save them.
56
+ */
57
+ export async function readProjectCustomGcodes(threeMfPath: string, plate = 1): Promise<CustomGcodeInfo | undefined> {
58
+ let zip: JSZip;
59
+ try {
60
+ zip = await JSZip.loadAsync(await fs.promises.readFile(threeMfPath));
61
+ } catch {
62
+ return undefined;
63
+ }
64
+ const file = zip.file(/^Metadata\/custom_gcode_per_print_z\.xml$/i)[0];
65
+ if (!file) return undefined;
66
+ const xml = await file.async("string");
67
+ for (const block of xml.match(/<plate>[\s\S]*?<\/plate>/g) ?? []) {
68
+ const info = /<plate_info\b[^>]*>/.exec(block)?.[0];
69
+ if (Number(info ? xmlAttr(info, "id") : NaN) !== plate) continue;
70
+ const gcodes: CustomGcodeItem[] = [];
71
+ for (const tag of block.match(/<layer\b[^>]*>/g) ?? []) {
72
+ const type = CUSTOM_GCODE_TYPES[Number(xmlAttr(tag, "type"))] ?? "Unknown";
73
+ const printZ = Number(xmlAttr(tag, "top_z"));
74
+ if (!Number.isFinite(printZ)) continue;
75
+ gcodes.push({
76
+ type,
77
+ print_z: printZ,
78
+ color: xmlAttr(tag, "color") ?? "",
79
+ extruder: Number(xmlAttr(tag, "extruder") ?? 1) || 1,
80
+ // Template and Custom keep their G-code text in "extra" (CustomGCode.hpp).
81
+ extra: xmlAttr(tag, "extra") ?? "",
82
+ });
83
+ }
84
+ const modeTag = /<mode\b[^>]*>/.exec(block)?.[0];
85
+ return { mode: (modeTag && xmlAttr(modeTag, "value")) || "SingleExtruder", gcodes };
86
+ }
87
+ return undefined;
88
+ }
89
+
90
+ /** The plate's G-code text inside a sliced 3MF. */
91
+ export async function readPlateGcode(threeMfPath: string, plate = 1): Promise<string | undefined> {
92
+ const zip = await JSZip.loadAsync(await fs.promises.readFile(threeMfPath));
93
+ const exact = zip.file(`Metadata/plate_${plate}.gcode`);
94
+ const file = exact ?? zip.file(/^Metadata\/plate_\d+\.gcode$/)[0];
95
+ return file ? file.async("string") : undefined;
96
+ }
97
+
98
+ /** Each layer's top Z in order, from the slicer's "; Z_HEIGHT:" markers. */
99
+ export function layerTops(gcode: string): number[] {
100
+ const tops: number[] = [];
101
+ for (const match of gcode.matchAll(/^; Z_HEIGHT: ([0-9.]+)\s*$/gm)) tops.push(Number(match[1]));
102
+ return tops;
103
+ }
104
+
105
+ /**
106
+ * The 1-based layers whose block holds a pause: the slicer's "; PAUSE_PRINTING"
107
+ * marker or the machine's pause G-code on its own line.
108
+ */
109
+ export function pausedLayers(gcode: string, pauseGcode = "M400 U1"): number[] {
110
+ const lines = gcode.split(/\r?\n/);
111
+ const paused = new Set<number>();
112
+ let layer = 0;
113
+ const pauseLine = pauseGcode.trim();
114
+ for (const line of lines) {
115
+ if (line.startsWith("; Z_HEIGHT:")) { layer += 1; continue; }
116
+ if (layer === 0) continue;
117
+ const trimmed = line.trim();
118
+ if (trimmed === "; PAUSE_PRINTING" || (pauseLine && trimmed === pauseLine)) paused.add(layer);
119
+ }
120
+ return [...paused].sort((a, b) => a - b);
121
+ }
122
+
123
+ /** The machine_pause_gcode a sliced file was made with (its config block), else Bambu's M400 U1. */
124
+ export function machinePauseGcode(gcode: string): string {
125
+ const match = /^; machine_pause_gcode = (.*)$/m.exec(gcode);
126
+ const value = match?.[1]?.split("\\n")[0]?.trim();
127
+ return value || "M400 U1";
128
+ }
129
+
130
+ /** Project custom G-codes plus a pause before each requested layer, at that layer's exact top. */
131
+ export function customGcodesWithPauses(tops: number[], layers: number[], project?: CustomGcodeInfo): CustomGcodeInfo {
132
+ const total = tops.length;
133
+ const beyond = layers.filter(layer => layer > total);
134
+ if (beyond.length) {
135
+ throw new Error(`This print has ${total} layers, so it cannot pause before layer ${beyond.join(", ")}.`);
136
+ }
137
+ const pauses: CustomGcodeItem[] = layers.map(layer => ({ type: "PausePrint", print_z: tops[layer - 1], color: "", extruder: 1, extra: "" }));
138
+ const kept = (project?.gcodes ?? []).filter(item => !(item.type === "PausePrint" && pauses.some(p => Math.abs(p.print_z - item.print_z) < 1e-4)));
139
+ return {
140
+ mode: project?.mode || "SingleExtruder",
141
+ gcodes: [...kept, ...pauses].sort((a, b) => a.print_z - b.print_z),
142
+ };
143
+ }