bambu-printer-mcp 1.0.8 → 1.1.2

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.
@@ -1,18 +1,255 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
+ import { readFileSync, existsSync } from "node:fs";
3
4
  import path from "node:path";
5
+ import os from "node:os";
6
+ import { Readable } from "node:stream";
4
7
  import JSZip from "jszip";
5
8
  import { Client as FTPClient } from "basic-ftp";
6
- import { Readable } from "node:stream";
7
9
  import { BambuPrinter } from "bambu-js";
8
- import { BambuClient, GCodeFileCommand, GCodeLineCommand, PushAllCommand, UpdateStateCommand, } from "bambu-node";
10
+ import * as mqtt from "mqtt";
11
+ import { BambuClient, GCodeFileCommand, GCodeLineCommand, PushAllCommand, UpdateFanCommand, UpdateLightCommand, UpdateStateCommand, } from "bambu-node";
12
+ /**
13
+ * Post-Jan-2025 H2D firmware requires mTLS with a Bambu-issued client cert.
14
+ * Loads cert+key once from:
15
+ * - BAMBU_CLIENT_CERT / BAMBU_CLIENT_KEY env vars (paths), or
16
+ * - ~/Desktop/bambu certs/embedded-cert.pem + embedded-key.pem (default)
17
+ * Returns null if files missing — caller falls back to no-cert TLS.
18
+ */
19
+ function loadClientCreds() {
20
+ const defaultDir = path.join(os.homedir(), "Desktop", "bambu certs");
21
+ const certPath = process.env.BAMBU_CLIENT_CERT || path.join(defaultDir, "embedded-cert.pem");
22
+ const keyPath = process.env.BAMBU_CLIENT_KEY || path.join(defaultDir, "embedded-key.pem");
23
+ try {
24
+ if (!existsSync(certPath) || !existsSync(keyPath))
25
+ return null;
26
+ return { cert: readFileSync(certPath), key: readFileSync(keyPath) };
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ const CLIENT_CREDS = loadClientCreds();
33
+ const COMMAND_SETTLE_MS = 300;
34
+ const MODEL_ID_TO_NAME = {
35
+ O1D: "H2D",
36
+ O1E: "H2D Pro",
37
+ O1S: "H2S",
38
+ N2S: "A1",
39
+ A1M: "A1 Mini",
40
+ C11: "P1P",
41
+ C12: "P1S",
42
+ "BL-P001": "X1C",
43
+ "BL-P002": "X1",
44
+ C13: "X1E",
45
+ };
46
+ function sleep(ms) {
47
+ return new Promise((resolve) => setTimeout(resolve, ms));
48
+ }
49
+ function resolveModelName(data) {
50
+ const modelId = `${data?.model_id ?? ""}`.toUpperCase();
51
+ return (MODEL_ID_TO_NAME[modelId] ||
52
+ data?.model ||
53
+ data?.device?.devModel ||
54
+ data?.device?.dev_model ||
55
+ "Unknown");
56
+ }
57
+ async function invokeWithoutAck(printer, command) {
58
+ await command.invoke(printer);
59
+ await sleep(COMMAND_SETTLE_MS);
60
+ }
61
+ function getPrinterKey(host, serial, token) {
62
+ return `${host}-${serial}-${token}`;
63
+ }
64
+ class TolerantBambuClient extends BambuClient {
65
+ /**
66
+ * H2D-class firmware streams push status immediately after subscribe, but
67
+ * never answers bambu-node's initial get_version round-trip. Avoid treating
68
+ * that missing ACK as a failed connection.
69
+ */
70
+ async onConnect() {
71
+ const subscribe = this.subscribe.bind(this);
72
+ await subscribe(`device/${this.config.serialNumber}/report`);
73
+ }
74
+ /**
75
+ * H2S/H2D printers don't respond to get_version with module info.
76
+ * Infer model from serial number prefix so downstream code (Job, status
77
+ * parsing, etc.) has a valid printerModel instead of undefined.
78
+ */
79
+ inferModelFromSerial() {
80
+ const sn = this.config.serialNumber;
81
+ if (sn.startsWith("093"))
82
+ return "H2S";
83
+ if (sn.startsWith("094"))
84
+ return "H2D";
85
+ if (sn.startsWith("00M"))
86
+ return "X1C";
87
+ if (sn.startsWith("00W"))
88
+ return "X1";
89
+ if (sn.startsWith("03W"))
90
+ return "X1E";
91
+ if (sn.startsWith("01S"))
92
+ return "P1P";
93
+ if (sn.startsWith("01P"))
94
+ return "P1S";
95
+ if (sn.startsWith("030"))
96
+ return "A1";
97
+ if (sn.startsWith("039"))
98
+ return "A1M";
99
+ return undefined;
100
+ }
101
+ /**
102
+ * Override bambu-node's MQTT connect to pass a client cert+key for mTLS.
103
+ * Post-Jan-2025 H2D firmware rejects TLS handshakes without a valid Bambu-
104
+ * issued client certificate. Options mirror the upstream implementation
105
+ * plus `cert`/`key` when creds are available.
106
+ */
107
+ async connect() {
108
+ await new Promise((resolve, reject) => {
109
+ const self = this;
110
+ if (self.mqttClient) {
111
+ throw new Error("Can't establish a new connection while running another one!");
112
+ }
113
+ const tlsOpts = {
114
+ username: "bblp",
115
+ password: self.config.accessToken,
116
+ reconnectPeriod: self.clientOptions.reconnectInterval,
117
+ connectTimeout: self.clientOptions.connectTimeout,
118
+ keepalive: self.clientOptions.keepAlive,
119
+ resubscribe: true,
120
+ rejectUnauthorized: false,
121
+ };
122
+ if (CLIENT_CREDS) {
123
+ tlsOpts.cert = CLIENT_CREDS.cert;
124
+ tlsOpts.key = CLIENT_CREDS.key;
125
+ }
126
+ const client = mqtt.connect(`mqtts://${self.config.host}:${self.config.port}`, tlsOpts);
127
+ self.mqttClient = client;
128
+ client.on("connect", async (...args) => {
129
+ try {
130
+ await self.onConnect(...args);
131
+ self.emit("client:connect");
132
+ resolve();
133
+ }
134
+ catch (e) {
135
+ reject(e);
136
+ }
137
+ });
138
+ client.on("disconnect", () => {
139
+ self.emit("client:disconnect", false);
140
+ self.emit("printer:statusUpdate", self._printerStatus, "OFFLINE");
141
+ self._printerStatus = "OFFLINE";
142
+ if (self.currentJob)
143
+ self.emit("job:pause", self.currentJob, true);
144
+ });
145
+ client.on("offline", () => {
146
+ self.emit("client:disconnect", true);
147
+ self.emit("printer:statusUpdate", self._printerStatus, "OFFLINE");
148
+ self._printerStatus = "OFFLINE";
149
+ if (self.currentJob)
150
+ self.emit("job:pause", self.currentJob, true);
151
+ });
152
+ client.on("message", (topic, payload) => self.emit("rawMessage", topic, payload));
153
+ client.on("error", (err) => {
154
+ self.emit("client:error", err);
155
+ reject(err);
156
+ });
157
+ });
158
+ // H2S/H2D printers don't respond to get_version with module info.
159
+ // Infer model from serial number prefix so downstream code works.
160
+ if (!this.data.model) {
161
+ const inferred = this.inferModelFromSerial();
162
+ if (inferred) {
163
+ this.data.model = inferred;
164
+ this.emit("printer:dataUpdate", this.data, { model: inferred });
165
+ }
166
+ }
167
+ return [undefined];
168
+ }
169
+ }
170
+ /** Build FTPS secureOptions that include the client cert+key when available. */
171
+ function ftpsSecureOptions() {
172
+ const opts = { rejectUnauthorized: false };
173
+ if (CLIENT_CREDS) {
174
+ opts.cert = CLIENT_CREDS.cert;
175
+ opts.key = CLIENT_CREDS.key;
176
+ }
177
+ return opts;
178
+ }
9
179
  class BambuClientStore {
10
180
  constructor() {
11
181
  this.printers = new Map();
12
182
  this.initialConnectionPromises = new Map();
183
+ this.reportSnapshots = new Map();
184
+ this.initialReportPromises = new Map();
185
+ this.initialReportResolvers = new Map();
186
+ }
187
+ ensureInitialReportPromise(key) {
188
+ const existing = this.initialReportPromises.get(key);
189
+ if (existing) {
190
+ return existing;
191
+ }
192
+ const promise = new Promise((resolve) => {
193
+ this.initialReportResolvers.set(key, resolve);
194
+ });
195
+ this.initialReportPromises.set(key, promise);
196
+ return promise;
197
+ }
198
+ resolveInitialReport(key) {
199
+ const resolve = this.initialReportResolvers.get(key);
200
+ if (!resolve) {
201
+ return;
202
+ }
203
+ this.initialReportResolvers.delete(key);
204
+ resolve();
205
+ }
206
+ updateReportSnapshot(key, update) {
207
+ if (!update || Object.keys(update).length === 0) {
208
+ return;
209
+ }
210
+ const previous = this.reportSnapshots.get(key) || {};
211
+ this.reportSnapshots.set(key, { ...previous, ...update });
212
+ this.resolveInitialReport(key);
213
+ }
214
+ clearPrinterState(key) {
215
+ this.printers.delete(key);
216
+ this.initialConnectionPromises.delete(key);
217
+ this.reportSnapshots.delete(key);
218
+ this.initialReportPromises.delete(key);
219
+ this.initialReportResolvers.delete(key);
220
+ }
221
+ getCachedReport(host, serial, token) {
222
+ return this.reportSnapshots.get(getPrinterKey(host, serial, token)) || null;
223
+ }
224
+ async waitForInitialReport(host, serial, token, timeoutMs = 4000) {
225
+ const key = getPrinterKey(host, serial, token);
226
+ const existing = this.reportSnapshots.get(key);
227
+ if (!existing || Object.keys(existing).length === 0) {
228
+ // No MQTT data yet — wait for the first push.
229
+ const reportPromise = this.ensureInitialReportPromise(key);
230
+ try {
231
+ await Promise.race([
232
+ reportPromise,
233
+ sleep(timeoutMs).then(() => {
234
+ throw new Error(`Timed out waiting for initial printer report after ${timeoutMs}ms.`);
235
+ }),
236
+ ]);
237
+ }
238
+ catch (error) {
239
+ console.warn(`No initial printer report received for ${serial}:`, error);
240
+ }
241
+ }
242
+ // Short settle: the first MQTT push from the printer is a sparse "hello"
243
+ // with only model/modules. A second push carrying the full status
244
+ // (gcode_state, ams, hms, temperatures, fans, etc.) arrives afterward
245
+ // and gets merged into reportSnapshots via incremental update.
246
+ // This settle runs regardless of whether data arrived before or during
247
+ // the promise race above, so the merge has time to complete.
248
+ await sleep(500);
249
+ return this.reportSnapshots.get(key) || null;
13
250
  }
14
251
  async getPrinter(host, serial, token) {
15
- const key = `${host}-${serial}`;
252
+ const key = getPrinterKey(host, serial, token);
16
253
  if (this.printers.has(key)) {
17
254
  return this.printers.get(key);
18
255
  }
@@ -23,22 +260,36 @@ class BambuClientStore {
23
260
  }
24
261
  throw new Error(`Existing Bambu client connection for ${key} failed.`);
25
262
  }
26
- const printer = new BambuClient({
263
+ const printer = new TolerantBambuClient({
27
264
  host,
28
265
  serialNumber: serial,
29
266
  accessToken: token,
30
267
  });
268
+ this.ensureInitialReportPromise(key);
269
+ printer.on("rawMessage", (_topic, payload) => {
270
+ try {
271
+ const parsed = JSON.parse(payload.toString());
272
+ const printMessage = parsed?.print;
273
+ if (printMessage && typeof printMessage === "object") {
274
+ this.updateReportSnapshot(key, printMessage);
275
+ }
276
+ }
277
+ catch {
278
+ // Ignore unrelated payloads.
279
+ }
280
+ });
281
+ printer.on("printer:dataUpdate", (data) => {
282
+ this.updateReportSnapshot(key, data);
283
+ });
31
284
  printer.on("client:connect", () => {
32
285
  this.printers.set(key, printer);
33
286
  this.initialConnectionPromises.delete(key);
34
287
  });
35
288
  printer.on("client:error", () => {
36
- this.printers.delete(key);
37
- this.initialConnectionPromises.delete(key);
289
+ this.clearPrinterState(key);
38
290
  });
39
291
  printer.on("client:disconnect", () => {
40
- this.printers.delete(key);
41
- this.initialConnectionPromises.delete(key);
292
+ this.clearPrinterState(key);
42
293
  });
43
294
  const connectPromise = printer.connect().then(() => { });
44
295
  this.initialConnectionPromises.set(key, connectPromise);
@@ -47,7 +298,7 @@ class BambuClientStore {
47
298
  return printer;
48
299
  }
49
300
  catch (error) {
50
- this.initialConnectionPromises.delete(key);
301
+ this.clearPrinterState(key);
51
302
  throw error;
52
303
  }
53
304
  }
@@ -66,6 +317,9 @@ class BambuClientStore {
66
317
  await Promise.allSettled(disconnectPromises);
67
318
  this.printers.clear();
68
319
  this.initialConnectionPromises.clear();
320
+ this.reportSnapshots.clear();
321
+ this.initialReportPromises.clear();
322
+ this.initialReportResolvers.clear();
69
323
  }
70
324
  }
71
325
  export class BambuImplementation {
@@ -94,25 +348,67 @@ export class BambuImplementation {
94
348
  }
95
349
  const gcodeBuffer = await selectedEntry.async("nodebuffer");
96
350
  const md5 = createHash("md5").update(gcodeBuffer).digest("hex");
351
+ // Project filament count: parse the gcode header line
352
+ // `; filament_colour = #FFFFFF;#FF911A80;#DCF478;#DCF478`
353
+ // This is the authoritative source -- it always reflects the slicer's
354
+ // project filament list length. We only scan the first ~32KB of the
355
+ // gcode to keep this cheap even on large plates.
356
+ let projectFilamentCount = 1;
357
+ const head = gcodeBuffer.slice(0, 32 * 1024).toString("utf8");
358
+ const colourLine = head.match(/;\s*filament_colour\s*=\s*([^\n\r]+)/i);
359
+ if (colourLine) {
360
+ projectFilamentCount = colourLine[1].split(";").filter((s) => s.trim()).length;
361
+ }
362
+ else {
363
+ // Fallback: count filament_ids header entries.
364
+ const idsLine = head.match(/;\s*filament_ids\s*=\s*([^\n\r]+)/i);
365
+ if (idsLine) {
366
+ projectFilamentCount = idsLine[1].split(";").filter((s) => s.trim()).length;
367
+ }
368
+ }
369
+ // Used filament positions: from Metadata/plate_<n>.json.filament_ids.
370
+ // These are 0-based positions into the project filament list that the
371
+ // selected plate actually consumes.
372
+ let usedFilamentPositions = [];
373
+ const plateJsonName = selectedEntry.name.replace(/\.gcode$/i, ".json");
374
+ const plateJsonEntry = zip.file(plateJsonName);
375
+ if (plateJsonEntry) {
376
+ try {
377
+ const raw = await plateJsonEntry.async("string");
378
+ const json = JSON.parse(raw);
379
+ if (Array.isArray(json.filament_ids)) {
380
+ usedFilamentPositions = json.filament_ids
381
+ .filter((n) => Number.isInteger(n))
382
+ .map((n) => n);
383
+ }
384
+ }
385
+ catch {
386
+ // tolerate malformed plate_N.json -- caller can pass amsMapping directly
387
+ }
388
+ }
389
+ if (usedFilamentPositions.length === 0)
390
+ usedFilamentPositions = [0];
97
391
  return {
98
392
  plateFileName: path.posix.basename(selectedEntry.name),
99
393
  plateInternalPath: selectedEntry.name,
100
394
  md5,
395
+ projectFilamentCount,
396
+ usedFilamentPositions,
101
397
  };
102
398
  }
103
399
  async getStatus(host, serial, token) {
104
400
  try {
105
401
  const printer = await this.getPrinter(host, serial, token);
106
402
  try {
107
- await printer.executeCommand(new PushAllCommand());
403
+ await invokeWithoutAck(printer, new PushAllCommand());
108
404
  }
109
405
  catch (error) {
110
406
  console.warn("PushAllCommand failed, continuing with cached status", error);
111
407
  }
112
- if (!printer.data || Object.keys(printer.data).length === 0) {
113
- await new Promise((resolve) => setTimeout(resolve, 1500));
114
- }
115
- const data = printer.data;
408
+ const cachedData = await this.printerStore.waitForInitialReport(host, serial, token);
409
+ const data = cachedData && Object.keys(cachedData).length > 0
410
+ ? cachedData
411
+ : printer.data;
116
412
  return {
117
413
  status: data.gcode_state || "UNKNOWN",
118
414
  connected: true,
@@ -135,7 +431,7 @@ export class BambuImplementation {
135
431
  totalLayers: data.total_layer_num || 0,
136
432
  },
137
433
  ams: data.ams || null,
138
- model: data.model || "Unknown",
434
+ model: resolveModelName(data),
139
435
  serial,
140
436
  raw: data,
141
437
  };
@@ -149,51 +445,183 @@ export class BambuImplementation {
149
445
  if (!options.filePath.toLowerCase().endsWith(".3mf")) {
150
446
  throw new Error("print3mf requires a .3mf input file.");
151
447
  }
152
- const projectMetadata = await this.resolveProjectFileMetadata(options.filePath, options.plateIndex);
153
- const remoteFileName = path.basename(options.filePath);
154
- const remoteProjectPath = `cache/${remoteFileName}`;
448
+ // Normalise remote filename: collapse double-extension artifacts like
449
+ // "Cube.gcode.3mf.gcode.3mf" -> "Cube.gcode.3mf" so firmware can identify
450
+ // the container format from the extension.
451
+ let remoteFileName = path.basename(options.filePath);
452
+ remoteFileName = remoteFileName.replace(/\.gcode\.3mf\.gcode\.3mf$/i, ".gcode.3mf");
453
+ // H2S/H2D land files at the FTP root and reference them via ftp:///<name>.
454
+ // P1/A1/X1 use /cache/<name> and file:///sdcard/cache/<name>.
455
+ const isH2 = serial.startsWith("093") || serial.startsWith("094");
456
+ const remoteProjectPath = isH2 ? remoteFileName : `cache/${remoteFileName}`;
457
+ const remoteUploadPath = isH2 ? `/${remoteFileName}` : `/cache/${remoteFileName}`;
458
+ const projectUrl = isH2
459
+ ? `ftp:///${remoteFileName}`
460
+ : `file:///sdcard/${remoteProjectPath}`;
155
461
  // Upload via basic-ftp directly (bypasses bambu-js double-path bug)
156
- await this.ftpUpload(host, token, options.filePath, `/cache/${remoteFileName}`);
462
+ await this.ftpUpload(host, token, options.filePath, remoteUploadPath);
463
+ // Pre-sliced .gcode.3mf files: routing depends on firmware generation.
464
+ // P1/A1/X1 series: project_file returns 405004002 for .gcode.3mf (firmware
465
+ // doesn't recognise the container), so use gcode_file instead.
466
+ // H2S/H2D: gcode_file is not supported; project_file works because the
467
+ // firmware can open the zip and find Metadata/plate_<n>.gcode directly.
468
+ if (options.filePath.toLowerCase().endsWith(".gcode.3mf")) {
469
+ if (!isH2) {
470
+ const printer = await this.getPrinter(host, serial, token);
471
+ await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remoteProjectPath }));
472
+ return {
473
+ status: "success",
474
+ message: `Uploaded and started gcode.3mf print: ${options.projectName}`,
475
+ remoteProjectPath,
476
+ };
477
+ }
478
+ // H2S/H2D: fall through to project_file path below
479
+ }
480
+ const projectMetadata = await this.resolveProjectFileMetadata(options.filePath, options.plateIndex);
157
481
  // Send project_file command via bambu-node MQTT (bypasses bambu-js
158
482
  // hardcoded use_ams=true and missing ams_mapping support)
159
483
  const printer = await this.getPrinter(host, serial, token);
160
484
  const md5 = options.md5 ?? projectMetadata.md5;
161
- // Build AMS mapping per OpenBambuAPI spec: 5-element array
162
- // [-1,-1,-1,-1,0] means slot 0 only; pad unused slots with -1
163
- let amsMapping;
485
+ // Build AMS mapping.
486
+ //
487
+ // Convention: position = project-level filament index, value = absolute
488
+ // tray index (0-3 = AMS 0 trays, 4-7 = AMS 1, 8-11 = AMS 2, 128+ = AMS-HT,
489
+ // 254 = external spool, -1 = unused). Required on AMS-equipped printers
490
+ // even when you think "no AMS" -- firmware looks up the mapping table
491
+ // whenever the 3MF declares filaments, and a missing/invalid mapping
492
+ // fails with 0700-8012-032015 "Failed to get AMS mapping table".
493
+ //
494
+ // For H2-series the array length MUST equal the project-level filament
495
+ // count declared by the slicer (parsed from the gcode header's
496
+ // `filament_colour` list). For P1/A1/X1 we pad to length 5 per the
497
+ // historical bambu-js behavior.
498
+ //
499
+ // Caller ergonomics: callers typically know only "I want to pull this
500
+ // print's filaments from these AMS slots" in the order the plate uses
501
+ // them. We expose `amsSlots` for that -- one entry per position in
502
+ // `plate_N.json.filament_ids` -- and expand to a full project-level
503
+ // array here. `amsMapping` is the raw escape hatch (takes precedence
504
+ // when both are supplied).
505
+ const validateTrayValue = (v, label) => {
506
+ if (!Number.isInteger(v) ||
507
+ v < -1 ||
508
+ (v > 15 && v < 128) ||
509
+ v > 254) {
510
+ throw new Error(`${label} values must be integers in [-1, 15] (absolute tray) or 128-254 (HT/external); got ${v}`);
511
+ }
512
+ };
513
+ let baseMapping;
164
514
  if (options.amsMapping && options.amsMapping.length > 0) {
165
- amsMapping = Array.from({ length: 5 }, (_, i) => i < options.amsMapping.length ? options.amsMapping[i] : -1);
515
+ for (const v of options.amsMapping)
516
+ validateTrayValue(v, "ams_mapping");
517
+ baseMapping = options.amsMapping.slice();
518
+ }
519
+ else if (options.amsSlots && options.amsSlots.length > 0) {
520
+ for (const v of options.amsSlots)
521
+ validateTrayValue(v, "amsSlots");
522
+ const positions = projectMetadata.usedFilamentPositions;
523
+ if (options.amsSlots.length !== positions.length) {
524
+ throw new Error(`amsSlots length ${options.amsSlots.length} does not match used filament count ${positions.length} (plate uses positions ${JSON.stringify(positions)}). Provide one tray per used filament, or use amsMapping for a raw project-level array.`);
525
+ }
526
+ const projectLen = Math.max(projectMetadata.projectFilamentCount, ...positions.map((p) => p + 1));
527
+ baseMapping = Array(projectLen).fill(-1);
528
+ positions.forEach((pos, i) => {
529
+ baseMapping[pos] = options.amsSlots[i];
530
+ });
531
+ }
532
+ else {
533
+ if (isH2 && projectMetadata.usedFilamentPositions.length > 0) {
534
+ throw new Error(`H2 project_file requires amsSlots or amsMapping for sliced files with declared filaments. Plate uses project filament positions ${JSON.stringify(projectMetadata.usedFilamentPositions)}.`);
535
+ }
536
+ const positions = projectMetadata.usedFilamentPositions;
537
+ const projectLen = Math.max(projectMetadata.projectFilamentCount, ...positions.map((p) => p + 1), 1);
538
+ baseMapping = Array(projectLen).fill(-1);
539
+ positions.forEach((pos, i) => {
540
+ baseMapping[pos] = i;
541
+ });
542
+ }
543
+ let amsMapping;
544
+ let amsMapping2;
545
+ if (isH2) {
546
+ const projLen = Math.max(projectMetadata.projectFilamentCount, baseMapping.length, 1);
547
+ amsMapping = Array.from({ length: projLen }, (_, i) => i < baseMapping.length ? baseMapping[i] : -1);
548
+ amsMapping2 = amsMapping.map((v) => {
549
+ if (v < 0 || v === 255)
550
+ return { ams_id: 255, slot_id: 255 };
551
+ if (v === 254)
552
+ return { ams_id: 254, slot_id: 254 };
553
+ if (v >= 128)
554
+ return { ams_id: 128, slot_id: v - 128 };
555
+ return { ams_id: Math.floor(v / 4), slot_id: v % 4 };
556
+ });
166
557
  }
167
558
  else {
168
- amsMapping = [-1, -1, -1, -1, 0];
559
+ amsMapping = Array.from({ length: 5 }, (_, i) => i < baseMapping.length ? baseMapping[i] : -1);
560
+ amsMapping2 = [];
561
+ }
562
+ const b = (v) => (v ? 1 : 0);
563
+ let projectFileCmd;
564
+ if (isH2) {
565
+ const submissionId = String(Date.now() & 0x7fffffff);
566
+ projectFileCmd = {
567
+ print: {
568
+ sequence_id: "0",
569
+ command: "project_file",
570
+ param: `Metadata/${projectMetadata.plateFileName}`,
571
+ url: projectUrl,
572
+ file: remoteFileName,
573
+ md5,
574
+ bed_type: options.bedType || "auto",
575
+ timelapse: b(options.timelapse),
576
+ bed_leveling: b(options.bedLeveling ?? true),
577
+ auto_bed_leveling: 1,
578
+ flow_cali: b(options.flowCalibration ?? false),
579
+ vibration_cali: b(options.vibrationCalibration ?? true),
580
+ layer_inspect: b(options.layerInspect ?? false),
581
+ use_ams: options.useAMS !== false,
582
+ cfg: "0",
583
+ extrude_cali_flag: 0,
584
+ extrude_cali_manual_mode: 0,
585
+ nozzle_offset_cali: 2,
586
+ subtask_name: remoteFileName.replace(/\.3mf$/i, ""),
587
+ profile_id: "0",
588
+ project_id: submissionId,
589
+ subtask_id: submissionId,
590
+ task_id: submissionId,
591
+ ams_mapping: amsMapping,
592
+ ams_mapping2: amsMapping2,
593
+ },
594
+ };
595
+ }
596
+ else {
597
+ projectFileCmd = {
598
+ print: {
599
+ command: "project_file",
600
+ param: `Metadata/${projectMetadata.plateFileName}`,
601
+ url: projectUrl,
602
+ subtask_name: options.projectName,
603
+ md5,
604
+ flow_cali: options.flowCalibration ?? true,
605
+ layer_inspect: options.layerInspect ?? true,
606
+ vibration_cali: options.vibrationCalibration ?? true,
607
+ bed_leveling: options.bedLeveling ?? true,
608
+ bed_type: options.bedType || "textured_plate",
609
+ timelapse: options.timelapse ?? false,
610
+ use_ams: options.useAMS !== false,
611
+ ams_mapping: amsMapping,
612
+ profile_id: "0",
613
+ project_id: "0",
614
+ sequence_id: "0",
615
+ subtask_id: "0",
616
+ task_id: "0",
617
+ },
618
+ };
169
619
  }
170
- const projectFileCmd = {
171
- print: {
172
- command: "project_file",
173
- param: `Metadata/${projectMetadata.plateFileName}`,
174
- url: `ftp://${remoteFileName}`,
175
- subtask_name: options.projectName,
176
- md5,
177
- flow_cali: options.flowCalibration ?? true,
178
- layer_inspect: options.layerInspect ?? true,
179
- vibration_cali: options.vibrationCalibration ?? true,
180
- bed_leveling: options.bedLeveling ?? true,
181
- bed_type: options.bedType || "textured_plate",
182
- timelapse: options.timelapse ?? false,
183
- use_ams: options.useAMS !== false,
184
- ams_mapping: amsMapping,
185
- profile_id: "0",
186
- project_id: "0",
187
- sequence_id: "0",
188
- subtask_id: "0",
189
- task_id: "0",
190
- },
191
- };
192
620
  await printer.publish(projectFileCmd);
193
621
  await new Promise((resolve) => setTimeout(resolve, 300));
194
622
  return {
195
623
  status: "success",
196
- message: `Uploaded 3MF and sent project_file print command: ${options.projectName}`,
624
+ message: `Uploaded and started 3MF print: ${options.projectName}`,
197
625
  remoteProjectPath,
198
626
  plateFile: projectMetadata.plateFileName,
199
627
  platePath: projectMetadata.plateInternalPath,
@@ -204,13 +632,118 @@ export class BambuImplementation {
204
632
  async cancelJob(host, serial, token) {
205
633
  const printer = await this.getPrinter(host, serial, token);
206
634
  try {
207
- await printer.executeCommand(new UpdateStateCommand({ state: "stop" }));
635
+ await invokeWithoutAck(printer, new UpdateStateCommand({ state: "stop" }));
208
636
  return { status: "success", message: "Cancel command sent successfully." };
209
637
  }
210
638
  catch (error) {
211
639
  throw new Error(`Failed to cancel print: ${error.message}`);
212
640
  }
213
641
  }
642
+ async pauseJob(host, serial, token) {
643
+ const printer = await this.getPrinter(host, serial, token);
644
+ try {
645
+ await invokeWithoutAck(printer, new UpdateStateCommand({ state: "pause" }));
646
+ return { status: "success", message: "Pause command sent successfully." };
647
+ }
648
+ catch (error) {
649
+ throw new Error(`Failed to pause print: ${error.message}`);
650
+ }
651
+ }
652
+ async resumeJob(host, serial, token) {
653
+ const printer = await this.getPrinter(host, serial, token);
654
+ try {
655
+ await invokeWithoutAck(printer, new UpdateStateCommand({ state: "resume" }));
656
+ return { status: "success", message: "Resume command sent successfully." };
657
+ }
658
+ catch (error) {
659
+ throw new Error(`Failed to resume print: ${error.message}`);
660
+ }
661
+ }
662
+ async clearHmsErrors(host, serial, token) {
663
+ const printer = await this.getPrinter(host, serial, token);
664
+ await printer.publish({
665
+ print: {
666
+ command: "clean_print_error",
667
+ sequence_id: "0",
668
+ },
669
+ });
670
+ await sleep(COMMAND_SETTLE_MS);
671
+ return { status: "success", message: "HMS clear command sent." };
672
+ }
673
+ async setPrintSpeed(host, serial, token, speedMode) {
674
+ const printer = await this.getPrinter(host, serial, token);
675
+ const normalized = typeof speedMode === "number" ? String(Math.trunc(speedMode)) : speedMode.trim().toLowerCase();
676
+ const mode = normalized === "silent" ? 1 :
677
+ normalized === "standard" ? 2 :
678
+ normalized === "sport" ? 3 :
679
+ normalized === "ludicrous" ? 4 :
680
+ Number(normalized);
681
+ if (!Number.isInteger(mode) || mode < 1 || mode > 4) {
682
+ throw new Error("Print speed mode must be one of: silent, standard, sport, ludicrous, 1, 2, 3, 4.");
683
+ }
684
+ await printer.publish({
685
+ print: {
686
+ command: "print_speed",
687
+ param: String(mode),
688
+ sequence_id: "0",
689
+ },
690
+ });
691
+ await sleep(COMMAND_SETTLE_MS);
692
+ const names = ["", "silent", "standard", "sport", "ludicrous"];
693
+ return {
694
+ status: "success",
695
+ message: `Print speed command sent for ${names[mode]}.`,
696
+ mode,
697
+ label: names[mode],
698
+ };
699
+ }
700
+ async setAirductMode(host, serial, token, mode) {
701
+ const printer = await this.getPrinter(host, serial, token);
702
+ const normalizedMode = mode.trim().toLowerCase();
703
+ if (normalizedMode !== "cooling" && normalizedMode !== "heating") {
704
+ throw new Error("Airduct mode must be one of: cooling, heating.");
705
+ }
706
+ await printer.publish({
707
+ print: {
708
+ command: "set_airduct",
709
+ modeId: normalizedMode === "cooling" ? 0 : 1,
710
+ submode: -1,
711
+ sequence_id: "0",
712
+ },
713
+ });
714
+ await sleep(COMMAND_SETTLE_MS);
715
+ return {
716
+ status: "success",
717
+ message: `Airduct mode command sent for ${normalizedMode}.`,
718
+ mode: normalizedMode,
719
+ };
720
+ }
721
+ async rereadAmsRfid(host, serial, token, amsId, slotId) {
722
+ const printer = await this.getPrinter(host, serial, token);
723
+ const normalizedAmsId = Math.trunc(amsId);
724
+ const normalizedSlotId = Math.trunc(slotId);
725
+ if (!Number.isInteger(normalizedAmsId) || normalizedAmsId < 0 || normalizedAmsId > 3) {
726
+ throw new Error("ams_id must be an integer from 0 to 3.");
727
+ }
728
+ if (!Number.isInteger(normalizedSlotId) || normalizedSlotId < 0 || normalizedSlotId > 3) {
729
+ throw new Error("slot_id must be an integer from 0 to 3.");
730
+ }
731
+ await printer.publish({
732
+ print: {
733
+ command: "ams_get_rfid",
734
+ ams_id: normalizedAmsId,
735
+ slot_id: normalizedSlotId,
736
+ sequence_id: "0",
737
+ },
738
+ });
739
+ await sleep(COMMAND_SETTLE_MS);
740
+ return {
741
+ status: "success",
742
+ message: `AMS RFID re-read command sent for AMS ${normalizedAmsId} slot ${normalizedSlotId}.`,
743
+ ams_id: normalizedAmsId,
744
+ slot_id: normalizedSlotId,
745
+ };
746
+ }
214
747
  async setTemperature(host, serial, token, component, temperature) {
215
748
  const printer = await this.getPrinter(host, serial, token);
216
749
  const normalizedComponent = component.toLowerCase();
@@ -231,13 +764,110 @@ export class BambuImplementation {
231
764
  else {
232
765
  throw new Error(`Unsupported temperature component: ${component}. Use one of: bed, nozzle, extruder.`);
233
766
  }
234
- await printer.executeCommand(new GCodeLineCommand({ gcodes: [gcode] }));
767
+ await invokeWithoutAck(printer, new GCodeLineCommand({ gcodes: [gcode] }));
235
768
  return {
236
769
  status: "success",
237
770
  message: `Temperature command sent for ${normalizedComponent}.`,
238
771
  command: gcode,
239
772
  };
240
773
  }
774
+ async setFanSpeed(host, serial, token, fan, speed) {
775
+ const printer = await this.getPrinter(host, serial, token);
776
+ const normalizedFan = typeof fan === "number" ? fan : fan.trim().toLowerCase();
777
+ const fanId = normalizedFan === 1 || normalizedFan === "1" || normalizedFan === "part" || normalizedFan === "part_cooling"
778
+ ? 1
779
+ : normalizedFan === 2 || normalizedFan === "2" || normalizedFan === "aux" || normalizedFan === "auxiliary"
780
+ ? 2
781
+ : normalizedFan === 3 || normalizedFan === "3" || normalizedFan === "chamber"
782
+ ? 3
783
+ : null;
784
+ if (fanId === null) {
785
+ throw new Error("Unsupported fan. Use one of: part, auxiliary, chamber, 1, 2, 3.");
786
+ }
787
+ const targetSpeed = Math.round(speed);
788
+ if (targetSpeed < 0 || targetSpeed > 100) {
789
+ throw new Error("Fan speed must be between 0 and 100 percent.");
790
+ }
791
+ await invokeWithoutAck(printer, new UpdateFanCommand({ fan: fanId, speed: targetSpeed }));
792
+ return {
793
+ status: "success",
794
+ message: `Fan speed command sent for fan ${fanId}.`,
795
+ fan: fanId,
796
+ speed: targetSpeed,
797
+ };
798
+ }
799
+ async setLight(host, serial, token, light, mode) {
800
+ const printer = await this.getPrinter(host, serial, token);
801
+ const normalizedLight = light.trim();
802
+ const normalizedMode = mode.trim().toLowerCase();
803
+ const validModes = new Set(["on", "off", "flashing"]);
804
+ if (!normalizedLight) {
805
+ throw new Error("Light node is required, for example: chamber_light.");
806
+ }
807
+ if (!validModes.has(normalizedMode)) {
808
+ throw new Error("Light mode must be one of: on, off, flashing.");
809
+ }
810
+ await invokeWithoutAck(printer, new UpdateLightCommand({
811
+ light: normalizedLight,
812
+ mode: normalizedMode,
813
+ }));
814
+ return {
815
+ status: "success",
816
+ message: `Light command sent for ${normalizedLight}.`,
817
+ light: normalizedLight,
818
+ mode: normalizedMode,
819
+ };
820
+ }
821
+ async setAmsDrying(host, serial, token, action, amsId) {
822
+ const printer = await this.getPrinter(host, serial, token);
823
+ const normalizedAction = action.trim().toLowerCase();
824
+ if (normalizedAction !== "start" && normalizedAction !== "stop") {
825
+ throw new Error("AMS drying action must be one of: start, stop.");
826
+ }
827
+ const normalizedAmsId = Math.trunc(amsId);
828
+ if (!Number.isInteger(normalizedAmsId) || normalizedAmsId < 0 || normalizedAmsId > 3) {
829
+ throw new Error("ams_id must be an integer from 0 to 3.");
830
+ }
831
+ const param = normalizedAction === "start" ? "start_drying" : "stop_drying";
832
+ await printer.publish({
833
+ print: {
834
+ command: "ams_control",
835
+ ams_id: normalizedAmsId,
836
+ param,
837
+ sequence_id: "0",
838
+ },
839
+ });
840
+ await sleep(COMMAND_SETTLE_MS);
841
+ const label = normalizedAction === "start" ? "started" : "stopped";
842
+ return {
843
+ status: "success",
844
+ message: `AMS drying ${label} for AMS ${normalizedAmsId}.`,
845
+ action: normalizedAction,
846
+ ams_id: normalizedAmsId,
847
+ };
848
+ }
849
+ async skipObjects(host, serial, token, objectIds) {
850
+ const printer = await this.getPrinter(host, serial, token);
851
+ const normalizedObjectIds = objectIds
852
+ .map((id) => Math.trunc(id))
853
+ .filter((id) => Number.isInteger(id) && id >= 0);
854
+ if (normalizedObjectIds.length === 0) {
855
+ throw new Error("At least one non-negative object id is required.");
856
+ }
857
+ await printer.publish({
858
+ print: {
859
+ sequence_id: "0",
860
+ command: "skip_objects",
861
+ obj_list: normalizedObjectIds,
862
+ },
863
+ });
864
+ await sleep(COMMAND_SETTLE_MS);
865
+ return {
866
+ status: "success",
867
+ message: "Skip objects command sent.",
868
+ object_ids: normalizedObjectIds,
869
+ };
870
+ }
241
871
  async getFiles(host, serial, token) {
242
872
  const printer = new BambuPrinter(host, serial, token);
243
873
  const directories = ["cache", "timelapse", "logs"];
@@ -302,7 +932,8 @@ export class BambuImplementation {
302
932
  return response;
303
933
  }
304
934
  async startJob(host, serial, token, filename) {
305
- if (filename.toLowerCase().endsWith(".3mf")) {
935
+ const lower = filename.toLowerCase();
936
+ if (lower.endsWith(".3mf") && !lower.endsWith(".gcode.3mf")) {
306
937
  throw new Error("Use print_3mf for .3mf project files.");
307
938
  }
308
939
  const printer = await this.getPrinter(host, serial, token);
@@ -310,13 +941,314 @@ export class BambuImplementation {
310
941
  const remoteFile = normalizedFileName.includes("/")
311
942
  ? normalizedFileName
312
943
  : `cache/${normalizedFileName}`;
313
- await printer.executeCommand(new GCodeFileCommand({ fileName: remoteFile }));
944
+ await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remoteFile }));
314
945
  return {
315
946
  status: "success",
316
947
  message: `Start command sent for ${remoteFile}.`,
317
948
  file: remoteFile,
318
949
  };
319
950
  }
951
+ /**
952
+ * Capture a single JPEG frame from the printer's chamber camera.
953
+ *
954
+ * Protocol per https://github.com/Doridian/OpenBambuAPI/blob/main/video.md
955
+ *
956
+ * Connect TLS to <host>:6000 (self-signed cert -- skip verification).
957
+ * Send an 80-byte auth packet:
958
+ * [0..4] uint32 LE payload size = 0x40 (64)
959
+ * [4..8] uint32 LE type = 0x3000
960
+ * [8..12] uint32 LE flags = 0
961
+ * [12..16] uint32 LE 0
962
+ * [16..48] "bblp" + null padding to 32 bytes
963
+ * [48..80] access token + null padding to 32 bytes
964
+ *
965
+ * The server then streams frames as repeating:
966
+ * [0..4] uint32 LE payload size
967
+ * [4..8] uint32 LE itrack (0)
968
+ * [8..12] uint32 LE flags (1)
969
+ * [12..16] uint32 LE 0
970
+ * [16..16+payloadSize] JPEG (FF D8 ... FF D9)
971
+ *
972
+ * Verified models per upstream docs: A1, A1 mini, P1S, P1P. X1/X1C/X1E
973
+ * and P2S use RTSP on port 322 instead -- not implemented yet. H2/H2S/H2D
974
+ * are not documented; we fail fast rather than guess at the protocol.
975
+ *
976
+ * Read-only; no confirm gate. Default 8s timeout for cold-start latency.
977
+ */
978
+ async cameraSnapshot(host, _serial, token, options = {}) {
979
+ const timeoutMs = options.timeoutMs ?? 8000;
980
+ const model = (options.bambuModel ?? "").toLowerCase();
981
+ // P1/A1 series still use the proprietary TCP-on-6000 framed JPEG path
982
+ // (per https://github.com/Doridian/OpenBambuAPI/blob/main/video.md).
983
+ const TCP_CAMERA_MODELS = new Set(["a1", "a1mini", "p1s", "p1p"]);
984
+ // X1, P2S, AND H2 (H2S/H2D/H2C) all use RTSP on port 322. The
985
+ // OpenBambuAPI doc only mentions X1/P2S, but the HA bambulab
986
+ // integration's models.py shows the printer reports its own
987
+ // `ipcam.rtsp_url` for these models, and Parker (H2S) rejects the
988
+ // A1/P1 80-byte auth packet on port 6000 (verified 2026-04-27 --
989
+ // see PROGRESS.md "H2 probe results").
990
+ const RTSP_MODELS = new Set([
991
+ "x1", "x1c", "x1carbon", "x1e", "p2s",
992
+ "h2", "h2s", "h2d", "h2c", "h2dpro",
993
+ ]);
994
+ if (!model) {
995
+ throw new Error("camera_snapshot requires bambu_model or BAMBU_MODEL so it can choose the correct Bambu camera protocol.");
996
+ }
997
+ if (RTSP_MODELS.has(model)) {
998
+ const jpeg = await this.fetchRtspCameraFrame(host, token, timeoutMs, options.ffmpegPath);
999
+ const result = {
1000
+ status: "success",
1001
+ format: "image/jpeg",
1002
+ sizeBytes: jpeg.length,
1003
+ base64: jpeg.toString("base64"),
1004
+ transport: "rtsps-322",
1005
+ };
1006
+ if (options.savePath) {
1007
+ const fsSync = await import("node:fs");
1008
+ fsSync.writeFileSync(options.savePath, jpeg);
1009
+ result.savedTo = options.savePath;
1010
+ }
1011
+ return result;
1012
+ }
1013
+ if (model && !TCP_CAMERA_MODELS.has(model)) {
1014
+ throw new Error(`camera_snapshot: model "${model}" is not a known Bambu Lab printer model. Supported: ${[...TCP_CAMERA_MODELS, ...RTSP_MODELS].sort().join(", ")}`);
1015
+ }
1016
+ const jpeg = await this.fetchTcpCameraFrame(host, token, timeoutMs);
1017
+ const result = {
1018
+ status: "success",
1019
+ format: "image/jpeg",
1020
+ sizeBytes: jpeg.length,
1021
+ base64: jpeg.toString("base64"),
1022
+ transport: "tcp-6000",
1023
+ };
1024
+ if (options.savePath) {
1025
+ const fsSync = await import("node:fs");
1026
+ fsSync.writeFileSync(options.savePath, jpeg);
1027
+ result.savedTo = options.savePath;
1028
+ }
1029
+ return result;
1030
+ }
1031
+ /**
1032
+ * Pull a single JPEG frame from the printer's RTSP/RTSPS stream using
1033
+ * ffmpeg. Used for X1, P2S, and H2 series.
1034
+ *
1035
+ * URL pattern verified against HA bambulab's models.py example:
1036
+ * rtsps://bblp:<access_code>@<host>:322/streaming/live/1
1037
+ *
1038
+ * ffmpeg invocation:
1039
+ * ffmpeg -rtsp_transport tcp -i <url> -frames:v 1 -f image2 -c:v mjpeg -y <out>
1040
+ *
1041
+ * -rtsp_transport tcp avoids UDP NAT/firewall issues. -frames:v 1
1042
+ * makes ffmpeg exit as soon as one frame lands. -y overwrites the temp
1043
+ * file. The Bambu printer presents a self-signed cert; ffmpeg's TLS
1044
+ * layer accepts that by default (no host verification).
1045
+ */
1046
+ async fetchRtspCameraFrame(host, token, timeoutMs, ffmpegPath) {
1047
+ const fsSync = await import("node:fs");
1048
+ const os = await import("node:os");
1049
+ const pathMod = await import("node:path");
1050
+ const { spawn } = await import("node:child_process");
1051
+ const tmpOut = pathMod.join(os.tmpdir(), `bambu-snap-${Date.now()}-${Math.random().toString(16).slice(2)}.jpg`);
1052
+ const url = `rtsps://bblp:${encodeURIComponent(token)}@${host}:322/streaming/live/1`;
1053
+ const bin = ffmpegPath ?? "ffmpeg";
1054
+ // Note: ffmpeg's `-stimeout` was removed in 8.0 and renamed across the
1055
+ // 5.x/6.x line; we rely on the outer kill timer instead so we don't
1056
+ // have to detect ffmpeg version. -rtsp_transport tcp avoids UDP NAT
1057
+ // headaches; -frames:v 1 makes ffmpeg exit on first frame.
1058
+ const args = [
1059
+ "-rtsp_transport", "tcp",
1060
+ "-i", url,
1061
+ "-frames:v", "1",
1062
+ "-f", "image2",
1063
+ "-c:v", "mjpeg",
1064
+ "-y",
1065
+ "-loglevel", "error",
1066
+ tmpOut,
1067
+ ];
1068
+ return new Promise((resolve, reject) => {
1069
+ let stderr = "";
1070
+ const proc = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
1071
+ const killTimer = setTimeout(() => {
1072
+ try {
1073
+ proc.kill("SIGKILL");
1074
+ }
1075
+ catch { /* ignore */ }
1076
+ reject(new Error(`camera_snapshot: ffmpeg timed out after ${timeoutMs}ms`));
1077
+ }, timeoutMs + 1000);
1078
+ proc.stderr.on("data", (d) => { stderr += d.toString(); });
1079
+ proc.on("error", (err) => {
1080
+ clearTimeout(killTimer);
1081
+ if (err.code === "ENOENT") {
1082
+ reject(new Error(`camera_snapshot: ffmpeg binary not found at "${bin}". Install with \`brew install ffmpeg\` or pass ffmpegPath.`));
1083
+ }
1084
+ else {
1085
+ reject(err);
1086
+ }
1087
+ });
1088
+ proc.on("close", (code) => {
1089
+ clearTimeout(killTimer);
1090
+ if (code !== 0) {
1091
+ // Strip access code from error messages so we don't leak credentials.
1092
+ const safeStderr = stderr.split(token).join("<token-redacted>").trim();
1093
+ reject(new Error(`camera_snapshot: ffmpeg exited ${code}. stderr: ${safeStderr.slice(-1000)}`));
1094
+ try {
1095
+ fsSync.unlinkSync(tmpOut);
1096
+ }
1097
+ catch { /* ignore */ }
1098
+ return;
1099
+ }
1100
+ try {
1101
+ const jpeg = fsSync.readFileSync(tmpOut);
1102
+ fsSync.unlinkSync(tmpOut);
1103
+ if (jpeg.length < 4 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) {
1104
+ reject(new Error("camera_snapshot: ffmpeg produced output that does not start with JPEG SOI"));
1105
+ return;
1106
+ }
1107
+ resolve(jpeg);
1108
+ }
1109
+ catch (err) {
1110
+ reject(err);
1111
+ }
1112
+ });
1113
+ });
1114
+ }
1115
+ /**
1116
+ * Open the TLS-on-6000 socket, send the 80-byte auth packet, and read
1117
+ * a single complete JPEG frame. Returns the JPEG bytes.
1118
+ */
1119
+ async fetchTcpCameraFrame(host, token, timeoutMs) {
1120
+ const tls = await import("node:tls");
1121
+ const auth = Buffer.alloc(80, 0);
1122
+ auth.writeUInt32LE(0x40, 0); // payload size
1123
+ auth.writeUInt32LE(0x3000, 4); // type
1124
+ // flags=0, reserved=0 are already zero from Buffer.alloc.
1125
+ auth.write("bblp", 16, 4, "ascii");
1126
+ auth.write(token, 48, Math.min(32, Buffer.byteLength(token, "ascii")), "ascii");
1127
+ return new Promise((resolve, reject) => {
1128
+ const chunks = [];
1129
+ let totalLen = 0;
1130
+ const FRAME_HEADER_BYTES = 16;
1131
+ let payloadSize = null;
1132
+ let settled = false;
1133
+ const finish = (err, jpeg) => {
1134
+ if (settled)
1135
+ return;
1136
+ settled = true;
1137
+ clearTimeout(timer);
1138
+ socket.destroy();
1139
+ if (err)
1140
+ reject(err);
1141
+ else if (jpeg)
1142
+ resolve(jpeg);
1143
+ else
1144
+ reject(new Error("camera_snapshot: ended without jpeg payload"));
1145
+ };
1146
+ const timer = setTimeout(() => finish(new Error(`camera_snapshot: timed out after ${timeoutMs}ms`)), timeoutMs);
1147
+ const socket = tls.connect({
1148
+ host,
1149
+ port: 6000,
1150
+ rejectUnauthorized: false,
1151
+ // The printer uses TLS for confidentiality but presents a self-signed cert.
1152
+ // Same trust posture as the FTPS path (basic-ftp with rejectUnauthorized: false).
1153
+ }, () => {
1154
+ socket.write(auth);
1155
+ });
1156
+ socket.on("data", (data) => {
1157
+ chunks.push(data);
1158
+ totalLen += data.length;
1159
+ if (payloadSize === null && totalLen >= FRAME_HEADER_BYTES) {
1160
+ const merged = Buffer.concat(chunks, totalLen);
1161
+ payloadSize = merged.readUInt32LE(0);
1162
+ if (payloadSize <= 0 || payloadSize > 5000000) {
1163
+ finish(new Error(`camera_snapshot: unreasonable payload size ${payloadSize} from header; auth likely failed.`));
1164
+ return;
1165
+ }
1166
+ // Reset chunk list to remaining bytes after the header.
1167
+ const remainder = merged.subarray(FRAME_HEADER_BYTES);
1168
+ chunks.length = 0;
1169
+ chunks.push(remainder);
1170
+ totalLen = remainder.length;
1171
+ }
1172
+ if (payloadSize !== null && totalLen >= payloadSize) {
1173
+ const merged = Buffer.concat(chunks, totalLen);
1174
+ const jpeg = merged.subarray(0, payloadSize);
1175
+ if (jpeg[0] !== 0xff || jpeg[1] !== 0xd8) {
1176
+ finish(new Error(`camera_snapshot: payload does not start with JPEG SOI (FF D8); got ${jpeg[0].toString(16)} ${jpeg[1].toString(16)}.`));
1177
+ return;
1178
+ }
1179
+ finish(null, jpeg);
1180
+ }
1181
+ });
1182
+ socket.on("error", (err) => finish(err));
1183
+ socket.on("end", () => finish(new Error("camera_snapshot: connection ended before a full JPEG frame arrived")));
1184
+ });
1185
+ }
1186
+ /**
1187
+ * Delete a single file from the printer's SD card via FTPS.
1188
+ *
1189
+ * Destructive. Caller MUST set confirm=true; otherwise we return without
1190
+ * touching the printer. Path is normalized the same way uploadFile()
1191
+ * normalizes -- if the caller passes a bare filename, we look in cache/.
1192
+ * Path traversal (`..`) is rejected.
1193
+ *
1194
+ * Only the printer-managed directories (cache/, timelapse/, logs/) are
1195
+ * accepted as parents to avoid letting an agent wander further into the
1196
+ * filesystem than expected.
1197
+ */
1198
+ async deleteFile(host, _serial, token, filename, confirm) {
1199
+ if (confirm !== true) {
1200
+ return {
1201
+ status: "skipped",
1202
+ deleted: false,
1203
+ remotePath: filename,
1204
+ message: "delete_printer_file requires confirm:true. No FTP request was made.",
1205
+ };
1206
+ }
1207
+ const normalizedFileName = filename.replace(/^\/+/, "");
1208
+ if (normalizedFileName.length === 0) {
1209
+ throw new Error("delete_printer_file: filename is required.");
1210
+ }
1211
+ if (normalizedFileName.split("/").some((seg) => seg === "..")) {
1212
+ throw new Error(`delete_printer_file: path traversal segments are not allowed (got "${filename}").`);
1213
+ }
1214
+ const remotePath = normalizedFileName.includes("/")
1215
+ ? normalizedFileName
1216
+ : `cache/${normalizedFileName}`;
1217
+ const topDir = remotePath.split("/")[0];
1218
+ const ALLOWED_DIRS = new Set(["cache", "timelapse", "logs"]);
1219
+ if (!ALLOWED_DIRS.has(topDir)) {
1220
+ throw new Error(`delete_printer_file: refusing to delete outside cache/, timelapse/, logs/. Got "${remotePath}".`);
1221
+ }
1222
+ await this.ftpDelete(host, token, `/${remotePath}`);
1223
+ return {
1224
+ status: "success",
1225
+ deleted: true,
1226
+ remotePath,
1227
+ };
1228
+ }
1229
+ /**
1230
+ * Delete a single remote file via FTPS, using basic-ftp directly so we
1231
+ * get the same TLS-session-ticket handshake as ftpUpload().
1232
+ */
1233
+ async ftpDelete(host, token, remotePath) {
1234
+ const client = new FTPClient(15000);
1235
+ try {
1236
+ await client.access({
1237
+ host,
1238
+ port: 990,
1239
+ user: "bblp",
1240
+ password: token,
1241
+ secure: "implicit",
1242
+ secureOptions: ftpsSecureOptions(),
1243
+ });
1244
+ await this.waitForTlsSession(client);
1245
+ const absoluteRemote = remotePath.startsWith("/") ? remotePath : `/${remotePath}`;
1246
+ await client.remove(absoluteRemote);
1247
+ }
1248
+ finally {
1249
+ client.close();
1250
+ }
1251
+ }
320
1252
  /**
321
1253
  * Upload a file to the printer via FTP using basic-ftp directly.
322
1254
  * Bypasses bambu-js's sendFile which has a double-path bug (ensureDir CDs
@@ -324,7 +1256,7 @@ export class BambuImplementation {
324
1256
  * again, resulting in e.g. /cache/cache/file.3mf).
325
1257
  */
326
1258
  async ftpUpload(host, token, localPath, remotePath) {
327
- const client = new FTPClient(30000);
1259
+ const client = new FTPClient(15000);
328
1260
  try {
329
1261
  await client.access({
330
1262
  host,
@@ -332,8 +1264,14 @@ export class BambuImplementation {
332
1264
  user: "bblp",
333
1265
  password: token,
334
1266
  secure: "implicit",
335
- secureOptions: { rejectUnauthorized: false },
1267
+ secureOptions: ftpsSecureOptions(),
336
1268
  });
1269
+ // With TLS 1.3 the session ticket arrives asynchronously; basic-ftp calls
1270
+ // getSession() when opening the data channel and gets undefined if the
1271
+ // ticket hasn't arrived yet, causing a fresh TLS negotiation that Bambu
1272
+ // printers reject. Wait for the session ticket before proceeding.
1273
+ await this.waitForTlsSession(client);
1274
+ // Use absolute path to avoid CWD side-effects
337
1275
  const absoluteRemote = remotePath.startsWith("/") ? remotePath : `/${remotePath}`;
338
1276
  const fileData = await fs.readFile(localPath);
339
1277
  await client.uploadFrom(Readable.from(fileData), absoluteRemote);
@@ -342,6 +1280,20 @@ export class BambuImplementation {
342
1280
  client.close();
343
1281
  }
344
1282
  }
1283
+ async waitForTlsSession(ftpClient) {
1284
+ const socket = ftpClient.ftp?.socket;
1285
+ if (!socket || typeof socket.getSession !== "function")
1286
+ return;
1287
+ if (socket.getSession())
1288
+ return;
1289
+ await new Promise((resolve) => {
1290
+ const timeout = setTimeout(resolve, 1000);
1291
+ socket.once("session", () => {
1292
+ clearTimeout(timeout);
1293
+ resolve();
1294
+ });
1295
+ });
1296
+ }
345
1297
  async disconnectAll() {
346
1298
  await this.printerStore.disconnectAll();
347
1299
  }