Fix print.push_status parsing, and stop losing reports silently
Pointed at a real H2C that was 20% into a job, `print_status()` returned
nothing at all. The printer was in fact pushing a full status object every
second; every one was arriving, failing to deserialize, and being dropped
invisibly by an `if let Ok(report) = ..` with no `else`.
That silence produced two confidently-wrong claims in our own comments,
both corrected here:
- `pushall`'s doc said whether v2 emits `push_status` unprompted was "an
open question". It is not: v2 pushes a full 97-field object roughly once
a second from the moment you subscribe, no trigger needed. There is no
missing "other trigger" to hunt for.
- The "sequence gap" warning blamed the network for dropped v1 updates.
Those updates were not dropped in transit - they failed to parse, so
they never reached the counter, making the next one that did look like a
skip. Confirmed: seq 57, 62, 64 and 69 all arrived. After the fix, zero
gaps and zero parse failures across a 25s run against both printers.
Two concrete causes, both found with captured payloads:
- v1 trays carry `tray_temp`/`tray_time`; v2 trays carry
`drying_temp`/`drying_time`. All four were required, so *every* v1 push
carrying AMS data failed.
- A third tray shape existed that nothing modelled: an empty v2 slot sends
`{"id": "2", "state": 0}`, which matched neither `EmptyTray` (it denies
unknown fields, deliberately) nor `LoadedTray` (16 fields short).
A parse failure now reports itself, naming the printer, the sequence id and
the serde error. A report this process cannot parse is a defect in
`PrintReport`, and the only way to fix it is to be told which field.
`PrintReport` itself modelled 9 of 97 top-level fields, and none of them
were progress or temperature - it was built from a truncated example. It
now carries gcode_state, percent, layer counts, remaining time, nozzle/bed
temperatures, fan gears, wifi and HMS entries. `merge_from`'s two dozen
four-line blocks collapse to `newer.x.or(self.x.take())` one-liners: the
old shape made adding a field a three-place edit, and forgetting the merge
half produced a field that silently never survived a partial update.
Two scale traps documented where they bite: reported fan speeds are 0-15
gears, not percent and not the 0-255 PWM we send (`set_fan_speed(50)`
reads back as "7"); and v2 pins `sequence_id` to one value for minutes
while contents change, so it orders and identifies nothing there.
Two examples, and the distinction between them is the point. `live_reports`
is read-only and safe against a printer mid-job. `bambu_idle_checks`
writes, so it requires an explicit printer id and refuses to run unless
that printer reports `gcode_state: "IDLE"`.
Regression fixtures are verbatim captures off both printers, hardware
identifiers scrubbed - the only way to keep this from regressing without a
printer plugged in.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
//! Run with: cargo run --example bambu_idle_checks -- <printer-id>
|
||||
//!
|
||||
//! **This one writes.** Unlike `live_reports`, it sends commands that change
|
||||
//! the printer: an FTPS file upload and a fan-speed change. So it does two
|
||||
//! things before touching anything:
|
||||
//!
|
||||
//! 1. Requires an explicit printer id from the command line. No "do this to
|
||||
//! every printer in the fleet" mode - that's not a thing you want to
|
||||
//! discover you ran.
|
||||
//! 2. Refuses to continue unless that printer reports `gcode_state: "IDLE"`.
|
||||
//! It connects, waits for a real `print.push_status`, and bails out if the
|
||||
//! printer turns out to be mid-job. Sending a fan command to a running
|
||||
//! print would corrupt it.
|
||||
//!
|
||||
//! What it deliberately does **not** do, even on an idle printer:
|
||||
//!
|
||||
//! - **Start a print.** The upload here goes through `upload_file`, which is
|
||||
//! FTPS only. `upload_project_file` (upload *then* print) and
|
||||
//! `start_uploaded_file` are left alone - committing a machine to hours of
|
||||
//! physical work needs a human deciding to.
|
||||
//! - **Calibrate.** `get_calibration` runs a real multi-minute bed-levelling
|
||||
//! / vibration-compensation sequence. Available, intentionally not wired
|
||||
//! in here.
|
||||
//! - **Heat anything.** No temperature commands.
|
||||
//!
|
||||
//! The fan is set and then put back to 0 before exiting.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use continuum_proxy::fleet;
|
||||
use continuum_proxy::printer::{GenericPrinter, PrinterHandle};
|
||||
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
/// How long to wait for the first `push_status` before giving up on knowing
|
||||
/// whether the printer is idle. v2 pushes within about a second; v1 needs the
|
||||
/// `pushall` this example sends first.
|
||||
const STATUS_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let Some(target) = std::env::args().nth(1) else {
|
||||
anyhow::bail!(
|
||||
"usage: cargo run --example bambu_idle_checks -- <printer-id>\n\
|
||||
(the id from printers.toml - required on purpose, this example writes to the printer)"
|
||||
);
|
||||
};
|
||||
|
||||
let mut printers = fleet::load(std::path::Path::new("printers.toml"))?;
|
||||
let printer = printers
|
||||
.iter_mut()
|
||||
.find(|p| p.base().id == target)
|
||||
.ok_or_else(|| anyhow::anyhow!("no printer with id '{target}' in printers.toml"))?;
|
||||
|
||||
let PrinterHandle::Bambu(bambu) = printer else {
|
||||
anyhow::bail!("'{target}' is not a Bambu printer - this example is Bambu-specific");
|
||||
};
|
||||
|
||||
println!("=== {} ===", bambu.display_name());
|
||||
|
||||
match tokio::time::timeout(CONNECT_TIMEOUT, bambu.connect()).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(err)) => anyhow::bail!("connect failed: {err}"),
|
||||
Err(_) => anyhow::bail!("connect timed out - printer off or unreachable?"),
|
||||
}
|
||||
|
||||
// --- Safety gate: is it actually idle? ---
|
||||
// v1 only sends a full object after a pushall; v2 sends one unprompted.
|
||||
bambu.pushall().await.ok();
|
||||
|
||||
let deadline = tokio::time::Instant::now() + STATUS_TIMEOUT;
|
||||
let state = loop {
|
||||
if let Some(report) = bambu.print_status().await {
|
||||
if let Some(state) = report.gcode_state.clone() {
|
||||
break state;
|
||||
}
|
||||
}
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
anyhow::bail!(
|
||||
"no print.push_status with a gcode_state within {STATUS_TIMEOUT:?} - refusing to \
|
||||
send anything, because there's no way to tell whether this printer is busy"
|
||||
);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
};
|
||||
|
||||
println!(" gcode_state: {state}");
|
||||
if state != "IDLE" {
|
||||
anyhow::bail!(
|
||||
"printer reports '{state}', not IDLE - refusing to send write commands to a printer \
|
||||
that may be mid-job. Use the `live_reports` example instead, it's read-only."
|
||||
);
|
||||
}
|
||||
println!(" idle - safe to continue\n");
|
||||
|
||||
// --- 1. FTPS upload (no print start) ---
|
||||
// The real point of this example: the FTPS path in bambu_ftps.rs had
|
||||
// never touched hardware. A tiny text file is enough to prove login,
|
||||
// binary mode, cwd into cache/, and the transfer itself.
|
||||
let file_name = "continuum-ftps-check.txt";
|
||||
let body = format!(
|
||||
"written by continuum-proxy bambu_idle_checks at {:?}\n",
|
||||
std::time::SystemTime::now()
|
||||
);
|
||||
let expected = body.len() as u64;
|
||||
|
||||
println!(" uploading {file_name} ({expected} bytes) over FTPS to cache/ ...");
|
||||
match bambu.upload_file(file_name, body.into_bytes()).await {
|
||||
Ok(written) if written == expected => println!(" OK - {written} bytes, matches what we sent"),
|
||||
Ok(written) => println!(" PARTIAL - printer accepted {written} of {expected} bytes"),
|
||||
Err(err) => println!(" FAILED: {err}"),
|
||||
}
|
||||
|
||||
// --- 2. Fan speed (an MQTT gcode_line publish under the hood) ---
|
||||
// Audible and visible on the machine, and harmless on an idle printer.
|
||||
println!("\n setting part-cooling fan to 50% ...");
|
||||
match bambu.set_fan_speed(50).await {
|
||||
Ok(()) => println!(" sent (M106 P1 S127) - listen for the fan"),
|
||||
Err(err) => println!(" FAILED: {err}"),
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
|
||||
println!(" putting the fan back to 0% ...");
|
||||
match bambu.set_fan_speed(0).await {
|
||||
Ok(()) => println!(" sent"),
|
||||
Err(err) => println!(" FAILED: {err}"),
|
||||
}
|
||||
|
||||
// Give the printer a moment to report the change back, so the fan
|
||||
// reading below reflects the command rather than racing it.
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
if let Some(report) = bambu.print_status().await {
|
||||
println!(
|
||||
"\n cooling_fan_speed now reads: {:?}",
|
||||
report.cooling_fan_speed.as_deref().unwrap_or("?")
|
||||
);
|
||||
}
|
||||
|
||||
println!("\ndone - nothing was printed, calibrated, or heated");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Run with: cargo run --example live_reports
|
||||
//!
|
||||
//! **Read-only. Safe to run against a printer that is mid-print.**
|
||||
//!
|
||||
//! Connects to every Bambu printer in printers.toml, asks each one what
|
||||
//! firmware it's running, then watches its `print.push_status` stream for a
|
||||
//! while. Everything it sends either reads state or asks the printer to
|
||||
//! re-send what it already knows:
|
||||
//!
|
||||
//! - `get_version` - read-only.
|
||||
//! - `pushall` - "re-send the full status object". A request for data,
|
||||
//! not a state change. v1 only; a no-op on v2.
|
||||
//! - `print_status` - reads this process's own in-memory cache, no traffic.
|
||||
//!
|
||||
//! It deliberately sends **no** `gcode_line`, **no** `set_fan_speed`, **no**
|
||||
//! `calibration` (that one starts a physical calibration sequence and would
|
||||
//! wreck a running print), no upload, and nothing that starts or stops a
|
||||
//! job. Keep it that way - the whole point of this example is that it can
|
||||
//! be pointed at a working printer without a second thought. Use
|
||||
//! `bambu_idle_checks` for anything that writes.
|
||||
//!
|
||||
//! The raw payloads are the real output. `PrintReport` models only a small
|
||||
//! fraction of what a real `push_status` carries (see its doc comment), so
|
||||
//! this turns on the `trace`-level raw-payload log in `bambu_mqtt.rs` and
|
||||
//! lets you capture the untouched JSON:
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run --example live_reports 2> capture.jsonl
|
||||
//! ```
|
||||
//!
|
||||
//! Then grow `PrintReport` and `continuum-schemas`' `push_status.schema.json`
|
||||
//! from what's actually in there, rather than from guesses.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use continuum_proxy::fleet;
|
||||
use continuum_proxy::printer::{GenericPrinter, PrinterHandle};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
/// How long to sit and watch each printer's stream before moving on.
|
||||
const WATCH_FOR: Duration = Duration::from_secs(25);
|
||||
/// How often to print a one-line summary of the cached report.
|
||||
const POLL_EVERY: Duration = Duration::from_secs(2);
|
||||
/// A printer that's switched off shouldn't hold the whole run up - the TLS
|
||||
/// handshake inside `connect` has its own 5s timeout, but the MQTT half
|
||||
/// doesn't, so this bounds the lot.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
// Default to trace for the raw-payload target specifically, so a plain
|
||||
// run captures payloads without needing RUST_LOG set by hand. An
|
||||
// explicit RUST_LOG still wins.
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| {
|
||||
EnvFilter::new("info,continuum_proxy::printer::bambu_mqtt=trace")
|
||||
}))
|
||||
.with_writer(std::io::stderr)
|
||||
.init();
|
||||
|
||||
let mut printers = fleet::load(std::path::Path::new("printers.toml"))?;
|
||||
|
||||
// Optional: a printer id to look at just that one. No argument means the
|
||||
// whole fleet. Read-only either way, so there's nothing to guard here.
|
||||
let only: Option<String> = std::env::args().nth(1);
|
||||
|
||||
for printer in &mut printers {
|
||||
if let Some(id) = &only {
|
||||
if &printer.base().id != id {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let PrinterHandle::Bambu(bambu) = printer else {
|
||||
println!("skipping {} - not a Bambu printer", printer.display_name());
|
||||
continue;
|
||||
};
|
||||
|
||||
println!("\n=== {} ===", bambu.display_name());
|
||||
|
||||
match tokio::time::timeout(CONNECT_TIMEOUT, bambu.connect()).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(err)) => {
|
||||
println!(" connect failed: {err}");
|
||||
continue;
|
||||
}
|
||||
Err(_) => {
|
||||
println!(" connect timed out after {CONNECT_TIMEOUT:?} - printer off or unreachable?");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
match bambu.get_version().await {
|
||||
Ok(version) => {
|
||||
println!(" get_version OK: {} modules", version.module.len());
|
||||
for module in &version.module {
|
||||
println!(" {:<12} sw {:<14} hw {}", module.name, module.sw_ver, module.hw_ver);
|
||||
}
|
||||
}
|
||||
Err(err) => println!(" get_version failed: {err}"),
|
||||
}
|
||||
|
||||
// v1 needs this to get a full object at all; it's a no-op on v2 (see
|
||||
// `pushall`'s doc comment). Harmless either way.
|
||||
if let Err(err) = bambu.pushall().await {
|
||||
println!(" pushall failed: {err}");
|
||||
}
|
||||
|
||||
println!(" watching print.push_status for {WATCH_FOR:?}...");
|
||||
let deadline = tokio::time::Instant::now() + WATCH_FOR;
|
||||
// Keyed on the *contents*, not on `sequence_id`. v2 leaves
|
||||
// `sequence_id` pinned at one value while the report genuinely
|
||||
// changes underneath it (confirmed live - see `PrintStatusCache`),
|
||||
// so keying on it reports one update for a whole print.
|
||||
let mut last_seen: Option<String> = None;
|
||||
let mut updates = 0u32;
|
||||
|
||||
while tokio::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(POLL_EVERY).await;
|
||||
|
||||
match bambu.print_status().await {
|
||||
Some(report) => {
|
||||
let seq = report.envelope.sequence_id.clone();
|
||||
let fingerprint = format!(
|
||||
"{:?}|{:?}|{:?}|{:?}|{:?}|{:?}",
|
||||
report.gcode_state,
|
||||
report.mc_percent,
|
||||
report.layer_num,
|
||||
report.mc_remaining_time,
|
||||
report.nozzle_temper,
|
||||
report.bed_temper
|
||||
);
|
||||
let changed = last_seen.as_ref() != Some(&fingerprint);
|
||||
if changed {
|
||||
updates += 1;
|
||||
last_seen = Some(fingerprint);
|
||||
}
|
||||
println!(
|
||||
" seq={seq:<6} {:<8} {:>3}% layer {}/{} {} min left nozzle {:.1}/{:.1}C bed {:.1}/{:.1}C{}",
|
||||
report.gcode_state.as_deref().unwrap_or("?"),
|
||||
report.mc_percent.unwrap_or(0),
|
||||
report.layer_num.unwrap_or(0),
|
||||
report.total_layer_num.unwrap_or(0),
|
||||
report.mc_remaining_time.unwrap_or(0),
|
||||
report.nozzle_temper.unwrap_or(0.0),
|
||||
report.nozzle_target_temper.unwrap_or(0.0),
|
||||
report.bed_temper.unwrap_or(0.0),
|
||||
report.bed_target_temper.unwrap_or(0.0),
|
||||
if changed { "" } else { " (unchanged)" }
|
||||
);
|
||||
if let Some(job) = report.subtask_name.as_deref().filter(|s| !s.is_empty()) {
|
||||
println!(" job: {job}");
|
||||
}
|
||||
if let Some(hms) = report.hms.as_ref().filter(|h| !h.is_empty()) {
|
||||
println!(" hms: {} active entr(y/ies)", hms.len());
|
||||
}
|
||||
println!(
|
||||
" fans: cooling={} heatbreak={} big1={} big2={} wifi={}",
|
||||
report.cooling_fan_speed.as_deref().unwrap_or("?"),
|
||||
report.heatbreak_fan_speed.as_deref().unwrap_or("?"),
|
||||
report.big_fan1_speed.as_deref().unwrap_or("?"),
|
||||
report.big_fan2_speed.as_deref().unwrap_or("?"),
|
||||
report.wifi_signal.as_deref().unwrap_or("?")
|
||||
);
|
||||
}
|
||||
// Reaching here now means genuinely nothing arrived. It used
|
||||
// to also mean "something arrived and failed to parse",
|
||||
// which is why a mid-print H2C once looked completely
|
||||
// silent - see `handle_incoming_report`.
|
||||
None => println!(" no push_status received yet"),
|
||||
}
|
||||
}
|
||||
|
||||
println!(" {updates} distinct push_status update(s) in {WATCH_FOR:?}");
|
||||
}
|
||||
|
||||
println!("\ndone - raw payloads went to stderr (redirect it to capture them)");
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user