bambu-printer-mcp 1.1.51 → 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 +202 -45
  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 +3 -0
  35. package/dist/stl/stl-manipulator.js +50 -4
  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 +195 -49
  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 +58 -5
@@ -1,9 +1,10 @@
1
1
  import { spawn, type ChildProcessWithoutNullStreams } 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
 
8
9
  const FRAME_MAGIC = 0x52424a50;
9
10
  const FRAME_HEADER_SIZE = 16;
@@ -28,11 +29,64 @@ export function describeBambuNetworkPrintError(value: number): string {
28
29
  return BAMBU_NETWORK_PRINT_ERRORS[value] ? ` (${BAMBU_NETWORK_PRINT_ERRORS[value]})` : "";
29
30
  }
30
31
  /** Waits from native/bambu-native-print.cpp, which prints through the same plug-in calls. */
31
- export const LOCAL_PRINT_TIMING = Object.freeze({ connectTimeoutMs: 30_000, pollMs: 250, settleMs: 3_000, retryWaitMs: 8_000 });
32
+ export type LocalTiming = { connectTimeoutMs: number; pollMs: number; settleMs: number; retryWaitMs: number };
33
+ export const LOCAL_PRINT_TIMING: Readonly<LocalTiming> = Object.freeze({ connectTimeoutMs: 30_000, pollMs: 250, settleMs: 3_000, retryWaitMs: 8_000 });
34
+ /** A control waits briefly for the certificate message, then sends; -4/-4030 returns are retried after a reinstall. */
35
+ export type LocalControlTiming = LocalTiming & { certificateWaitMs: number; attempts: number; deliveryMs: number };
36
+ export const LOCAL_CONTROL_TIMING: Readonly<LocalControlTiming> = Object.freeze({ ...LOCAL_PRINT_TIMING, settleMs: 1_000, retryWaitMs: 1_500, certificateWaitMs: 5_000, attempts: 3, deliveryMs: 5_000 });
37
+
38
+ /** Bounded event text for diagnostics, with any access code removed. */
39
+ function traceText(text: string): string {
40
+ const clean = text.replace(/("?access_code"?\s*[:=]\s*"?)[^",}\s]*/gi, "$1[redacted]");
41
+ // A signed printer reply (a header, then its payload) is the printer's answer to a command: keep it whole.
42
+ return clean.startsWith('{"header"') ? clean.slice(0, 4000) : clean.slice(0, 160);
43
+ }
44
+
45
+ export { controlReply, isAuthorizationRefusal } from "./control-reply.js";
46
+
47
+ /** Result of a sent control from the printer's answer during the hold; a refusal throws. */
48
+ function controlResult(command: string, route: string, reply: { accepted: boolean; errCode: number } | undefined, attempts: number): Record<string, unknown> {
49
+ const word = `${command[0].toUpperCase()}${command.slice(1)}`;
50
+ if (reply && !reply.accepted) throw new Error(refusedControlMessage(command, route, reply.errCode));
51
+ return { status: "success", attempts, confirmed: Boolean(reply),
52
+ message: reply ? `The printer accepted ${word}.` : `${word} submitted over ${route}. Check printer status to confirm it took effect.` };
53
+ }
54
+
55
+ /** Cloud session waits: connection and printer subscription, certificate, settle after the state requests. */
56
+ export type CloudTiming = { connectTimeoutMs: number; pollMs: number; settleMs: number; certificateWaitMs: number };
57
+ export const CLOUD_PRINT_TIMING: Readonly<CloudTiming> = Object.freeze({ connectTimeoutMs: 30_000, pollMs: 250, settleMs: 3_000, certificateWaitMs: 10_000 });
58
+ export type CloudSession = {
59
+ settle: (ms: number) => Promise<void>;
60
+ /** Ask the plug-in to install the printer's certificate again, as Bambu Studio does after a failed send. */
61
+ installCertificate: () => Promise<void>;
62
+ /** Wait up to ms for device_cert_installed; true once it has arrived. */
63
+ certificateReadyWithin: (ms: number) => Promise<boolean>;
64
+ /** This printer's cloud messages, as they arrive. */
65
+ messages: string[];
66
+ jobUpdates: BridgeJobUpdate[];
67
+ };
68
+ let stateSequence = 0;
69
+ const nextSequence = () => String(++stateSequence);
70
+ // The signed Studio channel on P1S 01.10 accepts string IDs in [20000, 29999].
71
+ // Larger IDs receive 0502400A even when the RSA signature is valid. Share the
72
+ // counter across LAN/cloud controls and retries; never derive IDs from wall time.
73
+ let controlSequence = 19_999;
74
+ const nextControlSequence = () => String(controlSequence = controlSequence >= 29_999 ? 20_000 : controlSequence + 1);
75
+
32
76
 
