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
@@ -1,9 +1,10 @@
1
1
  import { spawn } from "node:child_process";
2
- import { createHash } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { BAMBU_NETWORK_CERTIFICATES } from "./bambu-network-certs.js";
7
+ import { controlReply, refusedControlMessage } from "./control-reply.js";
7
8
  const FRAME_MAGIC = 0x52424a50;
8
9
  const FRAME_HEADER_SIZE = 16;
9
10
  const FRAME_TYPE_JSON_REQUEST = 1;
@@ -25,8 +26,31 @@ const BAMBU_NETWORK_PRINT_ERRORS = {
25
26
  export function describeBambuNetworkPrintError(value) {
26
27
  return BAMBU_NETWORK_PRINT_ERRORS[value] ? ` (${BAMBU_NETWORK_PRINT_ERRORS[value]})` : "";
27
28
  }
28
- /** Waits from native/bambu-native-print.cpp, which prints through the same plug-in calls. */
29
29
  export const LOCAL_PRINT_TIMING = Object.freeze({ connectTimeoutMs: 30000, pollMs: 250, settleMs: 3000, retryWaitMs: 8000 });
30
+ export const LOCAL_CONTROL_TIMING = Object.freeze({ ...LOCAL_PRINT_TIMING, settleMs: 1000, retryWaitMs: 1500, certificateWaitMs: 5000, attempts: 3, deliveryMs: 5000 });
31
+ /** Bounded event text for diagnostics, with any access code removed. */
32
+ function traceText(text) {
33
+ const clean = text.replace(/("?access_code"?\s*[:=]\s*"?)[^",}\s]*/gi, "$1[redacted]");
34
+ // A signed printer reply (a header, then its payload) is the printer's answer to a command: keep it whole.
35
+ return clean.startsWith('{"header"') ? clean.slice(0, 4000) : clean.slice(0, 160);
36
+ }
37
+ export { controlReply, isAuthorizationRefusal } from "./control-reply.js";
38
+ /** Result of a sent control from the printer's answer during the hold; a refusal throws. */
39
+ function controlResult(command, route, reply, attempts) {
40
+ const word = `${command[0].toUpperCase()}${command.slice(1)}`;
41
+ if (reply && !reply.accepted)
42
+ throw new Error(refusedControlMessage(command, route, reply.errCode));
43
+ return { status: "success", attempts, confirmed: Boolean(reply),
44
+ message: reply ? `The printer accepted ${word}.` : `${word} submitted over ${route}. Check printer status to confirm it took effect.` };
45
+ }
46
+ export const CLOUD_PRINT_TIMING = Object.freeze({ connectTimeoutMs: 30000, pollMs: 250, settleMs: 3000, certificateWaitMs: 10000 });
47
+ let stateSequence = 0;
48
+ const nextSequence = () => String(++stateSequence);
49
+ // The signed Studio channel on P1S 01.10 accepts string IDs in [20000, 29999].
50
+ // Larger IDs receive 0502400A even when the RSA signature is valid. Share the
51
+ // counter across LAN/cloud controls and retries; never derive IDs from wall time.
52
+ let controlSequence = 19999;
53
+ const nextControlSequence = () => String(controlSequence = controlSequence >= 29999 ? 20000 : controlSequence + 1);
30
54
  /**
31
55
  * The plug-in's certificate folder: BAMBU_NETWORK_CERT_DIR when set, else
32
56
  * Bambu's pinned public certificates written to the agent's config folder,
@@ -60,6 +84,40 @@ function trimEnv(value) {
60
84
  const trimmed = value?.trim();
61
85
  return trimmed ? trimmed : undefined;
62
86
  }
87
+ /**
88
+ * The client identity FULU's GUI gives the plug-in before agent start
89
+ * (GUI_App::init_http_extra_header). Through the Linux bridge FULU presents
90
+ * itself as Bambu Studio at the version its plug-in ABI belongs to
91
+ * (PJarczakLinuxBridgeConfig.cpp forced_client_version, "02.05.02.51").
92
+ * Bambu's cloud issues the printer-control certificate and creates print
93
+ * tasks for this client, so an agent started without it is an unknown client.
94
+ * The device id is kept in the config folder so it stays the same per install.
95
+ */
96
+ export function bambuNetworkClientHeaders(configDir, env = process.env) {
97
+ const idFile = path.join(configDir, "client-device-id");
98
+ let deviceId = "";
99
+ try {
100
+ deviceId = fs.readFileSync(idFile, "utf8").trim();
101
+ }
102
+ catch { /* first start */ }
103
+ if (!deviceId) {
104
+ deviceId = randomUUID();
105
+ try {
106
+ fs.mkdirSync(configDir, { recursive: true });
107
+ fs.writeFileSync(idFile, `${deviceId}\n`, { mode: 0o600 });
108
+ }
109
+ catch { /* still send this run's id */ }
110
+ }
111
+ return {
112
+ "X-BBL-Client-Type": "slicer",
113
+ "X-BBL-Client-Name": trimEnv(env.BAMBU_NETWORK_CLIENT_NAME) ?? "BambuStudio",
114
+ "X-BBL-Client-Version": trimEnv(env.BAMBU_NETWORK_CLIENT_VERSION) ?? "02.05.02.51",
115
+ "X-BBL-OS-Type": "linux",
116
+ "X-BBL-OS-Version": os.release(),
117
+ "X-BBL-Device-ID": deviceId,
118
+ "X-BBL-Language": "en",
119
+ };
120
+ }
63
121
  function fileExists(filePath) {
64
122
  try {
65
123
  return fs.existsSync(filePath);
@@ -169,6 +227,9 @@ function bridgeNumericResult(value) {
169
227
  ? value.value
170
228
  : undefined;
171
229
  }
230
+ function bridgeValueIsTrue(value) {
231
+ return typeof value === "object" && value !== null && value.value === true;
232
+ }
172
233
  function assertBridgeOk(value, method) {
173
234
  if (isBridgeFailure(value)) {
174
235
  const errorText = value.error === undefined ? "unknown bridge error" : String(value.error);
@@ -327,6 +388,8 @@ export class BambuNetworkBridge {
327
388
  // plug-in verifies a LAN printer with printer.cer from this folder, and
328
389
  // FULU's host crashes on connect_printer when no folder was ever set.
329
390
  const certificates = await withAgent("net.set_cert_file", { folder: certDir, filename: "slicer_base64.cer" }, false);
391
+ // FULU's GUI order: set_cert_file, then the client headers, then start.
392
+ await withAgent("net.set_extra_http_header", { headers: bambuNetworkClientHeaders(configDir) }, false);
330
393
  await withAgent("net.set_country_code", { country_code: countryCode });
331
394
  await withAgent("net.start");
332
395
  // The plug-in runs callbacks through queue_on_main; FULU's host executes
@@ -367,6 +430,8 @@ export class BambuNetworkBridge {
367
430
  }
368
431
  async runLocalSession(printer, options, assertActive, timing, run) {
369
432
  const jobUpdates = [];
433
+ const controlMessages = [];
434
+ let certificateReady = false;
370
435
  const installCertificate = async () => {
371
436
  await this.callWithAgent("net.install_device_cert", { dev_id: printer.devId, lan_only: true }, options);
372
437
  await this.callWithAgent("net.update_cert", {}, options);
@@ -379,11 +444,23 @@ export class BambuNetworkBridge {
379
444
  const statuses = [];
380
445
  let waitInfo = false;
381
446
  for (const event of Array.isArray(polled?.events) ? polled.events : []) {
447
+ options.trace?.({ event: event?.name, devMatch: event?.payload?.dev_id === undefined ? "none" : event.payload.dev_id === printer.devId,
448
+ ...(event?.payload?.status !== undefined ? { status: event.payload.status } : {}), ...(typeof event?.payload?.msg === "string" ? { msg: traceText(event.payload.msg) } : {}) });
382
449
  if (event?.name === "job.update_status")
383
450
  jobUpdates.push({ status: event.payload?.status, code: event.payload?.code, msg: event.payload?.msg });
384
451
  const eventDev = event?.payload?.dev_id;
385
452
  if (eventDev !== undefined && eventDev !== "" && eventDev !== printer.devId)
386
453
  continue;
454
+ // FULU v1.0.0 GUI_App's certificate-state callback. A connect callback
455
+ // alone does not establish that protected controls can be encrypted.
456
+ if (eventDev === printer.devId && (event?.name === "on_local_message" || event?.name === "on_message")) {
457
+ if (event.payload?.msg === "device_cert_installed")
458
+ certificateReady = true;
459
+ if (event.payload?.msg === "device_cert_uninstalled")
460
+ certificateReady = false;
461
+ if (typeof event.payload?.msg === "string" && /"command":"(stop|pause|resume)"/.test(event.payload.msg))
462
+ controlMessages.push(event.payload.msg);
463
+ }
387
464
  if (event?.name === "on_local_connect")
388
465
  statuses.push(event.payload.status);
389
466
  if ((event?.name === "on_local_message" || event?.name === "on_message") && event.payload?.msg === "wait_info")
@@ -400,16 +477,28 @@ export class BambuNetworkBridge {
400
477
  await new Promise(resolve => setTimeout(resolve, timing.pollMs));
401
478
  }
402
479
  };
480
+ const certificateReadyWithin = async (ms) => {
481
+ const deadline = Date.now() + ms;
482
+ do {
483
+ assertActive();
484
+ await pump();
485
+ if (certificateReady)
486
+ return true;
487
+ await new Promise(resolve => setTimeout(resolve, timing.pollMs));
488
+ } while (Date.now() < deadline);
489
+ return certificateReady;
490
+ };
403
491
  await this.ensureAgent(options);
404
492
  assertActive();
405
493
  if (!this.localSessionReady) {
406
494
  throw new Error("FULU BambuNetwork bridge host did not accept the certificate folder or local-connection callbacks a LAN print needs. Update the FULU runtime; no print command was sent.");
407
495
  }
408
- for (const callback of ["net.set_on_printer_connected_fn", "net.set_on_local_message_fn"]) {
496
+ for (const callback of ["net.set_on_printer_connected_fn", "net.set_on_message_fn", "net.set_on_local_message_fn"]) {
409
497
  assertBridgeOk(await this.callWithAgent(callback, {}, options), callback);
410
498
  }
411
499
  await this.callWithAgent("net.update_cert", {}, options);
412
500
  await pump();
501
+ certificateReady = false; // Ignore completion queued by an earlier session.
413
502
  assertActive();
414
503
  const requested = await this.callWithAgent("net.connect_printer", {
415
504
  dev_id: printer.devId, dev_ip: printer.devIp, username: printer.username, password: printer.password, use_ssl: printer.useSsl,
@@ -450,7 +539,7 @@ export class BambuNetworkBridge {
450
539
  await this.callWithAgent("net.send_message_to_printer", { dev_id: printer.devId, msg: JSON.stringify(message), qos, flag: 0 }, options);
451
540
  }
452
541
  await settle(timing.settleMs);
453
- const result = await run({ installCertificate, settle, jobUpdates });
542
+ const result = await run({ installCertificate, settle, certificateReadyWithin, controlMessages, jobUpdates });
454
543
  await pump();
455
544
  return result;
456
545
  }
@@ -479,6 +568,197 @@ export class BambuNetworkBridge {
479
568
  return { result, jobUpdates: session.jobUpdates };
480
569
  });
481
570
  }
571
+ /**
572
+ * A print control (stop, pause, resume) through the same authenticated LAN
573
+ * session as a FULU print. FULU's own app sends controls exactly this way
574
+ * (send_message_to_printer, qos 1, flag 0) on a connection whose certificate
575
+ * is installed. A fresh connection can report SEND_MSG_FAILED (-4) or
576
+ * LP_PUBLISH_MSG_FAILED (-4030) while that exchange finishes: those returns
577
+ * mean nothing was sent, so the certificate is reinstalled and the control
578
+ * tried again, as the native X2D helper does. Any other return is final.
579
+ * beforeDispatch runs before every send, so a resume re-checks the paused job.
580
+ */
581
+ async sendLocalPrintCommand(printer, command, options = {}, beforeDispatch, timing = LOCAL_CONTROL_TIMING) {
582
+ const assertActive = () => options.assertDispatchAllowed?.("net.send_message_to_printer");
583
+ const trace = options.trace ?? this.controlTrace(options);
584
+ const traced = { ...options, trace };
585
+ return this.withLocalSession(printer, traced, assertActive, timing, async (session) => {
586
+ const ready = await session.certificateReadyWithin(timing.certificateWaitMs);
587
+ trace({ step: "certificate", ready });
588
+ const method = "net.send_message_to_printer";
589
+ let code = 0;
590
+ for (let attempt = 1; attempt <= timing.attempts; attempt++) {
591
+ await beforeDispatch?.();
592
+ assertActive();
593
+ const sequenceId = nextControlSequence();
594
+ const result = await this.callWithAgent(method, {
595
+ dev_id: printer.devId,
596
+ msg: JSON.stringify({ print: { command, param: "", sequence_id: sequenceId } }),
597
+ qos: 1, flag: 0,
598
+ }, traced);
599
+ assertBridgeOk(result, method);
600
+ code = bridgeValueAsNumber(result, method);
601
+ trace({ step: "send", command, attempt, code });
602
+ if (code === 0) {
603
+ // The plug-in queues the publish; disconnecting at once dropped it (Nov 3: five accepted
604
+ // controls, printer never paused or stopped). Stay connected while it reaches the printer.
605
+ await session.settle(timing.deliveryMs);
606
+ trace({ step: "delivered", command, heldMs: timing.deliveryMs });
607
+ const reply = session.controlMessages.map(msg => controlReply(msg, command, sequenceId)).find(Boolean);
608
+ return controlResult(command, "the local network", reply, attempt);
609
+ }
610
+ if ((code !== -4 && code !== -4030) || attempt === timing.attempts)
611
+ break;
612
+ await session.settle(timing.retryWaitMs);
613
+ await session.installCertificate();
614
+ await session.certificateReadyWithin(timing.certificateWaitMs);
615
+ }
616
+ throw new Error(`The printer did not accept ${command} over the authenticated FULU LAN connection (plug-in code ${code}).`);
617
+ });
618
+ }
619
+ /**
620
+ * Open the plug-in's Bambu Cloud session with a printer bound to the account, in the order
621
+ * Bambu Studio uses (GUI_App.cpp on_server_connected / on_printer_connected): wait for the
622
+ * cloud connection, select and subscribe to the printer, and when it connects request its
623
+ * state (pushall, get_version, get_access_code) and install its certificate for cloud use.
624
+ * Without that state the plug-in refuses a cloud print with -3140 (ENC_FLAG_NOT_READY).
625
+ * Shares the LAN session queue: one reader of the plug-in's events at a time.
626
+ */
627
+ async withCloudSession(devId, options, assertActive, timing, run) {
628
+ const previous = this.localSessionTail;
629
+ let release;
630
+ this.localSessionTail = new Promise(resolve => { release = resolve; });
631
+ try {
632
+ await previous;
633
+ await this.ensureAgent(options);
634
+ assertActive();
635
+ if (!bridgeValueIsTrue(await this.callWithAgent("net.is_user_login", {}, options))) {
636
+ throw new Error("FULU's networking plug-in is not signed in to Bambu Cloud, so nothing was sent to the printer.");
637
+ }
638
+ for (const callback of ["net.set_on_printer_connected_fn", "net.set_on_message_fn", "net.set_on_server_connected_fn"]) {
639
+ assertBridgeOk(await this.callWithAgent(callback, {}, options), callback);
640
+ }
641
+ const messages = [];
642
+ const jobUpdates = [];
643
+ let printerConnected = false;
644
+ let certificateReady = false;
645
+ const pump = async () => {
646
+ const polled = await this.request("bridge.poll_events", { limit: 1024 }, options);
647
+ assertBridgeOk(polled, "bridge.poll_events");
648
+ for (const event of Array.isArray(polled?.events) ? polled.events : []) {
649
+ const eventDev = event?.payload?.dev_id ?? (typeof event?.payload?.topic_str === "string" ? event.payload.topic_str.replace(/^tunnel\//, "") : undefined);
650
+ options.trace?.({ event: event?.name, devMatch: eventDev === undefined ? "none" : eventDev === devId, ...(typeof event?.payload?.msg === "string" ? { msg: traceText(event.payload.msg) } : {}) });
651
+ if (event?.name === "job.update_status")
652
+ jobUpdates.push({ status: event.payload?.status, code: event.payload?.code, msg: event.payload?.msg });
653
+ if (eventDev !== devId)
654
+ continue;
655
+ if (event?.name === "on_printer_connected")
656
+ printerConnected = true;
657
+ if (event?.name === "on_message" && typeof event.payload?.msg === "string") {
658
+ if (event.payload.msg === "device_cert_installed")
659
+ certificateReady = true;
660
+ else if (event.payload.msg === "device_cert_uninstalled")
661
+ certificateReady = false;
662
+ else
663
+ messages.push(event.payload.msg);
664
+ }
665
+ }
666
+ };
667
+ const waitFor = async (done, ms) => {
668
+ for (const deadline = Date.now() + ms; !done() && Date.now() < deadline;) {
669
+ assertActive();
670
+ await pump();
671
+ if (!done())
672
+ await new Promise(resolve => setTimeout(resolve, timing.pollMs));
673
+ }
674
+ return done();
675
+ };
676
+ const settle = async (ms) => { await waitFor(() => false, ms); };
677
+ for (const deadline = Date.now() + timing.connectTimeoutMs; !bridgeValueIsTrue(await this.callWithAgent("net.is_server_connected", {}, options));) {
678
+ if (Date.now() >= deadline)
679
+ throw new Error(`FULU's networking plug-in could not reach Bambu Cloud within ${Math.round(timing.connectTimeoutMs / 1000)} s, so nothing was sent to the printer.`);
680
+ assertActive();
681
+ await new Promise(resolve => setTimeout(resolve, timing.pollMs));
682
+ }
683
+ await this.callWithAgent("net.set_user_selected_machine", { dev_id: devId }, options);
684
+ await this.callWithAgent("net.add_subscribe", { devs: [devId] }, options);
685
+ if (!await waitFor(() => printerConnected, timing.connectTimeoutMs)) {
686
+ throw new Error(`Bambu Cloud did not connect to printer ${devId} within ${Math.round(timing.connectTimeoutMs / 1000)} s. Check that the printer is online and bound to this account. Nothing was sent to the printer.`);
687
+ }
688
+ for (const [message, qos] of [
689
+ [{ pushing: { sequence_id: nextSequence(), command: "pushall", version: 1, push_target: 1 } }, 0],
690
+ [{ info: { sequence_id: nextSequence(), command: "get_version" } }, 1],
691
+ [{ system: { sequence_id: nextSequence(), command: "get_access_code" } }, 0],
692
+ ]) {
693
+ await this.callWithAgent("net.send_message", { dev_id: devId, msg: JSON.stringify(message), qos, flag: 0 }, options);
694
+ }
695
+ const installCertificate = async () => { await this.callWithAgent("net.install_device_cert", { dev_id: devId, lan_only: false }, options); };
696
+ const certificateReadyWithin = (ms) => waitFor(() => certificateReady, ms);
697
+ await installCertificate();
698
+ const ready = await certificateReadyWithin(timing.certificateWaitMs);
699
+ options.trace?.({ step: "certificate", route: "cloud", ready });
700
+ await settle(timing.settleMs);
701
+ const result = await run({ settle, messages, jobUpdates, installCertificate, certificateReadyWithin });
702
+ await pump();
703
+ return result;
704
+ }
705
+ finally {
706
+ release();
707
+ }
708
+ }
709
+ /** A cloud print method (start_print) in a cloud session, so the plug-in has the printer's state. */
710
+ async startCloudPrint(devId, method, payload, options = {}, assertActive = () => { }, timing = CLOUD_PRINT_TIMING) {
711
+ return await this.withCloudSession(devId, options, assertActive, timing, async (session) => ({ result: await this.callWithAgent(method, payload, options), jobUpdates: session.jobUpdates }));
712
+ }
713
+ /**
714
+ * A print control over Bambu Cloud: how Bambu Studio and FULU's slicer control a printer
715
+ * bound to the account (MachineObject::publish_json → cloud_publish_json: send_message,
716
+ * qos 1, flag 0), in a cloud session. Held open like the LAN control.
717
+ */
718
+ async sendCloudPrintCommand(devId, command, options = {}, beforeDispatch, timing = LOCAL_CONTROL_TIMING) {
719
+ const method = "net.send_message";
720
+ const assertActive = () => options.assertDispatchAllowed?.(method);
721
+ const trace = options.trace ?? this.controlTrace(options);
722
+ const traced = { ...options, trace };
723
+ return this.withCloudSession(devId, traced, assertActive, timing, async (session) => {
724
+ let code = 0;
725
+ for (let attempt = 1; attempt <= timing.attempts; attempt++) {
726
+ await beforeDispatch?.();
727
+ assertActive();
728
+ const sequenceId = nextControlSequence();
729
+ const result = await this.callWithAgent(method, {
730
+ dev_id: devId, msg: JSON.stringify({ print: { command, param: "", sequence_id: sequenceId } }), qos: 1, flag: 0,
731
+ }, traced);
732
+ assertBridgeOk(result, method);
733
+ code = bridgeValueAsNumber(result, method);
734
+ trace({ step: "send", route: "cloud", command, attempt, code });
735
+ if (code === 0) {
736
+ await session.settle(timing.deliveryMs);
737
+ trace({ step: "delivered", route: "cloud", command, heldMs: timing.deliveryMs });
738
+ return controlResult(command, "Bambu Cloud", session.messages.map(msg => controlReply(msg, command, sequenceId)).find(Boolean), attempt);
739
+ }
740
+ // Before the printer's certificate is installed the plug-in sends nothing and returns
741
+ // CONNECT_FAILED (-2) or SEND_MSG_FAILED (-4), as on the LAN route (Nov 3: cloud pause -2
742
+ // with the certificate not yet installed). Reinstall it, wait, and send again.
743
+ if ((code !== -2 && code !== -4) || attempt === timing.attempts)
744
+ break;
745
+ await session.settle(timing.retryWaitMs);
746
+ await session.installCertificate();
747
+ trace({ step: "certificate", route: "cloud", attempt, ready: await session.certificateReadyWithin(timing.certificateWaitMs) });
748
+ }
749
+ throw new Error(`Bambu Cloud did not accept ${command} for printer ${devId} (plug-in code ${code}).`);
750
+ });
751
+ }
752
+ /** Appends control diagnostics to control-trace.log in the bridge's config folder. */
753
+ controlTrace(options) {
754
+ const file = path.join(this.resolveConfigDir(options.configDir), "control-trace.log");
755
+ return entry => {
756
+ try {
757
+ fs.appendFileSync(file, JSON.stringify({ at: new Date().toISOString(), ...entry }) + "\n", { mode: 0o600 });
758
+ }
759
+ catch { /* diagnostics only */ }
760
+ };
761
+ }
482
762
  async callWithAgent(method, payload = {}, options = {}) {
483
763
  const { agent } = await this.ensureAgent(options);
484
764
  return await this.request(method, { ...payload, agent }, options);
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The printer's answer to Pause, Resume or Stop, shared by every route (FULU's local network and Bambu Cloud,
3
+ * and the direct local network a printer in LAN Only + Developer Mode takes).
4
+ */
5
+ export type ControlReply = {
6
+ accepted: boolean;
7
+ errCode: number;
8
+ };
9
+ /**
10
+ * The printer's answer to a control it was sent: it echoes command and sequence_id, with
11
+ * err_code set when it refuses. A P1S on authorization firmware signs it: {"header":{...},"print":{...}}.
12
+ */
13
+ export declare function controlReply(msg: unknown, command: string, sequenceId: string): ControlReply | undefined;
14
+ /**
15
+ * The printer's command verification refused the envelope. These codes do not
16
+ * establish that third-party controls are unsupported: P1S 01.10 also returns
17
+ * 0x0502400A for a valid signature with a sequence ID outside the Studio window.
18
+ */
19
+ export declare function isAuthorizationRefusal(errCode: number): boolean;
20
+ /** What to tell a person about a refused control. direct: the control went straight to the printer (Developer Mode connection). */
21
+ export declare function refusedControlMessage(command: string, route: string, errCode: number, direct?: boolean): string;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The printer's answer to Pause, Resume or Stop, shared by every route (FULU's local network and Bambu Cloud,
3
+ * and the direct local network a printer in LAN Only + Developer Mode takes).
4
+ */
5
+ /**
6
+ * The printer's answer to a control it was sent: it echoes command and sequence_id, with
7
+ * err_code set when it refuses. A P1S on authorization firmware signs it: {"header":{...},"print":{...}}.
8
+ */
9
+ export function controlReply(msg, command, sequenceId) {
10
+ if (typeof msg !== "string" || !msg.includes(sequenceId))
11
+ return undefined;
12
+ let print;
13
+ try {
14
+ print = JSON.parse(msg)?.print;
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ if (print?.command !== command || String(print.sequence_id) !== sequenceId)
20
+ return undefined;
21
+ const errCode = Number(print.err_code ?? 0) || 0;
22
+ const failed = typeof print.result === "string" && print.result.toLowerCase() !== "success";
23
+ return { accepted: errCode === 0 && !failed, errCode };
24
+ }
25
+ /**
26
+ * The printer's command verification refused the envelope. These codes do not
27
+ * establish that third-party controls are unsupported: P1S 01.10 also returns
28
+ * 0x0502400A for a valid signature with a sequence ID outside the Studio window.
29
+ */
30
+ export function isAuthorizationRefusal(errCode) {
31
+ const code = errCode >>> 0;
32
+ return code >= 0x05024007 && code <= 0x0502400B;
33
+ }
34
+ /** What to tell a person about a refused control. direct: the control went straight to the printer (Developer Mode connection). */
35
+ export function refusedControlMessage(command, route, errCode, direct = false) {
36
+ const word = `${command[0].toUpperCase()}${command.slice(1)}`;
37
+ const code = (errCode >>> 0).toString(16).toUpperCase().padStart(8, "0");
38
+ if (!isAuthorizationRefusal(errCode))
39
+ return `The printer refused ${word} over ${route} (error ${code}). Nothing changed on the printer.`;
40
+ const message = `The printer refused ${word} (error ${code}): its command verification failed. `;
41
+ return message + (direct
42
+ ? "Check LAN Only and Developer Mode for the direct connection, or choose an authenticated Local network or Bambu Cloud connection."
43
+ : "Check the authenticated connection and signing setup for this printer.");
44
+ }
@@ -22,6 +22,7 @@ export function bambuPrinterInfo(options) {
22
22
  layers: true,
23
23
  // camera_snapshot needs the model to choose its transport.
24
24
  camera: model && TCP_CAMERA_MODELS.has(model) ? "bambu-tcp" : model && RTSP_CAMERA_MODELS.has(model) ? "rtsp" : "none",
25
+ cameraStream: !!model && (TCP_CAMERA_MODELS.has(model) || RTSP_CAMERA_MODELS.has(model)),
25
26
  filaments: "ams",
26
27
  pause: true,
27
28
  resume: true,
@@ -0,0 +1,37 @@
1
+ /**
2
+ * lan: the local network through FULU's BambuNetwork bridge (or the configured X2D native or Bambu Connect mode).
3
+ * cloud: Bambu Cloud through FULU's bridge.
4
+ * developer: the local network straight to the printer (lan_mqtt_ftps), for a printer in LAN Only + Developer Mode.
5
+ */
6
+ export type PrintRoute = "lan" | "cloud" | "developer";
7
+ export declare const PRINT_ROUTES: readonly PrintRoute[];
8
+ export interface Connection {
9
+ mode: string;
10
+ type: string;
11
+ }
12
+ /** One connection a person can choose, as counterpart_print_route reports it. */
13
+ export interface RouteOption {
14
+ id: PrintRoute;
15
+ label: string;
16
+ available: boolean;
17
+ /** Why it can't be chosen here, when it can't. */
18
+ reason?: string;
19
+ /** What Pause, Resume and Stop do on this connection. */
20
+ controls: string;
21
+ }
22
+ export declare function routeOf(connection: Connection): PrintRoute;
23
+ /** The current connection when it is its own local route (X2D native or Bambu Connect); otherwise none. */
24
+ export declare function ownLocalOf(current: Connection): Connection | undefined;
25
+ /**
26
+ * Every connection, and whether this server can use it (bridgeConfigured: BAMBU_NETWORK_BRIDGE_COMMAND is set).
27
+ * ownLocal is the printer's own local route (X2D native or Bambu Connect), kept apart from the current choice
28
+ * so switching to Developer Mode or Bambu Cloud and back returns to it.
29
+ */
30
+ export declare function routeOptions(current: Connection, bridgeConfigured: boolean, ownLocal?: Connection | undefined): RouteOption[];
31
+ /**
32
+ * The configured defaults for a route. Cloud and the local network use FULU's BambuNetwork; an X2D native or
33
+ * Bambu Connect setup keeps its own mode for the local network. Developer Mode is the direct LAN route.
34
+ */
35
+ export declare function connectionForRoute(route: PrintRoute, current: Connection, bridgeConfigured?: boolean, ownLocal?: Connection | undefined): Connection;
36
+ /** Set KEY=value lines in a dotenv file, keeping every other line and the file's permissions. */
37
+ export declare function writeEnvValues(file: string, values: Record<string, string>): void;
@@ -0,0 +1,78 @@
1
+ /** counterpart_print_route: how this server reaches the printer for prints and controls (PRD §8.4). */
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ export const PRINT_ROUTES = ["lan", "cloud", "developer"];
5
+ /** Modes that are their own local-network route and stay as configured. */
6
+ const OWN_LOCAL_MODES = new Set(["bambu_native", "bambu_connect"]);
7
+ export function routeOf(connection) {
8
+ if (connection.mode === "bambu_network")
9
+ return connection.type === "cloud" ? "cloud" : "lan";
10
+ if (connection.mode === "lan_mqtt_ftps")
11
+ return "developer";
12
+ return "lan";
13
+ }
14
+ /** The current connection when it is its own local route (X2D native or Bambu Connect); otherwise none. */
15
+ export function ownLocalOf(current) {
16
+ return OWN_LOCAL_MODES.has(current.mode) ? current : undefined;
17
+ }
18
+ /**
19
+ * Every connection, and whether this server can use it (bridgeConfigured: BAMBU_NETWORK_BRIDGE_COMMAND is set).
20
+ * ownLocal is the printer's own local route (X2D native or Bambu Connect), kept apart from the current choice
21
+ * so switching to Developer Mode or Bambu Cloud and back returns to it.
22
+ */
23
+ export function routeOptions(current, bridgeConfigured, ownLocal = ownLocalOf(current)) {
24
+ const signedControls = "Uses the configured authenticated connection for Print, Pause, Resume and Stop.";
25
+ const needsBridge = "Needs FULU's BambuNetwork bridge (BAMBU_NETWORK_BRIDGE_COMMAND).";
26
+ const local = bridgeConfigured || ownLocal !== undefined;
27
+ return [
28
+ { id: "lan", label: "Local network", available: local, ...(local ? {} : { reason: needsBridge }), controls: signedControls },
29
+ { id: "cloud", label: "Bambu Cloud", available: bridgeConfigured, ...(bridgeConfigured ? {} : { reason: needsBridge }), controls: signedControls },
30
+ { id: "developer", label: "Local network, Developer Mode", available: true,
31
+ controls: "Pause, Resume and Stop go straight to the printer. Turn on LAN Only and Developer Mode on the printer first; Bambu Cloud and Bambu Handy then stop working for it." },
32
+ ];
33
+ }
34
+ /**
35
+ * The configured defaults for a route. Cloud and the local network use FULU's BambuNetwork; an X2D native or
36
+ * Bambu Connect setup keeps its own mode for the local network. Developer Mode is the direct LAN route.
37
+ */
38
+ export function connectionForRoute(route, current, bridgeConfigured = true, ownLocal = ownLocalOf(current)) {
39
+ const option = routeOptions(current, bridgeConfigured, ownLocal).find(item => item.id === route);
40
+ if (!option?.available)
41
+ throw new Error(`The ${option?.label ?? route} connection isn't available here. ${option?.reason ?? ""}`.trim());
42
+ if (route === "cloud")
43
+ return { mode: "bambu_network", type: "cloud" };
44
+ if (route === "developer")
45
+ return { mode: "lan_mqtt_ftps", type: "lan" };
46
+ return ownLocal ?? { mode: "bambu_network", type: "lan" };
47
+ }
48
+ /** Set KEY=value lines in a dotenv file, keeping every other line and the file's permissions. */
49
+ export function writeEnvValues(file, values) {
50
+ const original = fs.readFileSync(file, "utf8");
51
+ const lines = original.split("\n");
52
+ for (const [key, value] of Object.entries(values)) {
53
+ const pattern = new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`);
54
+ let found = false;
55
+ for (let index = lines.length - 1; index >= 0; index--) {
56
+ if (!pattern.test(lines[index]))
57
+ continue;
58
+ if (!found) {
59
+ lines[index] = `${key}=${value}`;
60
+ found = true;
61
+ }
62
+ // dotenv lets a later line win: keep one line per key, the one written here.
63
+ else
64
+ lines.splice(index, 1);
65
+ }
66
+ if (!found) {
67
+ if (lines.length && lines[lines.length - 1] === "")
68
+ lines.splice(lines.length - 1, 0, `${key}=${value}`);
69
+ else
70
+ lines.push(`${key}=${value}`);
71
+ }
72
+ }
73
+ const mode = fs.statSync(file).mode & 0o777;
74
+ const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`);
75
+ fs.writeFileSync(temporary, lines.join("\n"), { mode });
76
+ fs.chmodSync(temporary, mode);
77
+ fs.renameSync(temporary, file);
78
+ }
@@ -63,6 +63,7 @@ export type PrinterInfo = {
63
63
  progress: boolean;
64
64
  layers: boolean;
65
65
  camera: "bambu-tcp" | "rtsp" | "http-snapshot" | "none";
66
+ cameraStream?: boolean;
66
67
  filaments: "ams" | "single" | "none";
67
68
  pause: boolean;
68
69
  resume: boolean;
@@ -125,6 +126,9 @@ export declare const PRINTER_INFO_OUTPUT_SCHEMA: {
125
126
  type: string;
126
127
  enum: string[];
127
128
  };
129
+ cameraStream: {
130
+ type: string;
131
+ };
128
132
  filaments: {
129
133
  type: string;
130
134
  enum: string[];
@@ -39,6 +39,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
39
39
  progress: { type: "boolean" },
40
40
  layers: { type: "boolean" },
41
41
  camera: { type: "string", enum: ["bambu-tcp", "rtsp", "http-snapshot", "none"] },
42
+ cameraStream: { type: "boolean" },
42
43
  filaments: { type: "string", enum: ["ams", "single", "none"] },
43
44
  pause: { type: "boolean" },
44
45
  resume: { type: "boolean" },