bambu-printer-mcp 1.1.47 → 1.1.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +116 -2
- package/dist/blender-mcp-bridge.d.ts +15 -0
- package/dist/blender-mcp-bridge.js +21 -3
- package/dist/counterpart/info.d.ts +10 -0
- package/dist/counterpart/info.js +34 -0
- package/dist/counterpart/make-3mf.d.ts +16 -0
- package/dist/counterpart/make-3mf.js +219 -0
- package/dist/counterpart/progress.d.ts +28 -0
- package/dist/counterpart/progress.js +254 -0
- package/dist/counterpart/schemas.d.ts +322 -0
- package/dist/counterpart/schemas.js +124 -0
- package/dist/fusion-mcp-bridge.d.ts +182 -0
- package/dist/fusion-mcp-bridge.js +557 -0
- package/dist/index.js +192 -12
- package/dist/printers/bambu-stages.d.ts +7 -0
- package/dist/printers/bambu-stages.js +89 -0
- package/dist/printers/bambu.d.ts +76 -4
- package/dist/printers/bambu.js +297 -37
- package/dist/printers/camera-models.d.ts +7 -0
- package/dist/printers/camera-models.js +18 -0
- package/dist/safety/hms-messages.d.ts +42 -0
- package/dist/safety/hms-messages.js +6194 -0
- package/dist/safety/printer-state.d.ts +18 -0
- package/dist/safety/printer-state.js +3 -3
- package/dist/slicer/process-overrides.d.ts +12 -0
- package/dist/slicer/process-overrides.js +33 -0
- package/dist/slicer/remote-slicer.js +2 -0
- package/dist/stl/stl-manipulator.d.ts +2 -0
- package/dist/stl/stl-manipulator.js +19 -0
- package/package.json +1 -1
- package/src/blender-mcp-bridge.ts +22 -3
- package/src/counterpart/info.ts +36 -0
- package/src/counterpart/make-3mf.ts +220 -0
- package/src/counterpart/progress.ts +254 -0
- package/src/counterpart/schemas.ts +154 -0
- package/src/fusion-mcp-bridge.ts +545 -0
- package/src/index.ts +199 -12
- package/src/printers/bambu-stages.ts +90 -0
- package/src/printers/bambu.ts +315 -37
- package/src/printers/camera-models.ts +18 -0
- package/src/safety/hms-messages.ts +6198 -0
- package/src/safety/printer-state.ts +4 -4
- package/src/slicer/process-overrides.ts +42 -0
- package/src/slicer/remote-slicer.ts +2 -0
- package/src/stl/stl-manipulator.ts +22 -0
package/src/printers/bambu.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { isFinishedP1SJob, isCancelledX2DJob, readFreshPrinterStatus } from "../safety/printer-state.js";
|
|
3
3
|
import fs from "node:fs/promises";
|
|
4
|
-
import { readFileSync, existsSync } from "node:fs";
|
|
4
|
+
import { createReadStream, readFileSync, existsSync } from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import os from "node:os";
|
|
7
7
|
import { Readable } from "node:stream";
|
|
@@ -11,6 +11,7 @@ import { isDualNozzleModel, normalizeModel, validateTemperature } from "../safet
|
|
|
11
11
|
import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, describeAmsTrayRange } from "../ams-mapping.js";
|
|
12
12
|
import { describeHmsKey, hiddenHmsKeys, hiddenHmsNotices, reportedHmsKey, unchippedNozzles, validatePrinterState, manualHeatingRequirements, type PrinterStateRequirements } from "../safety/printer-state.js";
|
|
13
13
|
import { withPrinterOperation, withPrintSnapshot, uniquePrintName, normalizedRemotePath, cancelPendingPrinterOperations } from "../safety/artifact.js";
|
|
14
|
+
import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
|
|
14
15
|
import { Client as FTPClient } from "basic-ftp";
|
|
15
16
|
import * as mqtt from "mqtt";
|
|
16
17
|
import {
|
|
@@ -45,6 +46,8 @@ function loadClientCreds(): { cert: Buffer; key: Buffer } | null {
|
|
|
45
46
|
const CLIENT_CREDS = loadClientCreds();
|
|
46
47
|
|
|
47
48
|
const COMMAND_SETTLE_MS = 300;
|
|
49
|
+
/** A cached report older than this may be refreshed once with PushAll; see readProgressReport. */
|
|
50
|
+
const STALE_REPORT_MS = 300_000;
|
|
48
51
|
/** HMS 0500-0500-0001-0007: firmware 01.08.05+ rejected an unsigned MQTT command. */
|
|
49
52
|
const COMMAND_VERIFICATION_HMS = { attr: 0x05000500, code: 0x00010007 };
|
|
50
53
|
const COMMAND_REJECTED_MESSAGE =
|
|
@@ -289,9 +292,16 @@ function ftpsSecureOptions(host: string): Record<string, unknown> {
|
|
|
289
292
|
}
|
|
290
293
|
|
|
291
294
|
class BambuClientStore {
|
|
295
|
+
/** Sees every merged report, so a resume record notices a job ending even when nobody polls. */
|
|
296
|
+
constructor(private readonly onReport?: (host: string, serial: string, report: Record<string, any>) => void) {}
|
|
297
|
+
|
|
292
298
|
private printers: Map<string, BambuClient> = new Map();
|
|
293
299
|
private initialConnectionPromises: Map<string, Promise<void>> = new Map();
|
|
294
300
|
private reportSnapshots: Map<string, Record<string, any>> = new Map();
|
|
301
|
+
/** When the last MQTT report for each printer arrived (ms since epoch). */
|
|
302
|
+
private reportTimes: Map<string, number> = new Map();
|
|
303
|
+
/** When PushAll was last sent for a stale cache, so a quiet printer is not asked repeatedly. */
|
|
304
|
+
private refreshTimes: Map<string, number> = new Map();
|
|
295
305
|
private initialReportPromises: Map<string, Promise<void>> = new Map();
|
|
296
306
|
private initialReportResolvers: Map<string, () => void> = new Map();
|
|
297
307
|
|
|
@@ -325,17 +335,43 @@ class BambuClientStore {
|
|
|
325
335
|
|
|
326
336
|
const previous = this.reportSnapshots.get(key) || {};
|
|
327
337
|
this.reportSnapshots.set(key, { ...previous, ...update });
|
|
338
|
+
this.reportTimes.set(key, Date.now());
|
|
328
339
|
this.resolveInitialReport(key);
|
|
329
340
|
}
|
|
330
341
|
|
|
342
|
+
private reportObserved(host: string, serial: string, key: string): void {
|
|
343
|
+
const report = this.reportSnapshots.get(key);
|
|
344
|
+
if (!report || !this.onReport) return;
|
|
345
|
+
try { this.onReport(host, serial, report); } catch { /* an observer never breaks report handling */ }
|
|
346
|
+
}
|
|
347
|
+
|
|
331
348
|
private clearPrinterState(key: string): void {
|
|
332
349
|
this.printers.delete(key);
|
|
333
350
|
this.initialConnectionPromises.delete(key);
|
|
334
351
|
this.reportSnapshots.delete(key);
|
|
352
|
+
this.reportTimes.delete(key);
|
|
353
|
+
this.refreshTimes.delete(key);
|
|
335
354
|
this.initialReportPromises.delete(key);
|
|
336
355
|
this.initialReportResolvers.delete(key);
|
|
337
356
|
}
|
|
338
357
|
|
|
358
|
+
/** The merged report of a connected printer and when it last arrived; none before the first report. */
|
|
359
|
+
getCachedReportWithTime(host: string, serial: string, token: string): { raw: Record<string, any>; receivedAt: number } | null {
|
|
360
|
+
const key = getPrinterKey(host, serial, token);
|
|
361
|
+
const raw = this.reportSnapshots.get(key);
|
|
362
|
+
const receivedAt = this.reportTimes.get(key);
|
|
363
|
+
return raw && receivedAt !== undefined && this.printers.has(key) ? { raw, receivedAt } : null;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Records a stale-cache refresh; false when one was sent within minIntervalMs. */
|
|
367
|
+
claimRefresh(host: string, serial: string, token: string, minIntervalMs: number): boolean {
|
|
368
|
+
const key = getPrinterKey(host, serial, token);
|
|
369
|
+
const last = this.refreshTimes.get(key);
|
|
370
|
+
if (last !== undefined && Date.now() - last < minIntervalMs) return false;
|
|
371
|
+
this.refreshTimes.set(key, Date.now());
|
|
372
|
+
return true;
|
|
373
|
+
}
|
|
374
|
+
|
|
339
375
|
getCachedReport(host: string, serial: string, token: string): Record<string, any> | null {
|
|
340
376
|
return this.reportSnapshots.get(getPrinterKey(host, serial, token)) || null;
|
|
341
377
|
}
|
|
@@ -406,6 +442,7 @@ class BambuClientStore {
|
|
|
406
442
|
const printMessage = parsed?.print;
|
|
407
443
|
if (printMessage && typeof printMessage === "object") {
|
|
408
444
|
this.updateReportSnapshot(key, printMessage);
|
|
445
|
+
this.reportObserved(host, serial, key);
|
|
409
446
|
}
|
|
410
447
|
} catch {
|
|
411
448
|
// Ignore unrelated payloads.
|
|
@@ -414,6 +451,7 @@ class BambuClientStore {
|
|
|
414
451
|
|
|
415
452
|
printer.on("printer:dataUpdate", (data) => {
|
|
416
453
|
this.updateReportSnapshot(key, data);
|
|
454
|
+
this.reportObserved(host, serial, key);
|
|
417
455
|
});
|
|
418
456
|
|
|
419
457
|
printer.on("client:connect", () => {
|
|
@@ -466,6 +504,8 @@ class BambuClientStore {
|
|
|
466
504
|
this.printers.clear();
|
|
467
505
|
this.initialConnectionPromises.clear();
|
|
468
506
|
this.reportSnapshots.clear();
|
|
507
|
+
this.reportTimes.clear();
|
|
508
|
+
this.refreshTimes.clear();
|
|
469
509
|
this.initialReportPromises.clear();
|
|
470
510
|
this.initialReportResolvers.clear();
|
|
471
511
|
}
|
|
@@ -476,6 +516,82 @@ function printJobIdentity(raw: Record<string, any>): string {
|
|
|
476
516
|
return JSON.stringify([raw.gcode_file, raw.subtask_name, raw.task_id, raw.subtask_id, raw.job_id]);
|
|
477
517
|
}
|
|
478
518
|
|
|
519
|
+
/** A merged MQTT report and when it last arrived (ms since epoch). */
|
|
520
|
+
export type ProgressReport = { raw: Record<string, any>; receivedAt: number };
|
|
521
|
+
|
|
522
|
+
/** The inspected bytes and limits of a started job, for the resume prompt and byte check. */
|
|
523
|
+
export type CheckedFile = {
|
|
524
|
+
sha256: string;
|
|
525
|
+
/** A project's printed plate: its number and the SHA-256 of its Metadata/plate_<index>.gcode. */
|
|
526
|
+
plate?: { index: number; sha256: string };
|
|
527
|
+
model: string;
|
|
528
|
+
maxNozzleTemperature: number;
|
|
529
|
+
maxBedTemperature: number;
|
|
530
|
+
maxChamberTemperature: number;
|
|
531
|
+
materials: string[];
|
|
532
|
+
};
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* The last job this server inspected and started on a printer. seenRunning: a
|
|
536
|
+
* report showed it preparing, printing or paused, so a later ended report, or
|
|
537
|
+
* another job in its place, is about it rather than about the job before it.
|
|
538
|
+
*/
|
|
539
|
+
type CheckedJob = CheckedFile & {
|
|
540
|
+
remotePath: string;
|
|
541
|
+
requirements: PrinterStateRequirements;
|
|
542
|
+
seenRunning: boolean;
|
|
543
|
+
/** This server uploaded the bytes to remotePath over FTPS, so a failed re-read refuses the resume. */
|
|
544
|
+
uploadedHere: boolean;
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
const ACTIVE_JOB_STATES = new Set(["PREPARE", "SLICING", "RUNNING", "PAUSE"]);
|
|
548
|
+
/** Reports after which a started job can no longer be resumed. */
|
|
549
|
+
const ENDED_JOB_STATES = new Set(["FINISH", "FAILED", "IDLE"]);
|
|
550
|
+
|
|
551
|
+
const jobStem = (value: string) => path.posix.basename(value.replace(/\\/g, "/")).replace(/(?:\.gcode)?\.3mf$|\.gcode$/i, "");
|
|
552
|
+
const reportedJobNames = (raw: Record<string, any>): string[] =>
|
|
553
|
+
[raw.gcode_file, raw.subtask_name].filter((value): value is string => typeof value === "string" && value.trim() !== "");
|
|
554
|
+
/** Whether a report names the job stored at remotePath (subtask_name for projects, gcode_file for raw G-code). */
|
|
555
|
+
function reportsJob(raw: Record<string, any>, remotePath: string): boolean {
|
|
556
|
+
return reportedJobNames(raw).some(value => jobStem(value) === jobStem(remotePath));
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** What a resume needs to know about a started file (filePath, the inspected snapshot): its bytes, printed plate, limits and used materials. */
|
|
560
|
+
export async function checkedFile(inspection: PrintFileInspection, filePath: string): Promise<CheckedFile> {
|
|
561
|
+
const used = inspection.usedFilamentPositions.map(position => inspection.materials[position]).filter(Boolean);
|
|
562
|
+
let plate: CheckedFile["plate"];
|
|
563
|
+
const plateNumber = /^Metadata\/plate_(\d+)\.gcode$/i.exec(inspection.plateInternalPath ?? "");
|
|
564
|
+
if (plateNumber && /\.3mf$/i.test(filePath)) {
|
|
565
|
+
const entry = (await readSafe3mfArchive(filePath)).zip.file(inspection.plateInternalPath!);
|
|
566
|
+
if (entry) plate = { index: Number(plateNumber[1]), sha256: createHash("sha256").update(await entry.async("nodebuffer")).digest("hex") };
|
|
567
|
+
}
|
|
568
|
+
return {
|
|
569
|
+
sha256: inspection.sha256, ...(plate ? { plate } : {}), model: inspection.model,
|
|
570
|
+
maxNozzleTemperature: inspection.maxNozzleTemperature, maxBedTemperature: inspection.maxBedTemperature, maxChamberTemperature: inspection.maxChamberTemperature,
|
|
571
|
+
materials: [...new Set(used.length ? used : inspection.materials)],
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Where a printer keeps the plate G-code it extracted from a project to print
|
|
577
|
+
* it. A P1S removes the uploaded 3MF once it starts and keeps
|
|
578
|
+
* cache/<name>_plate_<n>.gcode, byte-identical to the 3MF's
|
|
579
|
+
* Metadata/plate_<n>.gcode (checked on a P1S for project_file and legacy
|
|
580
|
+
* .gcode.3mf jobs).
|
|
581
|
+
*/
|
|
582
|
+
function extractedPlatePath(remotePath: string, index: number): string {
|
|
583
|
+
const directory = path.posix.dirname(remotePath);
|
|
584
|
+
const stem = path.posix.basename(remotePath).replace(/(?:\.gcode)?\.3mf$/i, "");
|
|
585
|
+
return `${directory === "." ? "" : `${directory}/`}${stem}_plate_${index}.gcode`;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** The name counterpart_print_progress reports for the job: subtask_name, else the G-code file's basename. */
|
|
589
|
+
function reportedJobName(raw: Record<string, any>): string | undefined {
|
|
590
|
+
const subtask = typeof raw.subtask_name === "string" ? raw.subtask_name.trim() : "";
|
|
591
|
+
if (subtask) return subtask;
|
|
592
|
+
return typeof raw.gcode_file === "string" ? path.posix.basename(raw.gcode_file.replace(/\\/g, "/").replace(/^\d+:/, "")) || undefined : undefined;
|
|
593
|
+
}
|
|
594
|
+
|
|
479
595
|
export type PrintPreflight = { finishedJob?: string; serial: string; model: string; notices: string[] };
|
|
480
596
|
|
|
481
597
|
/**
|
|
@@ -510,23 +626,35 @@ export function cameraFrameParser(onFrame: (jpeg: Buffer) => void, onError: (err
|
|
|
510
626
|
|
|
511
627
|
export class BambuImplementation {
|
|
512
628
|
private printerStore: BambuClientStore;
|
|
513
|
-
|
|
629
|
+
/**
|
|
630
|
+
* The job each printer may resume, keyed host and serial. Cancel, a report
|
|
631
|
+
* that it ended after it was seen running, or another job seen in its place
|
|
632
|
+
* retires it, so a later job that reuses the name is never resumed.
|
|
633
|
+
*/
|
|
634
|
+
private checkedJobs = new Map<string, CheckedJob>();
|
|
635
|
+
/** In-flight counterpart_print_progress reads, one per printer. */
|
|
636
|
+
private progressReads = new Map<string, Promise<ProgressReport | null>>();
|
|
514
637
|
private clearedErrors = new Map<string, string[]>();
|
|
515
638
|
|
|
516
639
|
constructor(private readonly confirm?: (message: string) => Promise<boolean>) {
|
|
517
|
-
this.printerStore = new BambuClientStore();
|
|
640
|
+
this.printerStore = new BambuClientStore((host, serial, report) => this.observeReport(host, serial, report));
|
|
518
641
|
}
|
|
519
642
|
|
|
520
|
-
|
|
521
|
-
|
|
643
|
+
/**
|
|
644
|
+
* Ask a person through MCP elicitation. BAMBU_REQUIRE_CONFIRMATION=0 skips
|
|
645
|
+
* ordinary prompts; a physical check, or a prompt with requiredBecause (why
|
|
646
|
+
* this one cannot be skipped), always asks.
|
|
647
|
+
*/
|
|
648
|
+
async confirmHardwareAction(message: string, physicalCheck = false, requiredBecause?: string): Promise<void> {
|
|
649
|
+
if (!physicalCheck && requiredBecause === undefined && process.env.BAMBU_REQUIRE_CONFIRMATION === "0") return;
|
|
522
650
|
if (!this.confirm) {
|
|
523
|
-
throw new Error("Hardware safety confirmation is unavailable. Use an MCP client with elicitation support. No command was sent.");
|
|
651
|
+
throw new Error("Hardware safety confirmation is unavailable. Use an MCP client with elicitation support. No command was sent." + (requiredBecause ? ` ${requiredBecause}` : ""));
|
|
524
652
|
}
|
|
525
653
|
if (!(await this.confirm(message))) {
|
|
526
654
|
throw new Error("Hardware safety confirmation was declined or cancelled in the MCP client. No command was sent. " + (physicalCheck
|
|
527
655
|
? "This confirmation covers a physical check at the printer and always needs a person to accept it."
|
|
528
|
-
: "Some clients decline prompts automatically, for example in a non-interactive permission mode. " +
|
|
529
|
-
"A deliberately headless setup that approves jobs another way can set BAMBU_REQUIRE_CONFIRMATION=0 to skip ordinary print and heating prompts."));
|
|
656
|
+
: requiredBecause ?? ("Some clients decline prompts automatically, for example in a non-interactive permission mode. " +
|
|
657
|
+
"A deliberately headless setup that approves jobs another way can set BAMBU_REQUIRE_CONFIRMATION=0 to skip ordinary print and heating prompts.")));
|
|
530
658
|
}
|
|
531
659
|
}
|
|
532
660
|
|
|
@@ -581,12 +709,36 @@ export class BambuImplementation {
|
|
|
581
709
|
return this.printerStore.getPrinter(host, serial, token);
|
|
582
710
|
}
|
|
583
711
|
|
|
584
|
-
/**
|
|
585
|
-
|
|
586
|
-
|
|
712
|
+
/**
|
|
713
|
+
* Internal handoff from a successful inspected transport; never exposed as
|
|
714
|
+
* an MCP tool. uploadedHere is false for the plug-in routes, where Bambu's
|
|
715
|
+
* plug-in or cloud put the file on the printer at a path this server has not
|
|
716
|
+
* verified: a resume then re-reads it if it can and otherwise matches the
|
|
717
|
+
* unique name, as KAN-216 does for firmware that cannot download a file.
|
|
718
|
+
*/
|
|
719
|
+
recordCheckedJob(host: string, serial: string, remotePath: string, requirements: PrinterStateRequirements, file: CheckedFile, uploadedHere = true): void {
|
|
720
|
+
if (!/^[a-f0-9]{64}$/.test(file?.sha256 ?? "")) throw new Error("A started job needs the SHA-256 of its inspected bytes.");
|
|
721
|
+
this.checkedJobs.set(`${host}\n${serial}`, {
|
|
722
|
+
...structuredClone(file), remotePath, requirements: structuredClone(requirements), seenRunning: false, uploadedHere,
|
|
723
|
+
});
|
|
587
724
|
this.clearedErrors.delete(serial);
|
|
588
725
|
}
|
|
589
726
|
|
|
727
|
+
/** Feed one merged report to the resume record (internal; the client store calls it for every report). */
|
|
728
|
+
observeReport(host: string, serial: string, raw: Record<string, any> | undefined): void {
|
|
729
|
+
const key = `${host}\n${serial}`;
|
|
730
|
+
const checked = this.checkedJobs.get(key);
|
|
731
|
+
if (!checked || !raw || typeof raw.gcode_state !== "string") return;
|
|
732
|
+
const state = raw.gcode_state.toUpperCase();
|
|
733
|
+
if (ACTIVE_JOB_STATES.has(state) && reportsJob(raw, checked.remotePath)) {
|
|
734
|
+
checked.seenRunning = true;
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
if (checked.seenRunning && (ENDED_JOB_STATES.has(state) || (ACTIVE_JOB_STATES.has(state) && reportedJobNames(raw).length > 0))) {
|
|
738
|
+
this.checkedJobs.delete(key);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
590
742
|
private validateLoadedGcodeState(status: any, inspection: Awaited<ReturnType<typeof inspectPrintFile>>): PrinterStateRequirements {
|
|
591
743
|
const usedMaterials = inspection.usedFilamentPositions.map(position => inspection.materials[position]);
|
|
592
744
|
if (new Set(usedMaterials).size !== 1) throw new Error("gcode_file printing cannot verify physical changes between different materials. Use a mapped .3mf project.");
|
|
@@ -670,6 +822,69 @@ export class BambuImplementation {
|
|
|
670
822
|
return readFreshPrinterStatus(await this.getPrinter(host, serial, token), serial);
|
|
671
823
|
}
|
|
672
824
|
|
|
825
|
+
/**
|
|
826
|
+
* The merged MQTT report for counterpart_print_progress and when it arrived.
|
|
827
|
+
* On a held session it comes from the cache with no printer traffic. PushAll
|
|
828
|
+
* is sent only to fill a cold cache, or at most once per STALE_REPORT_MS when
|
|
829
|
+
* the printer has been quiet for longer than that (P1-series firmware lags
|
|
830
|
+
* when asked often). The whole read, connection and publish included, is
|
|
831
|
+
* bounded by timeoutMs: the MQTT connect to an unreachable printer keeps
|
|
832
|
+
* retrying, so it must not hold the call. Then the result is null, or a stale
|
|
833
|
+
* report that could not be refreshed in time. Display data only; safety
|
|
834
|
+
* checks use getSafetyStatus.
|
|
835
|
+
*/
|
|
836
|
+
async readProgressReport(host: string, serial: string, token: string, timeoutMs = 8_000): Promise<ProgressReport | null> {
|
|
837
|
+
const cached = this.printerStore.getCachedReportWithTime(host, serial, token);
|
|
838
|
+
const warm = cached !== null && typeof cached.raw.gcode_state === "string";
|
|
839
|
+
if (warm && (Date.now() - cached.receivedAt <= STALE_REPORT_MS || !this.printerStore.claimRefresh(host, serial, token, STALE_REPORT_MS))) return cached;
|
|
840
|
+
// One first read or refresh per printer at a time. Callers that gave up share
|
|
841
|
+
// it, so a printer that comes back gets one PushAll, not one per expired poll.
|
|
842
|
+
const key = getPrinterKey(host, serial, token);
|
|
843
|
+
let read = this.progressReads.get(key);
|
|
844
|
+
if (!read) {
|
|
845
|
+
const started = warm ? this.refreshProgressReport(host, serial, token, cached) : this.firstProgressReport(host, serial, token);
|
|
846
|
+
read = started.finally(() => { if (this.progressReads.get(key) === read) this.progressReads.delete(key); });
|
|
847
|
+
read.catch(() => {});
|
|
848
|
+
this.progressReads.set(key, read);
|
|
849
|
+
}
|
|
850
|
+
const latest = () => warm ? this.printerStore.getCachedReportWithTime(host, serial, token) ?? cached : null;
|
|
851
|
+
let timer: NodeJS.Timeout | undefined;
|
|
852
|
+
const expired = new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), timeoutMs); });
|
|
853
|
+
try {
|
|
854
|
+
return (await Promise.race([read, expired])) ?? latest();
|
|
855
|
+
} catch {
|
|
856
|
+
return latest();
|
|
857
|
+
} finally {
|
|
858
|
+
clearTimeout(timer);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
private async firstProgressReport(host: string, serial: string, token: string): Promise<ProgressReport | null> {
|
|
863
|
+
const printer = await this.getPrinter(host, serial, token);
|
|
864
|
+
// The printer may already have pushed its full status while connecting.
|
|
865
|
+
if (typeof this.printerStore.getCachedReportWithTime(host, serial, token)?.raw.gcode_state !== "string") {
|
|
866
|
+
try { await invokeWithoutAck(printer, new PushAllCommand()); } catch { /* the printer pushes on its own too */ }
|
|
867
|
+
}
|
|
868
|
+
await this.printerStore.waitForInitialReport(host, serial, token, 4_000);
|
|
869
|
+
// A connected printer whose report still lacks gcode_state is busy, not offline.
|
|
870
|
+
return this.printerStore.getCachedReportWithTime(host, serial, token);
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
private async refreshProgressReport(host: string, serial: string, token: string, cached: ProgressReport): Promise<ProgressReport> {
|
|
874
|
+
try {
|
|
875
|
+
await invokeWithoutAck(await this.getPrinter(host, serial, token), new PushAllCommand());
|
|
876
|
+
const deadline = Date.now() + 2_000;
|
|
877
|
+
while (Date.now() < deadline) {
|
|
878
|
+
const latest = this.printerStore.getCachedReportWithTime(host, serial, token);
|
|
879
|
+
if (latest && latest.receivedAt > cached.receivedAt) return latest;
|
|
880
|
+
await sleep(50);
|
|
881
|
+
}
|
|
882
|
+
} catch {
|
|
883
|
+
// A failed refresh leaves the cached report, which still carries its own time.
|
|
884
|
+
}
|
|
885
|
+
return this.printerStore.getCachedReportWithTime(host, serial, token) ?? cached;
|
|
886
|
+
}
|
|
887
|
+
|
|
673
888
|
async getStatus(host: string, serial: string, token: string): Promise<any> {
|
|
674
889
|
try {
|
|
675
890
|
const printer = await this.getPrinter(host, serial, token);
|
|
@@ -772,6 +987,7 @@ export class BambuImplementation {
|
|
|
772
987
|
const inspection = await inspectPrintFile(options.filePath, {
|
|
773
988
|
model, nozzleDiameters: options.nozzleDiameters, plateIndex: options.plateIndex ?? 0, bedType: options.bedType,
|
|
774
989
|
});
|
|
990
|
+
const resumeFile = await checkedFile(inspection, options.filePath);
|
|
775
991
|
const projectMetadata = await this.resolveProjectFileMetadata(
|
|
776
992
|
options.filePath,
|
|
777
993
|
options.plateIndex,
|
|
@@ -914,7 +1130,7 @@ export class BambuImplementation {
|
|
|
914
1130
|
if (legacyContainer) {
|
|
915
1131
|
const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
|
|
916
1132
|
try { await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remoteProjectPath })); } catch (error) { watcher.dispose(); throw error; }
|
|
917
|
-
this.recordCheckedJob(host, serial, remoteProjectPath, requirements);
|
|
1133
|
+
this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
|
|
918
1134
|
const dispatch = await watcher.settled();
|
|
919
1135
|
return {
|
|
920
1136
|
status: "success", dispatch, remoteProjectPath,
|
|
@@ -927,8 +1143,13 @@ export class BambuImplementation {
|
|
|
927
1143
|
|
|
928
1144
|
const b = (v: any) => (v ? 1 : 0);
|
|
929
1145
|
let projectFileCmd: Record<string, any>;
|
|
1146
|
+
// The printer reports these back as subtask_name/task_id, so the result
|
|
1147
|
+
// returns exactly what was sent. Only the H2-style route sends a real task id.
|
|
1148
|
+
const subtaskName = remoteFileName.replace(/\.3mf$/i, "");
|
|
1149
|
+
let taskId: string | undefined;
|
|
930
1150
|
if (usesH2ProjectFile) {
|
|
931
1151
|
const submissionId = String(Date.now() & 0x7fffffff);
|
|
1152
|
+
taskId = submissionId;
|
|
932
1153
|
projectFileCmd = {
|
|
933
1154
|
print: {
|
|
934
1155
|
sequence_id: "0",
|
|
@@ -949,7 +1170,7 @@ export class BambuImplementation {
|
|
|
949
1170
|
extrude_cali_flag: 0,
|
|
950
1171
|
extrude_cali_manual_mode: 0,
|
|
951
1172
|
nozzle_offset_cali: 2,
|
|
952
|
-
subtask_name:
|
|
1173
|
+
subtask_name: subtaskName,
|
|
953
1174
|
profile_id: "0",
|
|
954
1175
|
project_id: submissionId,
|
|
955
1176
|
subtask_id: submissionId,
|
|
@@ -964,7 +1185,7 @@ export class BambuImplementation {
|
|
|
964
1185
|
command: "project_file",
|
|
965
1186
|
param: projectMetadata.plateInternalPath,
|
|
966
1187
|
url: projectUrl,
|
|
967
|
-
subtask_name:
|
|
1188
|
+
subtask_name: subtaskName,
|
|
968
1189
|
md5,
|
|
969
1190
|
flow_cali: options.flowCalibration ?? true,
|
|
970
1191
|
layer_inspect: options.layerInspect ?? true,
|
|
@@ -985,7 +1206,7 @@ export class BambuImplementation {
|
|
|
985
1206
|
|
|
986
1207
|
const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
|
|
987
1208
|
try { await printer.publish(projectFileCmd); } catch (error) { watcher.dispose(); throw error; }
|
|
988
|
-
this.recordCheckedJob(host, serial, remoteProjectPath, requirements);
|
|
1209
|
+
this.recordCheckedJob(host, serial, remoteProjectPath, requirements, resumeFile);
|
|
989
1210
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
990
1211
|
const dispatch = await watcher.settled();
|
|
991
1212
|
|
|
@@ -1001,6 +1222,8 @@ export class BambuImplementation {
|
|
|
1001
1222
|
platePath: projectMetadata.plateInternalPath,
|
|
1002
1223
|
md5,
|
|
1003
1224
|
amsMapping,
|
|
1225
|
+
subtaskName,
|
|
1226
|
+
...(taskId !== undefined ? { taskId } : {}),
|
|
1004
1227
|
};
|
|
1005
1228
|
}
|
|
1006
1229
|
|
|
@@ -1077,29 +1300,93 @@ export class BambuImplementation {
|
|
|
1077
1300
|
}
|
|
1078
1301
|
}
|
|
1079
1302
|
|
|
1303
|
+
/**
|
|
1304
|
+
* Resume reheats and moves the printer, so it is gated like a print start:
|
|
1305
|
+
* only the job this server inspected and started, while a fresh report shows
|
|
1306
|
+
* it paused, with its bytes re-read over FTPS and compared, and after human
|
|
1307
|
+
* confirmation (unless BAMBU_REQUIRE_CONFIRMATION=0). The record must still
|
|
1308
|
+
* be current at every check, including the native helper's last one.
|
|
1309
|
+
*/
|
|
1080
1310
|
async resumeJob(host: string, serial: string, token: string, dispatch?: (assertActive: () => void, beforeDispatch: () => Promise<void>) => Promise<any>): Promise<any> {
|
|
1081
1311
|
return withPrinterOperation(host, serial, async assertActive => {
|
|
1082
|
-
const
|
|
1312
|
+
const key = `${host}\n${serial}`;
|
|
1313
|
+
const checked = this.checkedJobs.get(key);
|
|
1083
1314
|
if (!checked) throw new Error("Resume requires a job inspected and started by this server instance. Verify other jobs on the printer before resuming them there.");
|
|
1084
|
-
|
|
1315
|
+
let jobName = path.posix.basename(checked.remotePath);
|
|
1316
|
+
const pausedJob = async () => {
|
|
1085
1317
|
assertActive();
|
|
1086
1318
|
const status = await this.getSafetyStatus(host, serial, token);
|
|
1319
|
+
this.observeReport(host, serial, status.raw);
|
|
1320
|
+
if (this.checkedJobs.get(key) !== checked) {
|
|
1321
|
+
throw new Error(`${jobName} is no longer the job this server started: it was cancelled, it ended, or another job took its place. Nothing was sent; check the printer and resume it there.`);
|
|
1322
|
+
}
|
|
1087
1323
|
validatePrinterState(status, { ...checked.requirements, requireIdle: false });
|
|
1088
1324
|
if (status.raw.gcode_state !== "PAUSE") throw new Error("Resume requires a freshly reported paused job.");
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
if (!names.some(value => stem(value) === stem(checked.remotePath))) throw new Error("Paused job identity does not match this server's inspected artifact.");
|
|
1325
|
+
if (!reportsJob(status.raw, checked.remotePath)) throw new Error("Paused job identity does not match this server's inspected artifact.");
|
|
1326
|
+
jobName = reportedJobName(status.raw) ?? jobName;
|
|
1092
1327
|
assertActive();
|
|
1093
1328
|
};
|
|
1094
|
-
await
|
|
1329
|
+
await pausedJob();
|
|
1330
|
+
const reread = await this.rereadJob(host, token, checked);
|
|
1331
|
+
if ("changed" in reread) {
|
|
1332
|
+
if (this.checkedJobs.get(key) === checked) this.checkedJobs.delete(key);
|
|
1333
|
+
throw new Error(`${jobName} on the printer is no longer the file this server inspected (SHA-256 of ${reread.changed} changed). Nothing was sent, and this job can no longer be resumed from here.`);
|
|
1334
|
+
}
|
|
1335
|
+
const unread = "unread" in reread ? reread.unread : undefined;
|
|
1336
|
+
if (unread !== undefined && checked.uploadedHere) {
|
|
1337
|
+
throw new Error(`Could not re-read ${jobName} from the printer over FTPS to confirm it is the inspected file (${unread}). Nothing was sent; resume it at the printer.`);
|
|
1338
|
+
}
|
|
1339
|
+
const bytesVerified = "verified" in reread;
|
|
1340
|
+
assertActive();
|
|
1341
|
+
await this.confirmHardwareAction(
|
|
1342
|
+
`Resume ${jobName} on ${checked.model.toUpperCase()} (${serial})? It reheats to its targets (peak nozzle ${checked.maxNozzleTemperature}°C, ` +
|
|
1343
|
+
`bed ${checked.maxBedTemperature}°C, chamber ${checked.maxChamberTemperature}°C) and moves. Materials: ${checked.materials.length ? checked.materials.join(", ") : "none declared"}. ` +
|
|
1344
|
+
`File SHA-256: ${checked.sha256}${"verified" in reread ? ` (re-read from the printer${reread.verified === checked.remotePath ? "" : ` as its extracted plate ${reread.verified}`})` : ` (Bambu's plug-in placed the file, and it could not be re-read over FTPS: ${unread}; matched by its unique name)`}. ` +
|
|
1345
|
+
"Confirm the nozzle path is clear and the filament is still loaded.",
|
|
1346
|
+
false,
|
|
1347
|
+
// The opt-out covers resumes whose bytes were checked; an unverified file always needs a person.
|
|
1348
|
+
bytesVerified ? undefined : "The printer's copy of this file could not be re-read, so this resume always needs a person to accept it, even with BAMBU_REQUIRE_CONFIRMATION=0."
|
|
1349
|
+
);
|
|
1350
|
+
// The job may have been resumed, stopped or replaced at the printer while the prompt was open.
|
|
1351
|
+
await pausedJob();
|
|
1095
1352
|
const printer = dispatch ? undefined : await this.getPrinter(host, serial, token);
|
|
1096
1353
|
assertActive();
|
|
1097
|
-
if (dispatch) await dispatch(assertActive,
|
|
1354
|
+
if (dispatch) await dispatch(assertActive, pausedJob);
|
|
1098
1355
|
else await invokeWithoutAck(printer!, new UpdateStateCommand({ state: "resume" }));
|
|
1099
|
-
return { status: "success", message:
|
|
1356
|
+
return { status: "success", message: `Resume command sent for ${jobName}.`, jobName, bytesVerified };
|
|
1100
1357
|
});
|
|
1101
1358
|
}
|
|
1102
1359
|
|
|
1360
|
+
/**
|
|
1361
|
+
* Re-read a started job's bytes over FTPS: the uploaded file, else the plate
|
|
1362
|
+
* G-code the printer extracted from the project to print it. The first file
|
|
1363
|
+
* that can be read decides; a mismatch is reported as changed.
|
|
1364
|
+
*/
|
|
1365
|
+
private async rereadJob(host: string, token: string, checked: CheckedJob): Promise<{ verified: string } | { changed: string } | { unread: string }> {
|
|
1366
|
+
const candidates = [{ remote: checked.remotePath, sha256: checked.sha256 }];
|
|
1367
|
+
if (checked.plate) candidates.push({ remote: extractedPlatePath(checked.remotePath, checked.plate.index), sha256: checked.plate.sha256 });
|
|
1368
|
+
const failures: string[] = [];
|
|
1369
|
+
for (const candidate of candidates) {
|
|
1370
|
+
let sha256: string;
|
|
1371
|
+
try { sha256 = await this.remoteSha256(host, token, candidate.remote); }
|
|
1372
|
+
catch (error) { failures.push(`${candidate.remote}: ${(error as Error).message}`); continue; }
|
|
1373
|
+
return sha256 === candidate.sha256 ? { verified: candidate.remote } : { changed: candidate.remote };
|
|
1374
|
+
}
|
|
1375
|
+
return { unread: failures.join("; ") };
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
/** SHA-256 of a printer file, streamed from an FTPS download into a private directory. */
|
|
1379
|
+
private async remoteSha256(host: string, token: string, remotePath: string): Promise<string> {
|
|
1380
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "bambu-resume-check-"));
|
|
1381
|
+
try {
|
|
1382
|
+
const localPath = path.join(directory, "job");
|
|
1383
|
+
await this.ftpDownload(host, token, remotePath, localPath);
|
|
1384
|
+
const hash = createHash("sha256");
|
|
1385
|
+
for await (const chunk of createReadStream(localPath)) hash.update(chunk as Buffer);
|
|
1386
|
+
return hash.digest("hex");
|
|
1387
|
+
} finally { await fs.rm(directory, { recursive: true, force: true }); }
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1103
1390
|
async clearHmsErrors(host: string, serial: string, token: string, dispatch?: (assertActive: () => void, beforeDispatch: () => Promise<void>) => Promise<any>): Promise<any> {
|
|
1104
1391
|
return withPrinterOperation(host, serial, async assertActive => {
|
|
1105
1392
|
const codesFor = (status: any): string[] => {
|
|
@@ -1536,6 +1823,7 @@ export class BambuImplementation {
|
|
|
1536
1823
|
if (!model) throw new Error("A supported bambuModel is required before printing.");
|
|
1537
1824
|
const inspection = await inspectPrintFile(filePath, { model });
|
|
1538
1825
|
if (inspection.selectsAms) throw new Error("Raw G-code with AMS selection requires a .3mf project export with verified physical slot mappings.");
|
|
1826
|
+
const resumeFile = await checkedFile(inspection, filePath);
|
|
1539
1827
|
const initialStatus = await this.getSafetyStatus(host, serial, token);
|
|
1540
1828
|
let requirements = this.validateLoadedGcodeState(initialStatus, inspection);
|
|
1541
1829
|
const preflight = await this.confirmPrintPreflight(serial, initialStatus, inspection);
|
|
@@ -1552,10 +1840,12 @@ export class BambuImplementation {
|
|
|
1552
1840
|
assertActive();
|
|
1553
1841
|
const watcher = this.watchDispatch(printer, host, serial, token, dispatchStatus, assertActive);
|
|
1554
1842
|
try { await invokeWithoutAck(printer, new GCodeFileCommand({ fileName: remotePath })); } catch (error) { watcher.dispose(); throw error; }
|
|
1555
|
-
this.recordCheckedJob(host, serial, remotePath, requirements);
|
|
1843
|
+
this.recordCheckedJob(host, serial, remotePath, requirements, resumeFile);
|
|
1556
1844
|
const dispatch = await watcher.settled();
|
|
1557
1845
|
return {
|
|
1558
1846
|
status: "success", uploaded: true, printRequested: true, dispatch, remotePath,
|
|
1847
|
+
// counterpart_print_progress reports this as job.name (the printer reports no subtask_name for raw G-code).
|
|
1848
|
+
jobName: path.posix.basename(remotePath),
|
|
1559
1849
|
message: dispatch === "started"
|
|
1560
1850
|
? `The printer accepted and started ${remotePath}.`
|
|
1561
1851
|
: `Sent the print command for ${remotePath}; the printer has not reported starting yet. Check get_printer_status before assuming it is printing.`,
|
|
@@ -1714,19 +2004,7 @@ export class BambuImplementation {
|
|
|
1714
2004
|
}> {
|
|
1715
2005
|
const timeoutMs = options.timeoutMs ?? 8_000;
|
|
1716
2006
|
const model = (options.bambuModel ?? "").toLowerCase();
|
|
1717
|
-
|
|
1718
|
-
// (per https://github.com/Doridian/OpenBambuAPI/blob/main/video.md).
|
|
1719
|
-
const TCP_CAMERA_MODELS = new Set(["a1", "a1mini", "p1s", "p1p"]);
|
|
1720
|
-
// X1, P2S, H2 (H2S/H2D/H2C), AND X2D all use RTSP on port 322. The
|
|
1721
|
-
// OpenBambuAPI doc only mentions X1/P2S, but the HA bambulab
|
|
1722
|
-
// integration's models.py shows the printer reports its own
|
|
1723
|
-
// `ipcam.rtsp_url` for these models, and Parker (H2S) rejects the
|
|
1724
|
-
// A1/P1 80-byte auth packet on port 6000 (verified 2026-04-27 --
|
|
1725
|
-
// confirmed by local H2 camera transport probes).
|
|
1726
|
-
const RTSP_MODELS = new Set([
|
|
1727
|
-
"x1", "x1c", "x1carbon", "x1e", "p2s",
|
|
1728
|
-
"h2", "h2s", "h2d", "h2c", "h2dpro", "x2d",
|
|
1729
|
-
]);
|
|
2007
|
+
const RTSP_MODELS = RTSP_CAMERA_MODELS;
|
|
1730
2008
|
|
|
1731
2009
|
if (!model) {
|
|
1732
2010
|
throw new Error(
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which camera transport each model uses, keyed by the lowercased model name
|
|
3
|
+
* with spaces removed. camera_snapshot routes by these sets and
|
|
4
|
+
* counterpart_printer_info reports them, so the two always agree.
|
|
5
|
+
*/
|
|
6
|
+
// P1/A1 series use the proprietary TCP-on-6000 framed JPEG path
|
|
7
|
+
// (per https://github.com/Doridian/OpenBambuAPI/blob/main/video.md).
|
|
8
|
+
export const TCP_CAMERA_MODELS: ReadonlySet<string> = new Set(["a1", "a1mini", "p1s", "p1p"]);
|
|
9
|
+
// X1, P2S, H2 (H2S/H2D/H2C), AND X2D all use RTSP on port 322. The
|
|
10
|
+
// OpenBambuAPI doc only mentions X1/P2S, but the HA bambulab
|
|
11
|
+
// integration's models.py shows the printer reports its own
|
|
12
|
+
// `ipcam.rtsp_url` for these models, and Parker (H2S) rejects the
|
|
13
|
+
// A1/P1 80-byte auth packet on port 6000 (verified 2026-04-27 --
|
|
14
|
+
// confirmed by local H2 camera transport probes).
|
|
15
|
+
export const RTSP_CAMERA_MODELS: ReadonlySet<string> = new Set([
|
|
16
|
+
"x1", "x1c", "x1carbon", "x1e", "p2s",
|
|
17
|
+
"h2", "h2s", "h2d", "h2c", "h2dpro", "x2d",
|
|
18
|
+
]);
|