33
77
  export type LocalPrinter = { devId: string; devIp: string; username: string; password: string; useSsl: boolean };
34
78
  export type BridgeJobUpdate = { status: unknown; code: unknown; msg: unknown };
35
- export type LocalSession = { installCertificate: () => Promise<void>; settle: (ms: number) => Promise<void>; jobUpdates: BridgeJobUpdate[] };
79
+ export type LocalSession = {
80
+ installCertificate: () => Promise<void>;
81
+ settle: (ms: number) => Promise<void>;
82
+ /** Waits up to ms for FULU's certificate-installed message for this printer; false if it never came. */
83
+ certificateReadyWithin: (ms: number) => Promise<boolean>;
84
+ /** This printer's messages about stop/pause/resume, as they arrive. */
85
+ controlMessages: string[];
86
+ jobUpdates: BridgeJobUpdate[];
87
+ };
88
+ /** One line per FULU event or control send, for diagnosing controls. Never includes access codes. */
89
+ export type BridgeTrace = (entry: Record<string, unknown>) => void;
36
90
 
37
91
  type JsonObject = Record<string, unknown>;
38
92
 
@@ -52,6 +106,8 @@ export type BambuNetworkBridgeOptions = {
52
106
  /** Trusted in-process preflight; never populated from tool arguments. */
53
107
  beforeDispatch?: (method: string) => Promise<void>;
54
108
  assertDispatchAllowed?: (method: string) => void;
109
+ /** Diagnostics for a print control: every FULU event and send in its session. */
110
+ trace?: BridgeTrace;
55
111
  onDispatched?: (method: string) => void;
56
112
  };
57
113
 
@@ -118,6 +174,34 @@ function trimEnv(value: string | undefined): string | undefined {
118
174
  return trimmed ? trimmed : undefined;
119
175
  }
120
176
 
177
+ /**
178
+ * The client identity FULU's GUI gives the plug-in before agent start
179
+ * (GUI_App::init_http_extra_header). Through the Linux bridge FULU presents
180
+ * itself as Bambu Studio at the version its plug-in ABI belongs to
181
+ * (PJarczakLinuxBridgeConfig.cpp forced_client_version, "02.05.02.51").
182
+ * Bambu's cloud issues the printer-control certificate and creates print
183
+ * tasks for this client, so an agent started without it is an unknown client.
184
+ * The device id is kept in the config folder so it stays the same per install.
185
+ */
186
+ export function bambuNetworkClientHeaders(configDir: string, env: NodeJS.ProcessEnv = process.env): Record<string, string> {
187
+ const idFile = path.join(configDir, "client-device-id");
188
+ let deviceId = "";
189
+ try { deviceId = fs.readFileSync(idFile, "utf8").trim(); } catch { /* first start */ }
190
+ if (!deviceId) {
191
+ deviceId = randomUUID();
192
+ try { fs.mkdirSync(configDir, { recursive: true }); fs.writeFileSync(idFile, `${deviceId}\n`, { mode: 0o600 }); } catch { /* still send this run's id */ }
193
+ }
194
+ return {
195
+ "X-BBL-Client-Type": "slicer",
196
+ "X-BBL-Client-Name": trimEnv(env.BAMBU_NETWORK_CLIENT_NAME) ?? "BambuStudio",
197
+ "X-BBL-Client-Version": trimEnv(env.BAMBU_NETWORK_CLIENT_VERSION) ?? "02.05.02.51",
198
+ "X-BBL-OS-Type": "linux",
199
+ "X-BBL-OS-Version": os.release(),
200
+ "X-BBL-Device-ID": deviceId,
201
+ "X-BBL-Language": "en",
202
+ };
203
+ }
204
+
121
205
  function fileExists(filePath: string): boolean {
122
206
  try {
123
207
  return fs.existsSync(filePath);
@@ -244,6 +328,10 @@ function bridgeNumericResult(value: unknown): number | undefined {
244
328
  : undefined;
245
329
  }
246
330
 
331
+ function bridgeValueIsTrue(value: unknown): boolean {
332
+ return typeof value === "object" && value !== null && (value as { value?: unknown }).value === true;
333
+ }
334
+
247
335
  function assertBridgeOk(value: unknown, method: string): void {
248
336
  if (isBridgeFailure(value)) {
249
337
  const errorText = value.error === undefined ? "unknown bridge error" : String(value.error);
@@ -433,6 +521,8 @@ export class BambuNetworkBridge {
433
521
  // plug-in verifies a LAN printer with printer.cer from this folder, and
434
522
  // FULU's host crashes on connect_printer when no folder was ever set.
435
523
  const certificates = await withAgent("net.set_cert_file", { folder: certDir, filename: "slicer_base64.cer" }, false);
524
+ // FULU's GUI order: set_cert_file, then the client headers, then start.
525
+ await withAgent("net.set_extra_http_header", { headers: bambuNetworkClientHeaders(configDir) }, false);
436
526
  await withAgent("net.set_country_code", { country_code: countryCode });
437
527
  await withAgent("net.start");
438
528
  // The plug-in runs callbacks through queue_on_main; FULU's host executes
@@ -466,7 +556,7 @@ export class BambuNetworkBridge {
466
556
  printer: LocalPrinter,
467
557
  options: BambuNetworkBridgeOptions,
468
558
  assertActive: () => void,
469
- timing: typeof LOCAL_PRINT_TIMING,
559
+ timing: Readonly<LocalTiming>,
470
560
  run: (session: LocalSession) => Promise<T>
471
561
  ): Promise<T> {
472
562
  const previous = this.localSessionTail;
@@ -484,10 +574,12 @@ export class BambuNetworkBridge {
484
574
  printer: LocalPrinter,
485
575
  options: BambuNetworkBridgeOptions,
486
576
  assertActive: () => void,
487
- timing: typeof LOCAL_PRINT_TIMING,
577
+ timing: Readonly<LocalTiming>,
488
578
  run: (session: LocalSession) => Promise<T>
489
579
  ): Promise<T> {
490
580
  const jobUpdates: BridgeJobUpdate[] = [];
581
+ const controlMessages: string[] = [];
582
+ let certificateReady = false;
491
583
  const installCertificate = async () => {
492
584
  await this.callWithAgent("net.install_device_cert", { dev_id: printer.devId, lan_only: true }, options);
493
585
  await this.callWithAgent("net.update_cert", {}, options);
@@ -500,9 +592,18 @@ export class BambuNetworkBridge {
500
592
  const statuses: unknown[] = [];
501
593
  let waitInfo = false;
502
594
  for (const event of Array.isArray(polled?.events) ? polled.events : []) {
595
+ options.trace?.({ event: event?.name, devMatch: event?.payload?.dev_id === undefined ? "none" : event.payload.dev_id === printer.devId,
596
+ ...(event?.payload?.status !== undefined ? { status: event.payload.status } : {}), ...(typeof event?.payload?.msg === "string" ? { msg: traceText(event.payload.msg) } : {}) });
503
597
  if (event?.name === "job.update_status") jobUpdates.push({ status: event.payload?.status, code: event.payload?.code, msg: event.payload?.msg });
504
598
  const eventDev = event?.payload?.dev_id;
505
599
  if (eventDev !== undefined && eventDev !== "" && eventDev !== printer.devId) continue;
600
+ // FULU v1.0.0 GUI_App's certificate-state callback. A connect callback
601
+ // alone does not establish that protected controls can be encrypted.
602
+ if (eventDev === printer.devId && (event?.name === "on_local_message" || event?.name === "on_message")) {
603
+ if (event.payload?.msg === "device_cert_installed") certificateReady = true;
604
+ if (event.payload?.msg === "device_cert_uninstalled") certificateReady = false;
605
+ if (typeof event.payload?.msg === "string" && /"command":"(stop|pause|resume)"/.test(event.payload.msg)) controlMessages.push(event.payload.msg);
606
+ }
506
607
  if (event?.name === "on_local_connect") statuses.push(event.payload.status);
507
608
  if ((event?.name === "on_local_message" || event?.name === "on_message") && event.payload?.msg === "wait_info") waitInfo = true;
508
609
  }
@@ -516,17 +617,28 @@ export class BambuNetworkBridge {
516
617
  await new Promise(resolve => setTimeout(resolve, timing.pollMs));
517
618
  }
518
619
  };
620
+ const certificateReadyWithin = async (ms: number) => {
621
+ const deadline = Date.now() + ms;
622
+ do {
623
+ assertActive();
624
+ await pump();
625
+ if (certificateReady) return true;
626
+ await new Promise(resolve => setTimeout(resolve, timing.pollMs));
627
+ } while (Date.now() < deadline);
628
+ return certificateReady;
629
+ };
519
630
 
520
631
  await this.ensureAgent(options);
521
632
  assertActive();
522
633
  if (!this.localSessionReady) {
523
634
  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.");
524
635
  }
525
- for (const callback of ["net.set_on_printer_connected_fn", "net.set_on_local_message_fn"]) {
636
+ for (const callback of ["net.set_on_printer_connected_fn", "net.set_on_message_fn", "net.set_on_local_message_fn"]) {
526
637
  assertBridgeOk(await this.callWithAgent(callback, {}, options), callback);
527
638
  }
528
639
  await this.callWithAgent("net.update_cert", {}, options);
529
640
  await pump();
641
+ certificateReady = false; // Ignore completion queued by an earlier session.
530
642
  assertActive();
531
643
  const requested = await this.callWithAgent("net.connect_printer", {
532
644
  dev_id: printer.devId, dev_ip: printer.devIp, username: printer.username, password: printer.password, use_ssl: printer.useSsl,
@@ -567,7 +679,7 @@ export class BambuNetworkBridge {
567
679
  await this.callWithAgent("net.send_message_to_printer", { dev_id: printer.devId, msg: JSON.stringify(message), qos, flag: 0 }, options);
568
680
  }
569
681
  await settle(timing.settleMs);
570
- const result = await run({ installCertificate, settle, jobUpdates });
682
+ const result = await run({ installCertificate, settle, certificateReadyWithin, controlMessages, jobUpdates });
571
683
  await pump();
572
684
  return result;
573
685
  } finally {
@@ -589,7 +701,7 @@ export class BambuNetworkBridge {
589
701
  payload: JsonObject,
590
702
  options: BambuNetworkBridgeOptions = {},
591
703
  assertActive: () => void = () => {},
592
- timing: typeof LOCAL_PRINT_TIMING = LOCAL_PRINT_TIMING
704
+ timing: Readonly<LocalTiming> = LOCAL_PRINT_TIMING
593
705
  ): Promise<{ result: unknown; jobUpdates: BridgeJobUpdate[] }> {
594
706
  return await this.withLocalSession(printer, options, assertActive, timing, async session => {
595
707
  let result = await this.callWithAgent(method, payload, options);
@@ -603,6 +715,197 @@ export class BambuNetworkBridge {
603
715
  });
604
716
  }
605
717
 
718
+ /**
719
+ * A print control (stop, pause, resume) through the same authenticated LAN
720
+ * session as a FULU print. FULU's own app sends controls exactly this way
721
+ * (send_message_to_printer, qos 1, flag 0) on a connection whose certificate
722
+ * is installed. A fresh connection can report SEND_MSG_FAILED (-4) or
723
+ * LP_PUBLISH_MSG_FAILED (-4030) while that exchange finishes: those returns
724
+ * mean nothing was sent, so the certificate is reinstalled and the control
725
+ * tried again, as the native X2D helper does. Any other return is final.
726
+ * beforeDispatch runs before every send, so a resume re-checks the paused job.
727
+ */
728
+ async sendLocalPrintCommand(printer: LocalPrinter, command: "stop" | "pause" | "resume", options: BambuNetworkBridgeOptions = {},
729
+ beforeDispatch?: () => Promise<void>, timing: Readonly<LocalControlTiming> = LOCAL_CONTROL_TIMING): Promise<Record<string, unknown>> {
730
+ const assertActive = () => options.assertDispatchAllowed?.("net.send_message_to_printer");
731
+ const trace = options.trace ?? this.controlTrace(options);
732
+ const traced = { ...options, trace };
733
+ return this.withLocalSession(printer, traced, assertActive, timing, async session => {
734
+ const ready = await session.certificateReadyWithin(timing.certificateWaitMs);
735
+ trace({ step: "certificate", ready });
736
+ const method = "net.send_message_to_printer";
737
+ let code = 0;
738
+ for (let attempt = 1; attempt <= timing.attempts; attempt++) {
739
+ await beforeDispatch?.();
740
+ assertActive();
741
+ const sequenceId = nextControlSequence();
742
+ const result = await this.callWithAgent(method, {
743
+ dev_id: printer.devId,
744
+ msg: JSON.stringify({ print: { command, param: "", sequence_id: sequenceId } }),
745
+ qos: 1, flag: 0,
746
+ }, traced);
747
+ assertBridgeOk(result, method);
748
+ code = bridgeValueAsNumber(result, method);
749
+ trace({ step: "send", command, attempt, code });
750
+ if (code === 0) {
751
+ // The plug-in queues the publish; disconnecting at once dropped it (Nov 3: five accepted
752
+ // controls, printer never paused or stopped). Stay connected while it reaches the printer.
753
+ await session.settle(timing.deliveryMs);
754
+ trace({ step: "delivered", command, heldMs: timing.deliveryMs });
755
+ const reply = session.controlMessages.map(msg => controlReply(msg, command, sequenceId)).find(Boolean);
756
+ return controlResult(command, "the local network", reply, attempt);
757
+ }
758
+ if ((code !== -4 && code !== -4030) || attempt === timing.attempts) break;
759
+ await session.settle(timing.retryWaitMs);
760
+ await session.installCertificate();
761
+ await session.certificateReadyWithin(timing.certificateWaitMs);
762
+ }
763
+ throw new Error(`The printer did not accept ${command} over the authenticated FULU LAN connection (plug-in code ${code}).`);
764
+ });
765
+ }
766
+
767
+ /**
768
+ * Open the plug-in's Bambu Cloud session with a printer bound to the account, in the order
769
+ * Bambu Studio uses (GUI_App.cpp on_server_connected / on_printer_connected): wait for the
770
+ * cloud connection, select and subscribe to the printer, and when it connects request its
771
+ * state (pushall, get_version, get_access_code) and install its certificate for cloud use.
772
+ * Without that state the plug-in refuses a cloud print with -3140 (ENC_FLAG_NOT_READY).
773
+ * Shares the LAN session queue: one reader of the plug-in's events at a time.
774
+ */
775
+ async withCloudSession<T>(
776
+ devId: string,
777
+ options: BambuNetworkBridgeOptions,
778
+ assertActive: () => void,
779
+ timing: Readonly<CloudTiming>,
780
+ run: (session: CloudSession) => Promise<T>
781
+ ): Promise<T> {
782
+ const previous = this.localSessionTail;
783
+ let release!: () => void;
784
+ this.localSessionTail = new Promise<void>(resolve => { release = resolve; });
785
+ try {
786
+ await previous;
787
+ await this.ensureAgent(options);
788
+ assertActive();
789
+ if (!bridgeValueIsTrue(await this.callWithAgent("net.is_user_login", {}, options))) {
790
+ throw new Error("FULU's networking plug-in is not signed in to Bambu Cloud, so nothing was sent to the printer.");
791
+ }
792
+ for (const callback of ["net.set_on_printer_connected_fn", "net.set_on_message_fn", "net.set_on_server_connected_fn"]) {
793
+ assertBridgeOk(await this.callWithAgent(callback, {}, options), callback);
794
+ }
795
+ const messages: string[] = [];
796
+ const jobUpdates: BridgeJobUpdate[] = [];
797
+ let printerConnected = false;
798
+ let certificateReady = false;
799
+ const pump = async () => {
800
+ const polled = await this.request("bridge.poll_events", { limit: 1024 }, options) as { events?: any[] };
801
+ assertBridgeOk(polled, "bridge.poll_events");
802
+ for (const event of Array.isArray(polled?.events) ? polled.events : []) {
803
+ const eventDev = event?.payload?.dev_id ?? (typeof event?.payload?.topic_str === "string" ? event.payload.topic_str.replace(/^tunnel\//, "") : undefined);
804
+ options.trace?.({ event: event?.name, devMatch: eventDev === undefined ? "none" : eventDev === devId, ...(typeof event?.payload?.msg === "string" ? { msg: traceText(event.payload.msg) } : {}) });
805
+ if (event?.name === "job.update_status") jobUpdates.push({ status: event.payload?.status, code: event.payload?.code, msg: event.payload?.msg });
806
+ if (eventDev !== devId) continue;
807
+ if (event?.name === "on_printer_connected") printerConnected = true;
808
+ if (event?.name === "on_message" && typeof event.payload?.msg === "string") {
809
+ if (event.payload.msg === "device_cert_installed") certificateReady = true;
810
+ else if (event.payload.msg === "device_cert_uninstalled") certificateReady = false;
811
+ else messages.push(event.payload.msg);
812
+ }
813
+ }
814
+ };
815
+ const waitFor = async (done: () => boolean, ms: number) => {
816
+ for (const deadline = Date.now() + ms; !done() && Date.now() < deadline;) {
817
+ assertActive();
818
+ await pump();
819
+ if (!done()) await new Promise(resolve => setTimeout(resolve, timing.pollMs));
820
+ }
821
+ return done();
822
+ };
823
+ const settle = async (ms: number) => { await waitFor(() => false, ms); };
824
+ for (const deadline = Date.now() + timing.connectTimeoutMs; !bridgeValueIsTrue(await this.callWithAgent("net.is_server_connected", {}, options));) {
825
+ if (Date.now() >= deadline) 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.`);
826
+ assertActive();
827
+ await new Promise(resolve => setTimeout(resolve, timing.pollMs));
828
+ }
829
+ await this.callWithAgent("net.set_user_selected_machine", { dev_id: devId }, options);
830
+ await this.callWithAgent("net.add_subscribe", { devs: [devId] }, options);
831
+ if (!await waitFor(() => printerConnected, timing.connectTimeoutMs)) {
832
+ 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.`);
833
+ }
834
+ for (const [message, qos] of [
835
+ [{ pushing: { sequence_id: nextSequence(), command: "pushall", version: 1, push_target: 1 } }, 0],
836
+ [{ info: { sequence_id: nextSequence(), command: "get_version" } }, 1],
837
+ [{ system: { sequence_id: nextSequence(), command: "get_access_code" } }, 0],
838
+ ] as const) {
839
+ await this.callWithAgent("net.send_message", { dev_id: devId, msg: JSON.stringify(message), qos, flag: 0 }, options);
840
+ }
841
+ const installCertificate = async () => { await this.callWithAgent("net.install_device_cert", { dev_id: devId, lan_only: false }, options); };
842
+ const certificateReadyWithin = (ms: number) => waitFor(() => certificateReady, ms);
843
+ await installCertificate();
844
+ const ready = await certificateReadyWithin(timing.certificateWaitMs);
845
+ options.trace?.({ step: "certificate", route: "cloud", ready });
846
+ await settle(timing.settleMs);
847
+ const result = await run({ settle, messages, jobUpdates, installCertificate, certificateReadyWithin });
848
+ await pump();
849
+ return result;
850
+ } finally {
851
+ release();
852
+ }
853
+ }
854
+
855
+ /** A cloud print method (start_print) in a cloud session, so the plug-in has the printer's state. */
856
+ async startCloudPrint(devId: string, method: string, payload: JsonObject, options: BambuNetworkBridgeOptions = {},
857
+ assertActive: () => void = () => {}, timing: Readonly<CloudTiming> = CLOUD_PRINT_TIMING): Promise<{ result: unknown; jobUpdates: BridgeJobUpdate[] }> {
858
+ return await this.withCloudSession(devId, options, assertActive, timing, async session => ({ result: await this.callWithAgent(method, payload, options), jobUpdates: session.jobUpdates }));
859
+ }
860
+
861
+ /**
862
+ * A print control over Bambu Cloud: how Bambu Studio and FULU's slicer control a printer
863
+ * bound to the account (MachineObject::publish_json → cloud_publish_json: send_message,
864
+ * qos 1, flag 0), in a cloud session. Held open like the LAN control.
865
+ */
866
+ async sendCloudPrintCommand(devId: string, command: "stop" | "pause" | "resume", options: BambuNetworkBridgeOptions = {},
867
+ beforeDispatch?: () => Promise<void>, timing: Readonly<LocalControlTiming> = LOCAL_CONTROL_TIMING): Promise<Record<string, unknown>> {
868
+ const method = "net.send_message";
869
+ const assertActive = () => options.assertDispatchAllowed?.(method);
870
+ const trace = options.trace ?? this.controlTrace(options);
871
+ const traced = { ...options, trace };
872
+ return this.withCloudSession(devId, traced, assertActive, timing, async session => {
873
+ let code = 0;
874
+ for (let attempt = 1; attempt <= timing.attempts; attempt++) {
875
+ await beforeDispatch?.();
876
+ assertActive();
877
+ const sequenceId = nextControlSequence();
878
+ const result = await this.callWithAgent(method, {
879
+ dev_id: devId, msg: JSON.stringify({ print: { command, param: "", sequence_id: sequenceId } }), qos: 1, flag: 0,
880
+ }, traced);
881
+ assertBridgeOk(result, method);
882
+ code = bridgeValueAsNumber(result, method);
883
+ trace({ step: "send", route: "cloud", command, attempt, code });
884
+ if (code === 0) {
885
+ await session.settle(timing.deliveryMs);
886
+ trace({ step: "delivered", route: "cloud", command, heldMs: timing.deliveryMs });
887
+ return controlResult(command, "Bambu Cloud", session.messages.map(msg => controlReply(msg, command, sequenceId)).find(Boolean), attempt);
888
+ }
889
+ // Before the printer's certificate is installed the plug-in sends nothing and returns
890
+ // CONNECT_FAILED (-2) or SEND_MSG_FAILED (-4), as on the LAN route (Nov 3: cloud pause -2
891
+ // with the certificate not yet installed). Reinstall it, wait, and send again.
892
+ if ((code !== -2 && code !== -4) || attempt === timing.attempts) break;
893
+ await session.settle(timing.retryWaitMs);
894
+ await session.installCertificate();
895
+ trace({ step: "certificate", route: "cloud", attempt, ready: await session.certificateReadyWithin(timing.certificateWaitMs) });
896
+ }
897
+ throw new Error(`Bambu Cloud did not accept ${command} for printer ${devId} (plug-in code ${code}).`);
898
+ });
899
+ }
900
+
901
+ /** Appends control diagnostics to control-trace.log in the bridge's config folder. */
902
+ private controlTrace(options: BambuNetworkBridgeOptions): BridgeTrace {
903
+ const file = path.join(this.resolveConfigDir(options.configDir), "control-trace.log");
904
+ return entry => {
905
+ try { fs.appendFileSync(file, JSON.stringify({ at: new Date().toISOString(), ...entry }) + "\n", { mode: 0o600 }); } catch { /* diagnostics only */ }
906
+ };
907
+ }
908
+
606
909
  async callWithAgent(
607
910
  method: string,
608
911
  payload: JsonObject = {},
@@ -0,0 +1,41 @@
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
+ export type ControlReply = { accepted: boolean; errCode: number };
7
+
8
+ /**
9
+ * The printer's answer to a control it was sent: it echoes command and sequence_id, with
10
+ * err_code set when it refuses. A P1S on authorization firmware signs it: {"header":{...},"print":{...}}.
11
+ */
12
+ export function controlReply(msg: unknown, command: string, sequenceId: string): ControlReply | undefined {
13
+ if (typeof msg !== "string" || !msg.includes(sequenceId)) return undefined;
14
+ let print: any;
15
+ try { print = JSON.parse(msg)?.print; } catch { return undefined; }
16
+ if (print?.command !== command || String(print.sequence_id) !== sequenceId) return undefined;
17
+ const errCode = Number(print.err_code ?? 0) || 0;
18
+ const failed = typeof print.result === "string" && print.result.toLowerCase() !== "success";
19
+ return { accepted: errCode === 0 && !failed, errCode };
20
+ }
21
+
22
+ /**
23
+ * The printer's command verification refused the envelope. These codes do not
24
+ * establish that third-party controls are unsupported: P1S 01.10 also returns
25
+ * 0x0502400A for a valid signature with a sequence ID outside the Studio window.
26
+ */
27
+ export function isAuthorizationRefusal(errCode: number): boolean {
28
+ const code = errCode >>> 0;
29
+ return code >= 0x05024007 && code <= 0x0502400B;
30
+ }
31
+
32
+ /** What to tell a person about a refused control. direct: the control went straight to the printer (Developer Mode connection). */
33
+ export function refusedControlMessage(command: string, route: string, errCode: number, direct = false): string {
34
+ const word = `${command[0]!.toUpperCase()}${command.slice(1)}`;
35
+ const code = (errCode >>> 0).toString(16).toUpperCase().padStart(8, "0");
36
+ if (!isAuthorizationRefusal(errCode)) return `The printer refused ${word} over ${route} (error ${code}). Nothing changed on the printer.`;
37
+ const message = `The printer refused ${word} (error ${code}): its command verification failed. `;
38
+ return message + (direct
39
+ ? "Check LAN Only and Developer Mode for the direct connection, or choose an authenticated Local network or Bambu Cloud connection."
40
+ : "Check the authenticated connection and signing setup for this printer.");
41
+ }
@@ -24,6 +24,7 @@ export function bambuPrinterInfo(options: { server: { name: string; version: str
24
24
  layers: true,
25
25
  // camera_snapshot needs the model to choose its transport.
26
26
  camera: model && TCP_CAMERA_MODELS.has(model) ? "bambu-tcp" : model && RTSP_CAMERA_MODELS.has(model) ? "rtsp" : "none",
27
+ cameraStream: !!model && (TCP_CAMERA_MODELS.has(model) || RTSP_CAMERA_MODELS.has(model)),
27
28
  filaments: "ams",
28
29
  pause: true,
29
30
  resume: true,
@@ -0,0 +1,91 @@
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
+
5
+ /**
6
+ * lan: the local network through FULU's BambuNetwork bridge (or the configured X2D native or Bambu Connect mode).
7
+ * cloud: Bambu Cloud through FULU's bridge.
8
+ * developer: the local network straight to the printer (lan_mqtt_ftps), for a printer in LAN Only + Developer Mode.
9
+ */
10
+ export type PrintRoute = "lan" | "cloud" | "developer";
11
+ export const PRINT_ROUTES: readonly PrintRoute[] = ["lan", "cloud", "developer"];
12
+ export interface Connection { mode: string; type: string }
13
+
14
+ /** One connection a person can choose, as counterpart_print_route reports it. */
15
+ export interface RouteOption {
16
+ id: PrintRoute;
17
+ label: string;
18
+ available: boolean;
19
+ /** Why it can't be chosen here, when it can't. */
20
+ reason?: string;
21
+ /** What Pause, Resume and Stop do on this connection. */
22
+ controls: string;
23
+ }
24
+
25
+ /** Modes that are their own local-network route and stay as configured. */
26
+ const OWN_LOCAL_MODES = new Set(["bambu_native", "bambu_connect"]);
27
+
28
+ export function routeOf(connection: Connection): PrintRoute {
29
+ if (connection.mode === "bambu_network") return connection.type === "cloud" ? "cloud" : "lan";
30
+ if (connection.mode === "lan_mqtt_ftps") return "developer";
31
+ return "lan";
32
+ }
33
+
34
+ /** The current connection when it is its own local route (X2D native or Bambu Connect); otherwise none. */
35
+ export function ownLocalOf(current: Connection): Connection | undefined {
36
+ return OWN_LOCAL_MODES.has(current.mode) ? current : undefined;
37
+ }
38
+
39
+ /**
40
+ * Every connection, and whether this server can use it (bridgeConfigured: BAMBU_NETWORK_BRIDGE_COMMAND is set).
41
+ * ownLocal is the printer's own local route (X2D native or Bambu Connect), kept apart from the current choice
42
+ * so switching to Developer Mode or Bambu Cloud and back returns to it.
43
+ */
44
+ export function routeOptions(current: Connection, bridgeConfigured: boolean, ownLocal = ownLocalOf(current)): RouteOption[] {
45
+ const signedControls = "Uses the configured authenticated connection for Print, Pause, Resume and Stop.";
46
+ const needsBridge = "Needs FULU's BambuNetwork bridge (BAMBU_NETWORK_BRIDGE_COMMAND).";
47
+ const local = bridgeConfigured || ownLocal !== undefined;
48
+ return [
49
+ { id: "lan", label: "Local network", available: local, ...(local ? {} : { reason: needsBridge }), controls: signedControls },
50
+ { id: "cloud", label: "Bambu Cloud", available: bridgeConfigured, ...(bridgeConfigured ? {} : { reason: needsBridge }), controls: signedControls },
51
+ { id: "developer", label: "Local network, Developer Mode", available: true,
52
+ 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." },
53
+ ];
54
+ }
55
+
56
+ /**
57
+ * The configured defaults for a route. Cloud and the local network use FULU's BambuNetwork; an X2D native or
58
+ * Bambu Connect setup keeps its own mode for the local network. Developer Mode is the direct LAN route.
59
+ */
60
+ export function connectionForRoute(route: PrintRoute, current: Connection, bridgeConfigured = true, ownLocal = ownLocalOf(current)): Connection {
61
+ const option = routeOptions(current, bridgeConfigured, ownLocal).find(item => item.id === route);
62
+ if (!option?.available) throw new Error(`The ${option?.label ?? route} connection isn't available here. ${option?.reason ?? ""}`.trim());
63
+ if (route === "cloud") return { mode: "bambu_network", type: "cloud" };
64
+ if (route === "developer") return { mode: "lan_mqtt_ftps", type: "lan" };
65
+ return ownLocal ?? { mode: "bambu_network", type: "lan" };
66
+ }
67
+
68
+ /** Set KEY=value lines in a dotenv file, keeping every other line and the file's permissions. */
69
+ export function writeEnvValues(file: string, values: Record<string, string>): void {
70
+ const original = fs.readFileSync(file, "utf8");
71
+ const lines = original.split("\n");
72
+ for (const [key, value] of Object.entries(values)) {
73
+ const pattern = new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`);
74
+ let found = false;
75
+ for (let index = lines.length - 1; index >= 0; index--) {
76
+ if (!pattern.test(lines[index]!)) continue;
77
+ if (!found) { lines[index] = `${key}=${value}`; found = true; }
78
+ // dotenv lets a later line win: keep one line per key, the one written here.
79
+ else lines.splice(index, 1);
80
+ }
81
+ if (!found) {
82
+ if (lines.length && lines[lines.length - 1] === "") lines.splice(lines.length - 1, 0, `${key}=${value}`);
83
+ else lines.push(`${key}=${value}`);
84
+ }
85
+ }
86
+ const mode = fs.statSync(file).mode & 0o777;
87
+ const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`);
88
+ fs.writeFileSync(temporary, lines.join("\n"), { mode });
89
+ fs.chmodSync(temporary, mode);
90
+ fs.renameSync(temporary, file);
91
+ }
@@ -30,6 +30,7 @@ export type PrinterInfo = {
30
30
  capabilities: {
31
31
  progress: boolean; layers: boolean;
32
32
  camera: "bambu-tcp" | "rtsp" | "http-snapshot" | "none";
33
+ cameraStream?: boolean;
33
34
  filaments: "ams" | "single" | "none";
34
35
  pause: boolean; resume: boolean; cancel: boolean; print3mf: boolean; gcode: boolean;
35
36
  };
@@ -67,6 +68,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
67
68
  progress: { type: "boolean" },
68
69
  layers: { type: "boolean" },
69
70
  camera: { type: "string", enum: ["bambu-tcp", "rtsp", "http-snapshot", "none"] },
71
+ cameraStream: { type: "boolean" },
70
72
  filaments: { type: "string", enum: ["ams", "single", "none"] },
71
73
  pause: { type: "boolean" },
72
74
  resume: { type: "boolean" },