Compare commits
20
Commits
2c1fd27dc6
..
main
No files matched your search
@@ -0,0 +1,3 @@
|
||||
[submodule "external/aldis"]
|
||||
path = external/aldis
|
||||
url = https://github.com/mjonuschat/aldis.git
|
||||
@@ -10,8 +10,10 @@ Voron 2.4 350, Klipper + Moonraker + Mainsail on a Raspberry Pi 4
|
||||
(`http://mainsailos.local`, Moonraker API on port 80). AFC Box Turtle with
|
||||
5 lanes, Blobifier purge bucket, Beacon (Z homing and probing), Nitehawk-SB
|
||||
toolboard (USB), Leviathan mainboard as USB-CAN bridge, bd_pressure
|
||||
(load-check firmware, branch `load-check-extension` in
|
||||
`D:\Claude\bd_pressure-load-check\bd_pressure`), bdwidth (CCD width/motion sensor on USB; switched off: its motion reading
|
||||
(load-check firmware; `bdpressure.py`, `bdpressure_check.py` and `bdp_guard.py`
|
||||
come from the fork `https://github.com/MangaValk/bd_pressure`, local clone
|
||||
`D:\Claude\bd_pressure`, branch `main`, installed on the Pi in `~/bd_pressure`),
|
||||
bdwidth (CCD width/motion sensor on USB; switched off: its motion reading
|
||||
stays at 0, its width compensation made the flow jump 77-119% and a USB
|
||||
dropout once shut down Klipper. The macros work with or without
|
||||
`[bdwidth fila_width_0]`; clogs and breaks are caught by AFC's buffer fault
|
||||
@@ -37,7 +39,14 @@ detection, `filament_error_sensitivity`), iHeater chamber heater.
|
||||
On the Pi, `macros/` is linked as `~/printer_data/config/klipper-macros/`
|
||||
and `scripts/` as `~/printer_data/config/klipper-macros-scripts/`.
|
||||
- `extras/*.py` are linked into `~/klipper/klippy/extras/`.
|
||||
- `scripts/` MCU firmware update scripts (printer-specific IDs).
|
||||
- MCU firmware: aldis (`external/aldis`, git submodule pinned to the release in
|
||||
use, v0.4.0; the Pi runs the released binary in `~/aldis`). Bump the
|
||||
submodule when the Pi's aldis is updated.
|
||||
- `scripts/` Katapult update script (printer-specific IDs), the archived Klipper
|
||||
update script in `scripts/archive/`, and
|
||||
`twist_check.py` (axis twist calibration, runs on the Pi and talks to
|
||||
Moonraker on localhost; started by `TWIST_CALIBRATE` in
|
||||
`macros/calibration/twist_check.cfg`, results in `config/twist_data/`).
|
||||
- `tools/effective_config.py` expands the includes like Klipper and compares
|
||||
the result between git refs.
|
||||
|
||||
@@ -54,7 +63,19 @@ detection, `filament_error_sensitivity`), iHeater chamber heater.
|
||||
After a PAUSE, `_RESUME_PRINT` first purges with `BLOBIFIER_CHECKED`
|
||||
(`_RESUME_PURGE`); a failed check raises an error, which aborts the whole
|
||||
chain (AFC_RESUME's restore too), so the printer stays paused.
|
||||
- A failed bed check in `PRINT_START` (`calibration/bed_scan_check.cfg`) pauses
|
||||
with `_BED_CHECK_STATE.pending` set: `PAUSE` then only pauses, and `RESUME`
|
||||
calls `_BED_CHECK_RETRY`, which sets the print file back to the `PRINT_START`
|
||||
line (`M26`) and resumes. Everything after the check belongs in
|
||||
`_PRINT_START_FINISH`: a pause does not stop a running macro.
|
||||
- An AFC infinite spool swap pauses and resumes the file without the PAUSE and
|
||||
RESUME macros and only stops on AFC's own error state, so PAUSE cannot stop it.
|
||||
During a swap `print_stats.state` is paused with `pause_resume.is_paused` False;
|
||||
a failed purge check then raises an error (`_PURGE_CHECK_SWAP_STOP`).
|
||||
- Only one `[save_variables]`, in `macros/save_variables.cfg`.
|
||||
- PA values are saved per nozzle and spool (`pa_value_0_4_spool_<id>`), the fitted
|
||||
size in `pa_nozzle` (`SET_NOZZLE`). The slicer's `NOZZLE=` on `PRINT_WARMUP` must
|
||||
match, or the print stops. A new size needs an entry in `_PA_CFG.nozzle_test`.
|
||||
- `PRINT_END` and `CANCEL_PRINT` share `_PRINT_CLEANUP` (heaters including
|
||||
`iHEATER_OFF`, fan, `M221 S100`, bdwidth off). Anything that must happen
|
||||
at the end of every print goes there. `RESTORE_GCODE_STATE` restores the
|
||||
@@ -70,7 +91,7 @@ detection, `filament_error_sensitivity`), iHeater chamber heater.
|
||||
not `action_raise_error` / `RESPOND TYPE=error`, so they also show on the
|
||||
display. `action_raise_error` aborts while rendering, so an `M117` in the
|
||||
same macro would never run. No double quotes in `MSG`/`DISPLAY`.
|
||||
- Nozzle guard (`print/nozzle_guard.cfg`, `extras/bdp_guard.py`): wrap only
|
||||
- Nozzle guard (`print/nozzle_guard.cfg`, `bdp_guard.py` in the bd_pressure repo): wrap only
|
||||
moves where nothing may touch the nozzle in `_GUARD_ON PHASE=x` /
|
||||
`_GUARD_OFF`. Never leave it on across contact homing, extrusion, purges,
|
||||
the Blobifier park or AFC cuts and loads: in `mode: stop` that is an
|
||||
@@ -103,6 +124,9 @@ detection, `filament_error_sensitivity`), iHeater chamber heater.
|
||||
in log mode); a light finger push on the cold nozzle gives 41
|
||||
(threshold 30).
|
||||
- Z check after a contact homing: Beacon vs Klipper Z about 0.06 mm.
|
||||
- Bed check (mesh_check, limits 0.03 and 0.30 mm): clean plate, worst deviation
|
||||
0.016 mm cold and on a hot PLA print, range 0.12-0.17. Residue on the plate:
|
||||
0.06-0.09 mm with the mesh ending at its edge, 0.30 mm with the mesh over it.
|
||||
- XY drift check: endstop noise about 0.01-0.02 mm; limit 0.1 mm (one motor
|
||||
skipping one cycle = 0.4 mm shows as 0.2 mm in X and Y).
|
||||
|
||||
|
||||
@@ -25,24 +25,25 @@ everything below, grouped by topic. Comment out what you do not use there.
|
||||
| `pause_resume.cfg` | `PAUSE`, `RESUME`, `CANCEL_PRINT`, `M600` (RESUME also handles a running `HEAT_SOAK`, and after a PAUSE purges 40 mm with `BLOBIFIER_CHECKED` first: a failed check keeps the print paused, `RESUME PURGE=0` skips the purge; CANCEL_PRINT runs the same cleanup as `PRINT_END`) | `heating/heat_soak.cfg`, `leds/`, `blobifier/`, `afc/purge_check.cfg` |
|
||||
| `filament.cfg` | `LOAD_FILAMENT`, `UNLOAD_FILAMENT` | — |
|
||||
| `homing.cfg` | `HOME`: X/Y, then Z always with Beacon contact (also when already homed); `_Z_CHECK`: stops the print when Klipper's Z and the Beacon reading differ (run in `PRINT_START` after the soak) | Beacon |
|
||||
| `nozzle_guard.cfg` | `[bdp_guard]`, `_GUARD_ON PHASE=<name>`, `_GUARD_OFF`: bd_pressure watches the nozzle force during print-start moves where nothing should touch it (QGL, Z homing, mesh); `mode: stop` shuts Klipper down on a touch (the brush runs log-only), `mode: log` only reports the peak per phase | `extras/bdp_guard.py` + bd_pressure load-check firmware |
|
||||
| `nozzle_guard.cfg` | `[bdp_guard]`, `_GUARD_ON PHASE=<name>`, `_GUARD_OFF`: bd_pressure watches the nozzle force during print-start moves where nothing should touch it (QGL, Z homing, mesh); `mode: stop` shuts Klipper down on a touch (the brush runs log-only), `mode: log` only reports the peak per phase | `bdp_guard.py` from the bd_pressure repo + its load-check firmware |
|
||||
| `test_speed.cfg` | `TEST_SPEED`: skipped-steps test for speed and acceleration | — |
|
||||
| `idle_timeout.cfg` | `[idle_timeout]`: heaters, chamber heater and motors off | iHeater macros |
|
||||
| **heating/** | | |
|
||||
| `heat_soak.cfg` | `HEAT_SOAK`, `STOP_HEAT_SOAK`, `CANCEL_HEAT_SOAK`, `HEAT_SOAK_RESUME`, `RESUME` | — |
|
||||
| `soak_my_bed.cfg` | `SOAK_MY_BED` (homes and levels first) | soak-my-bed |
|
||||
| `bed_fans.cfg` | Bed fans through `SET_HEATER_TEMPERATURE`/`M190`/`M140`/`TURN_OFF_HEATERS` overrides | `[fan_generic BedFans]` |
|
||||
| `bed_fans.cfg` | Bed fans through `SET_HEATER_TEMPERATURE`/`M190`/`M140`/`TURN_OFF_HEATERS` overrides; off during a print without a heated chamber (`PRINT_WARMUP CHAMBER=` 30 or less), on during the cooldown after any print | `[fan_generic BedFans]` |
|
||||
| `chamber_iheater.cfg` | iHeater MCU, heater and sensors, `M141`, `M191`, `iHEATER_ON`, `iHEATER_OFF` | iHeater chamber heater |
|
||||
| `filament_drying.cfg` | `START_DRYING`, `STOP_DRYING`, `STATUS_DRYING` | bed fans, chamber heater (optional) |
|
||||
| **afc/** | | |
|
||||
| `xy_safety_check.cfg` | `AFC_XY_SAFETY_CHECK`, `_AFC_STORE_HOME_REFERENCE`, `AFC_XY_RESUME`: lost-step check around tool changes | `extras/xy_drift.py` (CoreXY) |
|
||||
| `lane_tools.cfg` | `LANE_FEED_UNTIL_HUB_OPEN`, `LANE_FEED_ABORT` | AFC |
|
||||
| `purge_check.cfg` | `BLOBIFIER_CHECKED`: checks every AFC purge with bd_pressure (and optionally bdwidth motion); a bd_pressure that does not answer fails the check, `PURGE_CHECK_IGNORE_SENSOR` lets the current print finish without it; when the previous filament (saved `nozzle_last_temp`) needs more than 10°C above the new one, the purge runs at the previous filament's temperature and the nozzle cools back afterwards, so its leftover melts out | Blobifier, AFC, `extras/bdpressure_check.py` + bd_pressure load-check firmware, `extras/bdwidth_status.py` |
|
||||
| `purge_check.cfg` | `BLOBIFIER_CHECKED`: checks every AFC purge with bd_pressure (and optionally bdwidth motion); a bd_pressure that does not answer fails the check, `PURGE_CHECK_IGNORE_SENSOR` lets the current print finish without it; when the previous filament (saved `nozzle_last_temp`) needs more than 10°C above the new one, the purge runs at the previous filament's temperature and the nozzle cools back afterwards, so its leftover melts out | Blobifier, AFC, `bdpressure_check.py` from the bd_pressure repo + its load-check firmware, `extras/bdwidth_status.py` |
|
||||
| `flex_lanes.cfg` | Lanes holding TPU/TPE (material from Spoolman) get slower long moves (50 mm/s, AFC's minimum) through the tube; back to the configured speed when the lane holds something else. Polls every 5 s, reapplies after a restart. The last stretch into the extruder (`tool_load_speed`) stays as configured | AFC |
|
||||
| `auto_resume.cfg` | After an AFC "NOT FEEDING" buffer fault pause during a print (not "CLOG DETECTED": usually a real blockage), runs `RESUME` by itself after 5 s, so the lane check and the purge check decide; a failed check keeps it paused. At most 2 per print and none within 10 min of printing after the previous one; not during `PRINT_START` or a PA test. Off: `enabled` in `_AUTO_RESUME_CFG` | `print/pause_resume.cfg`, `purge_check.cfg`, AFC |
|
||||
| `purge_until_empty.cfg` | `PURGE_UNTIL_EMPTY`: purges a snapped filament out until there is no more nozzle pressure | same as `purge_check.cfg` |
|
||||
| **pressure_advance/** | | |
|
||||
| `bd_pressure.cfg` | `[bdpressure bd_pa]` (I2C on the Nitehawk) and the vendor macros `PA_CALIBRATE`, `PA_E`, `PA_RESET`, `PA_STATE`; `PA_CALIBRATE` no longer sets Z back to a value read before the test (wrong after a Z hop in `G28 XY`) | `bdpressure.py` from the bd_pressure repo |
|
||||
| `bd_pa_spoolman.cfg` + `bd_pa_*.sh` | `LANE_CALIBRATE_PA`, `PA_CALIBRATE_ALL_LANES`, `LANE_RECAL_PA`, `SET_SPOOL_ID`, `PA_STATUS`: pressure advance per lane/spool, cached locally and in Spoolman; before a calibration the lane's spool is assigned again so a temperature just changed in Spoolman is used; flexible materials (TPU/TPE) calibrate at a lower flow (8 mm³/s) and over a wider PA range (0–0.196 in 0.004 steps instead of 0–0.098); a calibration with no result, a pause during the test or too few/stuck sensor readings is rejected and not saved | bd_pressure, AFC, Spoolman, `gcode_shell_command` |
|
||||
| `bd_pa_spoolman.cfg` | `LANE_CALIBRATE_PA`, `PA_CALIBRATE_ALL_LANES`, `LANE_RECAL_PA`, `SET_SPOOL_ID`, `PA_STATUS`, `SET_NOZZLE`: pressure advance per nozzle and spool, saved on the printer; run `SET_NOZZLE SIZE=0.2` after a swap (a print start stops if the slicer profile has another size); each nozzle has its own test flow and PA range (0.4: 25 mm³/s, 0–0.098, about 2 min a lane; 0.2: 5 mm³/s, 0–0.196, about 9 min, not measured yet); before a calibration the lane's spool is assigned again so a temperature just changed in Spoolman is used; flexible materials (TPU/TPE) calibrate at a lower flow (8 mm³/s) and over a wider PA range (0–0.196 in 0.004 steps instead of 0–0.098); a calibration with no result, a pause during the test or too few/stuck sensor readings is rejected and not saved | bd_pressure, AFC, Spoolman through AFC |
|
||||
| **spoolman/** | | |
|
||||
| `active_spool.cfg` | `SET_ACTIVE_SPOOL`, `CLEAR_ACTIVE_SPOOL` | Spoolman in Moonraker |
|
||||
| **leds/** | | |
|
||||
@@ -51,21 +52,36 @@ everything below, grouped by topic. Comment out what you do not use there.
|
||||
| `motion_sensor.cfg` | PIR motion sensor: case light and nozzle LEDs on while someone is near (timeout from the last motion), `CASELIGHT MODE=AUTO\|ON\|OFF`; runs outside the G-code queue, so the lights also react during heat waits and AFC loads | `extras/motion_lights.py`, sensor on a pin, `[output_pin caselight]`, `leds/stealthburner_leds.cfg` |
|
||||
| `touch_compare.cfg` | `[bdp_touch]`, `TOUCH_COMPARE [N=10] [X] [Y] [TEMP=150]`: nozzle to 150C, `HOME`, then N pairs of a Beacon contact probe and a bd_pressure touch at one spot; reports mean, spread and range of each and of the difference | `extras/bdp_touch.py` + bd_pressure load-check firmware, Beacon |
|
||||
|
||||
| **calibration/** | | |
|
||||
| `twist_check.cfg` + `scripts/twist_check.py` | `TWIST_CALIBRATE`: axis twist calibration from Mainsail with windows that explain each step. Measure (25 min) says whether new `[axis_twist_compensation]` values are needed, Verify (17 min) checks them with bd_pressure. Progress on the status line, result in a window, HTML report with charts in `config/twist_data/`. Never changes `printer.cfg`. `TWIST_STOP` stops a run. | Beacon, `[axis_twist_compensation]`, `gcode_shell_command`, Mainsail prompts; Verify also `bdp_touch.py` |
|
||||
| `bed_scan_check.cfg` | `BED_SCAN_CHECK [BUMP=0.03] [RANGE=0.30]`: levels, scans and warns about bumps, dips or too much height range, without heating or touching the bed. In `PRINT_START` a failed check pauses before the nozzle heats and moves the toolhead away: clean the plate and Resume, which runs `PRINT_START` again from QGL with a new scan and check. `BED_CHECK_IGNORE`, then Resume: the next failed check only warns | `extras/mesh_check.py`, Beacon, AFC |
|
||||
|
||||
### Klipper modules (`extras/`)
|
||||
|
||||
| File | For |
|
||||
|---|---|
|
||||
| `xy_drift.py` | `AFC_XY_SAFETY_CHECK`: measures lost XY steps from the stepper step counts at the endstop triggers (CoreXY). The toolhead position after homing cannot show lost steps. |
|
||||
| `bdwidth_status.py` | exposes bdwidth's motion counter and width to macros (`present: False` with neutral values when no bdwidth is configured, so the macros also work without it), and keeps a USB dropout of bdwidth (port: usb) from shutting down Klipper: the read is retried every 10 s and the port reopened |
|
||||
| `bdpressure_check.py` | bd_pressure load check (`BDP_CHECK_START/STOP/QUERY`). Needs the load-check firmware from the bd_pressure `load-check-extension` branch; on stock firmware it reports "not available" and does nothing. Also reports how many readings the last `PA_CALIBRATE` got (`pa_points`, `pa_distinct`), used to reject runs with a silent or stuck sensor. |
|
||||
| `bdp_guard.py` | nozzle collision guard: while armed (`BDP_GUARD_ARM/DISARM/QUERY`) reads the bd_pressure force every 20 ms over I2C and, in stop mode, shuts Klipper down when it stays above the threshold. Reports reads, peak and errors per phase in the console and klippy.log. When it arms and finds the sensor still in PA mode (an emergency stop during `PA_CALIBRATE`; `FIRMWARE_RESTART` does not reset the sensor), it switches it to probe mode and takes a new zero first. Puts a lock on the sensor's I2C connection that `bdpressure.py` and `bdpressure_check.py` also go through (Klipper allows one I2C request at a time per device). Needs the load-check firmware. |
|
||||
| `bdp_touch.py` | `BDP_TOUCH`: lowers the nozzle in one slow continuous move (drip mode, like a homing move) while reading the bd_pressure force as fast as I2C allows (its endstop output is not wired), stops at a force limit (default 60) or 0.5 mm below the start, then lifts back; it must be one quick press, because the sensor re-zeros itself while the force looks steady; reports the height where the force reaches the threshold and the zero-force height from a line fit, and logs the whole curve to klippy.log. `_TOUCH_COMPARE`: alternates that with Beacon's contact probe. Refuses while the bdp_guard is armed or the sensor is in PA mode. Needs the load-check firmware. |
|
||||
| `mesh_check.py` | `BED_MESH_CHECK`: fits a smooth surface to the loaded mesh and reports the height range and every area further from it than the limit, with its position. Only reads the mesh. Needs numpy (Beacon needs it too). |
|
||||
|
||||
The bd_pressure load check (`bdpressure_check.py`: `BDP_CHECK_START/STOP/QUERY`,
|
||||
`pa_points`/`pa_distinct`) and nozzle guard (`bdp_guard.py`: `BDP_GUARD_ARM/DISARM/QUERY`)
|
||||
moved to the bd_pressure repo (`https://github.com/MangaValk/bd_pressure`, folder
|
||||
`klipper/`, docs in `klipper/load_check/README.md`). Install that repo with its
|
||||
`klipper/install.sh` and its own `[update_manager bd_pressure]` entry; the macros
|
||||
here (`purge_check.cfg`, `nozzle_guard.cfg`, `bd_pa_spoolman.cfg`) still use them.
|
||||
|
||||
### Scripts (`scripts/`)
|
||||
|
||||
Firmware update scripts for all MCUs (Klipper and Katapult). They contain
|
||||
this printer's CAN UUIDs and serial IDs: see [scripts/README.md](scripts/README.md)
|
||||
before using them on another printer.
|
||||
MCU firmware: Klipper on the MCUs is updated with
|
||||
[aldis](https://github.com/mjonuschat/aldis), included as a git submodule in
|
||||
`external/aldis` (pinned to the release in use; on the Pi run the released
|
||||
program in `~/aldis`). Install and use: [scripts/README.md](scripts/README.md).
|
||||
The old Klipper update script is in `scripts/archive/`; the Katapult script
|
||||
(`update_katapult_all_mcus.sh`, this printer's CAN UUIDs and serial IDs) is
|
||||
still used for the bootloaders. `twist_check.py` is the axis twist
|
||||
calibration behind `TWIST_CALIBRATE`: see [scripts/twist_check.md](scripts/twist_check.md).
|
||||
|
||||
### Tools (`tools/`)
|
||||
|
||||
@@ -137,7 +153,7 @@ These are the settings of one printer. Before using a file, check:
|
||||
- **Settings at the top of a file** (`variable_...`): `afc/purge_check.cfg`
|
||||
(`mode: "enforce"`, `motion_check: False` because this printer's bdwidth
|
||||
motion reading is unreliable), `pressure_advance/bd_pa_spoolman.cfg`
|
||||
(`spoolman_url`), `heating/bed_fans.cfg`, `heating/filament_drying.cfg`.
|
||||
(`nozzle_test`), `heating/bed_fans.cfg`, `heating/filament_drying.cfg`.
|
||||
- `xy_drift.py` is for CoreXY only.
|
||||
|
||||
Comment out files you do not need in `klipper-macros.cfg`.
|
||||
@@ -168,6 +184,7 @@ original licenses apply to those parts:
|
||||
| `pressure_advance/bd_pressure.cfg` | [bd_pressure](https://github.com/markniu/bd_pressure) `klipper/bd_pressure.cfg` |
|
||||
| `print/test_speed.cfg` | [Ellis' TEST_SPEED](https://ellis3dp.com/Print-Tuning-Guide/articles/determining_max_speeds_accels.html) |
|
||||
| `print/pause_resume.cfg`, `print/filament.cfg` | [KlipperScreen recommended macros](https://klipperscreen.readthedocs.io/en/latest/macros/#recommended) |
|
||||
| `external/aldis` | [aldis](https://github.com/mjonuschat/aldis) by mjonuschat, GPL-3.0 (git submodule, unchanged) |
|
||||
| `scripts/` | [Voron docs: automating MCU updates](https://docs.vorondesign.com/community/howto/drachenkatze/automating_klipper_mcu_updates.html), [Esoterical's CANBus guide](https://canbus.esoterical.online/) |
|
||||
|
||||
Uses: [Klipper](https://github.com/Klipper3d/klipper),
|
||||
|
||||
+1
Submodule external/aldis added at 607c8db1b0.
@@ -1,283 +0,0 @@
|
||||
# Nozzle collision guard with bd_pressure (load-check firmware extension).
|
||||
#
|
||||
# The bd_pressure strain gauge sees the force on the nozzle. The load-check
|
||||
# firmware keeps the current force minus its baseline in register 64-65
|
||||
# (chk_delta), also outside a load check; it is the same value the endstop
|
||||
# output switches on (|delta| >= thrhold). While the guard is armed this
|
||||
# module reads it every INTERVAL seconds. In stop mode, SAMPLES reads in a
|
||||
# row at or above THRESHOLD shut Klipper down at once (like M112, without
|
||||
# waiting for the running macro to finish).
|
||||
#
|
||||
# Every ARM (also a phase switch) first sets a new zero (register 52), so
|
||||
# slow pressure changes before the guarded moves do not count (TPU in a
|
||||
# nozzle that heats up keeps changing pressure for minutes).
|
||||
#
|
||||
# Arm it only around moves where the nozzle must not touch anything: not
|
||||
# around contact homing, extrusion, purges or AFC cuts and loads, which
|
||||
# press on the nozzle on purpose. ARM and DISARM act immediately, not in
|
||||
# the move queue: put an M400 before them (the _GUARD_ON/_GUARD_OFF macros
|
||||
# do this).
|
||||
#
|
||||
# Install: copy to ~/klipper/klippy/extras/bdp_guard.py and add
|
||||
#
|
||||
# [bdp_guard]
|
||||
# sensor: bd_pa # name after "bdpressure" in [bdpressure bd_pa]
|
||||
# mode: log # log: only measure; stop: shut down on a touch
|
||||
# threshold: 30 # |delta| that counts as a touch
|
||||
# samples: 3 # reads in a row at or above threshold
|
||||
# interval: 0.02 # seconds between reads while armed
|
||||
# timeout: 600 # disarm by itself when a phase runs this long
|
||||
# # (a macro that failed before its DISARM)
|
||||
#
|
||||
# Commands:
|
||||
# BDP_GUARD_ARM PHASE=<name> [MODE=log|stop] start (or switch phase)
|
||||
# BDP_GUARD_DISARM stop and report the phase
|
||||
# BDP_GUARD_QUERY report without stopping
|
||||
#
|
||||
# Each phase reports (console and klippy.log, "bdp_guard:") the reads, the
|
||||
# peak |delta|, the longest run of reads at or above threshold and the
|
||||
# read errors, so a log-mode print start shows what each phase normally
|
||||
# measures before stop mode is switched on.
|
||||
#
|
||||
# Status (printer.bdp_guard): armed, mode, phase, threshold, samples, peak,
|
||||
# longest_run, reads, errors, available
|
||||
|
||||
import logging
|
||||
|
||||
REG_MODE = 48 # status_clk: 7 = PA mode, 2 = probe (endstop) mode
|
||||
REG_RESET_PROBE = 52 # set_normal: write 1 = take the current reading as zero
|
||||
MODE_PA = 7
|
||||
REG_EXT = 54 # extension marker 0xBD + version
|
||||
REG_DELTA = 64 # chk_delta, int16 little-endian
|
||||
EXT_MAGIC = 0xBD
|
||||
MODES = ('log', 'stop')
|
||||
|
||||
|
||||
# Klipper allows only one I2C request at a time per device: a second one
|
||||
# while the first waits for its answer raises KeyError ('i2c_response', oid)
|
||||
# and shuts Klipper down. The guard reads from a timer while G-code runs,
|
||||
# and bdpressure.py writes the probe mode at every homing move (seen: G28
|
||||
# during an armed guard), so all transfers of the sensor take this lock.
|
||||
# The guard puts it on the sensor object at connect; bdpressure and
|
||||
# bdpressure_check use sensor.i2c and so get it too.
|
||||
class LockedI2C:
|
||||
def __init__(self, i2c, mutex):
|
||||
self._i2c = i2c
|
||||
self._mutex = mutex
|
||||
|
||||
def i2c_read(self, *args, **kwargs):
|
||||
with self._mutex:
|
||||
return self._i2c.i2c_read(*args, **kwargs)
|
||||
|
||||
def i2c_write(self, *args, **kwargs):
|
||||
with self._mutex:
|
||||
return self._i2c.i2c_write(*args, **kwargs)
|
||||
|
||||
def i2c_write_wait_ack(self, *args, **kwargs):
|
||||
with self._mutex:
|
||||
return self._i2c.i2c_write_wait_ack(*args, **kwargs)
|
||||
|
||||
def i2c_transfer(self, *args, **kwargs):
|
||||
with self._mutex:
|
||||
return self._i2c.i2c_transfer(*args, **kwargs)
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._i2c, name)
|
||||
|
||||
|
||||
class BDPGuard:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
self.reactor = self.printer.get_reactor()
|
||||
self.sensor_name = 'bdpressure ' + config.get('sensor', 'bd_pa')
|
||||
self.mode = config.getchoice('mode', {m: m for m in MODES}, 'log')
|
||||
self.threshold = config.getint('threshold', 30, minval=1)
|
||||
self.samples = config.getint('samples', 3, minval=1)
|
||||
self.interval = config.getfloat('interval', 0.02, minval=0.005)
|
||||
self.timeout = config.getfloat('timeout', 600., minval=10.)
|
||||
self.armed_until = 0.
|
||||
self.sensor = self.i2c = None
|
||||
self.available = False
|
||||
self.timer = None
|
||||
self.zeroing = False
|
||||
self.phase_mode = self.mode
|
||||
self._reset_phase('')
|
||||
self.printer.register_event_handler('klippy:connect',
|
||||
self._handle_connect)
|
||||
self.printer.register_event_handler('klippy:shutdown',
|
||||
self._handle_shutdown)
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
gcode.register_command('BDP_GUARD_ARM', self.cmd_ARM,
|
||||
desc="Arm the bd_pressure nozzle collision guard")
|
||||
gcode.register_command('BDP_GUARD_DISARM', self.cmd_DISARM,
|
||||
desc="Disarm the bd_pressure nozzle collision guard")
|
||||
gcode.register_command('BDP_GUARD_QUERY', self.cmd_QUERY,
|
||||
desc="Report the bd_pressure guard values")
|
||||
|
||||
def _handle_connect(self):
|
||||
self.sensor = self.printer.lookup_object(self.sensor_name, None)
|
||||
i2c = getattr(self.sensor, 'i2c', None)
|
||||
if i2c is not None and not isinstance(i2c, LockedI2C):
|
||||
# Every user of the sensor (bdpressure, bdpressure_check, this
|
||||
# guard) now goes through one lock, see LockedI2C
|
||||
i2c = LockedI2C(i2c, self.reactor.mutex())
|
||||
self.sensor.i2c = i2c
|
||||
self.i2c = i2c
|
||||
|
||||
def _handle_shutdown(self):
|
||||
self._stop_timer()
|
||||
|
||||
def _reset_phase(self, phase):
|
||||
self.phase = phase
|
||||
self.peak = self.longest_run = self.run = 0
|
||||
self.reads = self.errors = 0
|
||||
|
||||
def _check_available(self):
|
||||
if self.i2c is None:
|
||||
return False
|
||||
try:
|
||||
data = bytearray(self.i2c.i2c_read([REG_EXT], 2)['response'])
|
||||
except Exception:
|
||||
logging.exception("bdp_guard: reading the extension marker failed")
|
||||
return False
|
||||
return len(data) == 2 and data[0] == EXT_MAGIC and data[1] >= 1
|
||||
|
||||
def _ensure_probe_mode(self, gcmd):
|
||||
# An emergency stop during PA_CALIBRATE leaves the sensor in PA mode
|
||||
# (FIRMWARE_RESTART does not reset it); bdpressure.py only switches
|
||||
# it back at the next homing move, after the guard is armed. In PA
|
||||
# mode the delta means nothing and could trip the guard. Register 48
|
||||
# is the mode: 7 = PA, 2 = probe.
|
||||
if getattr(self.sensor, 'last_state', 0):
|
||||
return # a calibration runs, leave the sensor alone
|
||||
try:
|
||||
mode = bytearray(self.i2c.i2c_read([REG_MODE], 1)['response'])
|
||||
if len(mode) != 1 or mode[0] != MODE_PA:
|
||||
return
|
||||
self.sensor.set_probe_mode()
|
||||
# new samples at the probe sample rate, then a fresh baseline
|
||||
self.reactor.pause(self.reactor.monotonic() + 0.5)
|
||||
self.i2c.i2c_write([REG_RESET_PROBE, 1])
|
||||
self.reactor.pause(self.reactor.monotonic() + 0.3)
|
||||
except Exception:
|
||||
logging.exception("bdp_guard: switching the sensor to probe mode failed")
|
||||
return
|
||||
msg = ("BDP_GUARD: bd_pressure was still in PA mode (stopped "
|
||||
"calibration?), switched to probe mode")
|
||||
logging.info(msg)
|
||||
gcmd.respond_info(msg)
|
||||
|
||||
def _rezero(self):
|
||||
# A fresh zero at every ARM: only force that appears during the
|
||||
# guarded moves counts, not slow changes before them. Seen with TPU
|
||||
# in a nozzle heating to 150C: the pressure kept rising (+43) or
|
||||
# falling as it oozed (-56) for minutes, faster than the sensor's
|
||||
# own baseline update (only when steady, about every 7 s), and
|
||||
# stopped the printer at the start of a phase with the nozzle in
|
||||
# the air. ARM comes after M400, with the nozzle clear of
|
||||
# everything, so this does not hide a real touch.
|
||||
self.zeroing = True
|
||||
try:
|
||||
self.i2c.i2c_write([REG_RESET_PROBE, 1])
|
||||
self.reactor.pause(self.reactor.monotonic() + 0.2)
|
||||
except Exception:
|
||||
logging.exception("bdp_guard: setting a new zero failed")
|
||||
self.zeroing = False
|
||||
|
||||
def _stop_timer(self):
|
||||
if self.timer is not None:
|
||||
self.reactor.unregister_timer(self.timer)
|
||||
self.timer = None
|
||||
|
||||
def _poll(self, eventtime):
|
||||
# Never raise here: an exception in a timer shuts Klipper down.
|
||||
try:
|
||||
if self.printer.is_shutdown():
|
||||
return self.reactor.NEVER
|
||||
if eventtime > self.armed_until:
|
||||
logging.info("bdp_guard: %s armed longer than %.0f s, "
|
||||
"disarmed (%d reads, peak %d)", self.phase,
|
||||
self.timeout, self.reads, self.peak)
|
||||
self._stop_timer()
|
||||
self.phase = ''
|
||||
return self.reactor.NEVER
|
||||
# PA mode (SET_BDPRESSURE START): the delta means nothing then;
|
||||
# while ARM sets a new zero the readings are in between
|
||||
if self.zeroing or getattr(self.sensor, 'last_state', 0):
|
||||
return eventtime + self.interval
|
||||
data = bytearray(self.i2c.i2c_read([REG_DELTA], 2)['response'])
|
||||
if len(data) != 2:
|
||||
self.errors += 1
|
||||
return eventtime + self.interval
|
||||
delta = data[0] | (data[1] << 8)
|
||||
if delta & 0x8000:
|
||||
delta -= 0x10000
|
||||
mag = abs(delta)
|
||||
self.reads += 1
|
||||
self.peak = max(self.peak, mag)
|
||||
self.run = self.run + 1 if mag >= self.threshold else 0
|
||||
self.longest_run = max(self.longest_run, self.run)
|
||||
if self.run >= self.samples and self.phase_mode == 'stop':
|
||||
# klippy:shutdown unregisters this timer
|
||||
self.printer.invoke_shutdown(
|
||||
"bd_pressure guard: nozzle touched something during %s "
|
||||
"(delta %d, threshold %d)"
|
||||
% (self.phase or 'an armed move', delta, self.threshold))
|
||||
return self.reactor.NEVER
|
||||
except Exception:
|
||||
self.errors += 1
|
||||
if self.errors == 1: # 50 reads/s: only the first per phase
|
||||
logging.exception("bdp_guard: read failed")
|
||||
return eventtime + self.interval
|
||||
|
||||
def _report(self, gcmd, prefix):
|
||||
msg = ("%s %s (%s): %d reads, peak %d, longest run >= %d: %d reads, "
|
||||
"%d errors" % (prefix, self.phase or '-', self.phase_mode,
|
||||
self.reads, self.peak, self.threshold,
|
||||
self.longest_run, self.errors))
|
||||
logging.info("bdp_guard: %s", msg)
|
||||
gcmd.respond_info(msg)
|
||||
|
||||
def cmd_ARM(self, gcmd):
|
||||
phase = gcmd.get('PHASE', 'armed')
|
||||
mode = gcmd.get('MODE', self.mode).lower()
|
||||
if mode not in MODES:
|
||||
raise gcmd.error("BDP_GUARD_ARM: MODE must be log or stop")
|
||||
if self.timer is not None:
|
||||
self._report(gcmd, "BDP_GUARD")
|
||||
else:
|
||||
self.available = self._check_available()
|
||||
if not self.available:
|
||||
gcmd.respond_info("BDP_GUARD_ARM: bd_pressure load-check "
|
||||
"extension not found, guard not armed")
|
||||
return
|
||||
self._ensure_probe_mode(gcmd)
|
||||
self._rezero()
|
||||
self.phase_mode = mode
|
||||
self._reset_phase(phase)
|
||||
self.armed_until = self.reactor.monotonic() + self.timeout
|
||||
if self.timer is None:
|
||||
self.timer = self.reactor.register_timer(
|
||||
self._poll, self.reactor.monotonic() + self.interval)
|
||||
|
||||
def cmd_DISARM(self, gcmd):
|
||||
if self.timer is None:
|
||||
return
|
||||
self._stop_timer()
|
||||
self._report(gcmd, "BDP_GUARD")
|
||||
self.phase = ''
|
||||
|
||||
def cmd_QUERY(self, gcmd):
|
||||
self._report(gcmd, "BDP_GUARD_QUERY" + (" armed" if self.timer
|
||||
else " not armed"))
|
||||
|
||||
def get_status(self, eventtime):
|
||||
return {'armed': self.timer is not None, 'mode': self.phase_mode,
|
||||
'phase': self.phase, 'threshold': self.threshold,
|
||||
'samples': self.samples, 'peak': self.peak,
|
||||
'longest_run': self.longest_run, 'reads': self.reads,
|
||||
'errors': self.errors, 'available': self.available}
|
||||
|
||||
|
||||
def load_config(config):
|
||||
return BDPGuard(config)
|
||||
@@ -1,130 +0,0 @@
|
||||
# Load check using the bd_pressure firmware extension (bdp_check_ext.patch).
|
||||
#
|
||||
# Uses the I2C connection the existing [bdpressure <name>] section already
|
||||
# set up. Before writing anything it reads the extension marker (bytes
|
||||
# 54-55 = 0xBD + version 1 or 2). On stock firmware the marker is missing and every
|
||||
# command only reports "not available": nothing is written, because
|
||||
# writing past the stock register table would land in the sensor's RAM.
|
||||
#
|
||||
# Install: copy to ~/klipper/klippy/extras/bdpressure_check.py
|
||||
#
|
||||
# Config:
|
||||
# [bdpressure_check]
|
||||
# sensor: bd_pa # name after "bdpressure" in [bdpressure bd_pa]
|
||||
#
|
||||
# Commands (run them after M400, they act immediately, not in the move queue):
|
||||
# BDP_CHECK_START freeze the baseline and start measuring
|
||||
# BDP_CHECK_STOP stop measuring and read the result
|
||||
# BDP_CHECK_QUERY read the current values without stopping
|
||||
#
|
||||
# Status (printer.bdpressure_check), updated by the commands above:
|
||||
# available, running, peak, above_ms, longest_ms, delta
|
||||
# pa_points, pa_distinct - readings the [bdpressure] module collected in
|
||||
# its last PA_CALIBRATE, and how many of them differ (read
|
||||
# from that module, not from the sensor). A sensor that
|
||||
# stops answering gives few points; one that hangs repeats
|
||||
# the same reading. LANE_CALIBRATE_PA rejects such runs.
|
||||
|
||||
REG_EXT = 54 # first byte of the extension
|
||||
REG_CTRL = 56
|
||||
EXT_LEN = 12 # bytes 54-65, the same in version 1 and 2
|
||||
EXT_MAGIC = 0xBD
|
||||
# Version 2 (load-check firmware 20261015 and later) only adds diagnostics
|
||||
# at 66-71. Accepting only version 1 made the purge check report the sensor
|
||||
# as not answering after the firmware update.
|
||||
EXT_VERSIONS = (1, 2)
|
||||
|
||||
|
||||
class BDPressureCheck:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
self.sensor_name = 'bdpressure ' + config.get('sensor', 'bd_pa')
|
||||
self.sensor = None
|
||||
self.status = {'available': False, 'running': False, 'peak': 0,
|
||||
'above_ms': 0, 'longest_ms': 0, 'delta': 0}
|
||||
self.printer.register_event_handler('klippy:connect',
|
||||
self._handle_connect)
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
gcode.register_command('BDP_CHECK_START', self.cmd_START,
|
||||
desc="Start a bd_pressure load check")
|
||||
gcode.register_command('BDP_CHECK_STOP', self.cmd_STOP,
|
||||
desc="Stop the bd_pressure load check and read it")
|
||||
gcode.register_command('BDP_CHECK_QUERY', self.cmd_QUERY,
|
||||
desc="Read the bd_pressure load check values")
|
||||
|
||||
def _handle_connect(self):
|
||||
self.sensor = self.printer.lookup_object(self.sensor_name)
|
||||
|
||||
@property
|
||||
def i2c(self):
|
||||
# Looked up at every use: bdp_guard replaces the sensor's i2c with a
|
||||
# locked wrapper at connect, possibly after this module's connect.
|
||||
return getattr(self.sensor, 'i2c', None)
|
||||
|
||||
def _read(self):
|
||||
if self.i2c is None:
|
||||
self.status['available'] = False
|
||||
return False
|
||||
data = bytearray(self.i2c.i2c_read([REG_EXT], EXT_LEN)['response'])
|
||||
if (len(data) < EXT_LEN or data[0] != EXT_MAGIC
|
||||
or data[1] not in EXT_VERSIONS):
|
||||
self.status['available'] = False
|
||||
return False
|
||||
u16 = lambda i: data[i] | (data[i + 1] << 8)
|
||||
delta = u16(10)
|
||||
self.status.update({
|
||||
'available': True,
|
||||
'running': bool(data[3] & 1),
|
||||
'peak': u16(4),
|
||||
'above_ms': u16(6),
|
||||
'longest_ms': u16(8),
|
||||
'delta': delta - 0x10000 if delta & 0x8000 else delta,
|
||||
})
|
||||
return True
|
||||
|
||||
def _respond(self, gcmd, prefix):
|
||||
s = self.status
|
||||
if not s['available']:
|
||||
gcmd.respond_info("%s: bd_pressure check extension not found "
|
||||
"(stock firmware?), nothing done" % prefix)
|
||||
return
|
||||
gcmd.respond_info("%s: running=%d peak=%d above=%d ms longest=%d ms "
|
||||
"delta=%d" % (prefix, s['running'], s['peak'],
|
||||
s['above_ms'], s['longest_ms'],
|
||||
s['delta']))
|
||||
|
||||
def cmd_START(self, gcmd):
|
||||
# The values read here are still the previous check's, so only
|
||||
# confirm the start instead of printing them.
|
||||
if self._read():
|
||||
self.i2c.i2c_write([REG_CTRL, 1])
|
||||
self.status.update({'running': True, 'peak': 0, 'above_ms': 0,
|
||||
'longest_ms': 0})
|
||||
gcmd.respond_info("BDP_CHECK_START: started")
|
||||
return
|
||||
self._respond(gcmd, "BDP_CHECK_START")
|
||||
|
||||
def cmd_STOP(self, gcmd):
|
||||
if self._read():
|
||||
self.i2c.i2c_write([REG_CTRL, 0])
|
||||
self._read()
|
||||
self._respond(gcmd, "BDP_CHECK_STOP")
|
||||
|
||||
def cmd_QUERY(self, gcmd):
|
||||
self._read()
|
||||
self._respond(gcmd, "BDP_CHECK_QUERY")
|
||||
|
||||
def get_status(self, eventtime):
|
||||
status = dict(self.status)
|
||||
# [val, res, lk, rk, Hk, Ha] per reading, see bdpressure.py
|
||||
try:
|
||||
data = list(getattr(self.sensor, 'PA_data', None) or [])
|
||||
status['pa_points'] = len(data)
|
||||
status['pa_distinct'] = len(set(tuple(d[1:]) for d in data))
|
||||
except Exception:
|
||||
status['pa_points'] = status['pa_distinct'] = -1
|
||||
return status
|
||||
|
||||
|
||||
def load_config(config):
|
||||
return BDPressureCheck(config)
|
||||
@@ -0,0 +1,159 @@
|
||||
# Checks the loaded bed mesh for bumps, dips and too much height range.
|
||||
#
|
||||
# The bed is naturally bowl-shaped, so a height range alone cannot tell dirt
|
||||
# from normal shape. This fits a smooth surface (polynomial, degree 4) to the
|
||||
# probed points, leaving out outliers, and looks at how far each point is from
|
||||
# it. Measured on this printer's Beacon scans (33x35 points):
|
||||
# clean plate, cold or hot: worst deviation 0.016 mm
|
||||
# residue on the plate, 2026-11: 0.07 (bed 60C), 0.09 (bed 100C, at the old
|
||||
# mesh edge), 0.30 mm (cold, mesh over it)
|
||||
# Only reads the mesh: it moves nothing and changes nothing.
|
||||
#
|
||||
# Install: copy to ~/klipper/klippy/extras/mesh_check.py (install.sh links it)
|
||||
# and add
|
||||
#
|
||||
# [mesh_check]
|
||||
# bump_limit: 0.03 # mm from the smooth surface that counts as a bump or dip
|
||||
# range_limit: 0.30 # mm between the highest and lowest point
|
||||
#
|
||||
# Commands:
|
||||
# BED_MESH_CHECK [BUMP=<mm>] [RANGE=<mm>]
|
||||
#
|
||||
# Status (printer.mesh_check): result ('ok', 'fail', 'none' = no mesh or the
|
||||
# check failed, 'not run'), range, worst, areas (number of bumps and dips),
|
||||
# summary (no double quotes, usable in a macro's MSG="...")
|
||||
|
||||
import logging
|
||||
|
||||
import numpy as np
|
||||
|
||||
DEGREE = 4
|
||||
MAX_AREAS = 5 # areas named in the report, biggest deviation first
|
||||
MIN_POINTS = 40 # fewer points cannot carry a degree 4 surface reliably
|
||||
|
||||
|
||||
def surface_residuals(z):
|
||||
# Deviation of each point from a smooth surface. Refit without the points
|
||||
# far from it, so a bump does not pull the surface towards itself.
|
||||
ny, nx = z.shape
|
||||
x, y = np.meshgrid(np.linspace(-1., 1., nx), np.linspace(-1., 1., ny))
|
||||
terms = [x.ravel()**i * y.ravel()**j
|
||||
for i in range(DEGREE + 1) for j in range(DEGREE + 1 - i)]
|
||||
a = np.column_stack(terms)
|
||||
values = z.ravel()
|
||||
keep = np.ones(values.size, dtype=bool)
|
||||
residuals = np.zeros(values.size)
|
||||
for _ in range(5):
|
||||
coeffs = np.linalg.lstsq(a[keep], values[keep], rcond=None)[0]
|
||||
residuals = values - a.dot(coeffs)
|
||||
spread = 1.4826 * np.median(
|
||||
np.abs(residuals[keep] - np.median(residuals[keep])))
|
||||
keep = np.abs(residuals) < max(3. * spread, 0.01)
|
||||
return residuals.reshape(z.shape)
|
||||
|
||||
|
||||
def find_areas(residuals, limit):
|
||||
# Groups of touching points (diagonals too) beyond the limit, as
|
||||
# (peak, row min, row max, column min, column max)
|
||||
ny, nx = residuals.shape
|
||||
over = np.abs(residuals) > limit
|
||||
seen = np.zeros(over.shape, dtype=bool)
|
||||
areas = []
|
||||
for start in zip(*np.nonzero(over)):
|
||||
if seen[start]:
|
||||
continue
|
||||
seen[start] = True
|
||||
stack = [start]
|
||||
points = []
|
||||
while stack:
|
||||
j, i = stack.pop()
|
||||
points.append((j, i))
|
||||
for dj in (-1, 0, 1):
|
||||
for di in (-1, 0, 1):
|
||||
nj, ni = j + dj, i + di
|
||||
if (0 <= nj < ny and 0 <= ni < nx and over[nj, ni]
|
||||
and not seen[nj, ni]):
|
||||
seen[nj, ni] = True
|
||||
stack.append((nj, ni))
|
||||
peak = max((residuals[p] for p in points), key=abs)
|
||||
rows = [p[0] for p in points]
|
||||
cols = [p[1] for p in points]
|
||||
areas.append((float(peak), min(rows), max(rows), min(cols), max(cols)))
|
||||
areas.sort(key=lambda area: -abs(area[0]))
|
||||
return areas
|
||||
|
||||
|
||||
def analyse(matrix, mesh_min, mesh_max, bump_limit, range_limit):
|
||||
# Returns the status dictionary. No Klipper objects, so it can be tested
|
||||
# against saved scans.
|
||||
z = np.array(matrix, dtype=float)
|
||||
if z.ndim != 2 or z.size == 0:
|
||||
return {'result': 'none', 'range': 0., 'worst': 0., 'areas': 0,
|
||||
'summary': 'no bed mesh loaded'}
|
||||
height_range = float(z.max() - z.min())
|
||||
ny, nx = z.shape
|
||||
if z.size < MIN_POINTS:
|
||||
return {'result': 'none', 'range': height_range, 'worst': 0.,
|
||||
'areas': 0,
|
||||
'summary': 'mesh too small to check (%d points)' % (z.size,)}
|
||||
residuals = surface_residuals(z)
|
||||
worst = float(np.abs(residuals).max())
|
||||
areas = find_areas(residuals, bump_limit)
|
||||
step_x = (mesh_max[0] - mesh_min[0]) / float(nx - 1)
|
||||
step_y = (mesh_max[1] - mesh_min[1]) / float(ny - 1)
|
||||
problems = []
|
||||
for peak, row0, row1, col0, col1 in areas[:MAX_AREAS]:
|
||||
problems.append("%s %+.2f mm at X%.0f-%.0f Y%.0f-%.0f" % (
|
||||
"bump" if peak > 0. else "dip", peak,
|
||||
mesh_min[0] + col0 * step_x, mesh_min[0] + col1 * step_x,
|
||||
mesh_min[1] + row0 * step_y, mesh_min[1] + row1 * step_y))
|
||||
if len(areas) > MAX_AREAS:
|
||||
problems.append("%d more" % (len(areas) - MAX_AREAS,))
|
||||
too_wide = height_range > range_limit
|
||||
if too_wide:
|
||||
problems.append("range %.2f mm is over the limit of %.2f" % (
|
||||
height_range, range_limit))
|
||||
text = "range %.3f mm, worst deviation %.3f mm" % (height_range, worst)
|
||||
if problems:
|
||||
text = "%s: %s" % (text, ", ".join(problems))
|
||||
return {'result': 'fail' if problems else 'ok', 'range': height_range,
|
||||
'worst': worst, 'areas': len(areas), 'summary': text}
|
||||
|
||||
|
||||
class MeshCheck:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
self.reactor = self.printer.get_reactor()
|
||||
self.bump_limit = config.getfloat('bump_limit', 0.03, above=0.)
|
||||
self.range_limit = config.getfloat('range_limit', 0.30, above=0.)
|
||||
self.status = {'result': 'not run', 'range': 0., 'worst': 0.,
|
||||
'areas': 0, 'summary': ''}
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
gcode.register_command('BED_MESH_CHECK', self.cmd_BED_MESH_CHECK,
|
||||
desc="Check the loaded bed mesh for bumps, "
|
||||
"dips and too much height range")
|
||||
|
||||
def cmd_BED_MESH_CHECK(self, gcmd):
|
||||
bump = gcmd.get_float('BUMP', self.bump_limit, above=0.)
|
||||
height_range = gcmd.get_float('RANGE', self.range_limit, above=0.)
|
||||
# A failing analysis must not stop a print: it reports and goes on
|
||||
try:
|
||||
bed_mesh = self.printer.lookup_object('bed_mesh')
|
||||
mesh = bed_mesh.get_status(self.reactor.monotonic())
|
||||
self.status = analyse(mesh['probed_matrix'], mesh['mesh_min'],
|
||||
mesh['mesh_max'], bump, height_range)
|
||||
except Exception:
|
||||
logging.exception("mesh_check: analysis failed")
|
||||
self.status = {'result': 'none', 'range': 0., 'worst': 0.,
|
||||
'areas': 0,
|
||||
'summary': 'check failed, see klippy.log'}
|
||||
msg = "Bed mesh check: %s" % (self.status['summary'],)
|
||||
logging.info("mesh_check: %s (%s)", msg, self.status['result'])
|
||||
gcmd.respond_info(msg)
|
||||
|
||||
def get_status(self, eventtime):
|
||||
return dict(self.status)
|
||||
|
||||
|
||||
def load_config(config):
|
||||
return MeshCheck(config)
|
||||
@@ -0,0 +1,106 @@
|
||||
# Automatic resume after an AFC "NOT FEEDING" buffer fault
|
||||
#
|
||||
# When AFC pauses a print because the buffer stayed empty too long,
|
||||
# PAUSE (print/pause_resume.cfg) calls _AUTO_RESUME_ARM. After `delay` seconds
|
||||
# _AUTO_RESUME runs the normal RESUME: AFC clears its error, the lane check
|
||||
# runs, and _RESUME_PRINT purges into the Blobifier with the purge check. A
|
||||
# failed check (or lane check) stops that RESUME as usual, so the print stays
|
||||
# paused and waits for you.
|
||||
#
|
||||
# Limits, so a real problem (tangled spool, grinding extruder, clog) is not
|
||||
# hidden: at most `max_per_print` automatic resumes per print, and none when
|
||||
# the previous one was less than `min_interval` minutes of printing ago. After
|
||||
# that the print stays paused like before.
|
||||
#
|
||||
# Only between _PRINT_START_FINISH and the end of the print (`active`): a pause
|
||||
# during PRINT_START or a PA test needs CLEAR_PAUSE, not RESUME.
|
||||
#
|
||||
# Turn off: SET_GCODE_VARIABLE MACRO=_AUTO_RESUME_CFG VARIABLE=enabled VALUE=False
|
||||
# (until the next restart; change `enabled` below to keep it off)
|
||||
|
||||
[gcode_macro _AUTO_RESUME_CFG]
|
||||
description: Settings and state for the automatic resume after an AFC buffer fault
|
||||
variable_enabled: True
|
||||
variable_max_per_print: 2 # automatic resumes per print
|
||||
variable_min_interval: 10 # minutes of printing since the previous automatic resume
|
||||
variable_delay: 5 # seconds after the pause (AFC finishes its own pause first)
|
||||
variable_faults: ['NOT FEEDING'] # text in AFC's error message
|
||||
# Not 'CLOG DETECTED' (buffer stayed full: the extruder takes no filament):
|
||||
# that is usually a real blockage. On 2026-11-17 a nozzle blocked right after a
|
||||
# swap; the purge check still passed (a blocked nozzle also builds pressure),
|
||||
# so the automatic resume only printed air until the next CLOG pause.
|
||||
variable_clear_faults: ['NOT FEEDING', 'CLOG DETECTED'] # removed from AFC's queue after any resume
|
||||
# State (set by the macros)
|
||||
variable_active: False # True from _PRINT_START_FINISH to the end of the print
|
||||
variable_count: 0 # automatic resumes in this print
|
||||
variable_last_at: -1.0 # print_duration (s) of the last automatic resume, -1 = none
|
||||
variable_pending: '' # fault the timer is waiting to resume from
|
||||
gcode:
|
||||
RESPOND MSG="Auto-resume: {'on' if enabled else 'off'}, {'active' if active else 'not active'}, {count}/{max_per_print} used in this print"
|
||||
|
||||
# Called by _PRINT_START_FINISH (ON=1) and _PRINT_CLEANUP (ON=0)
|
||||
[gcode_macro _AUTO_RESUME_ACTIVE]
|
||||
description: Start (ON=1) or end (ON=0) the automatic resume for a print
|
||||
gcode:
|
||||
{% set on = params.ON|default(1)|int %}
|
||||
SET_GCODE_VARIABLE MACRO=_AUTO_RESUME_CFG VARIABLE=active VALUE={True if on else False}
|
||||
SET_GCODE_VARIABLE MACRO=_AUTO_RESUME_CFG VARIABLE=count VALUE=0
|
||||
SET_GCODE_VARIABLE MACRO=_AUTO_RESUME_CFG VARIABLE=last_at VALUE=-1.0
|
||||
SET_GCODE_VARIABLE MACRO=_AUTO_RESUME_CFG VARIABLE=pending VALUE="''"
|
||||
UPDATE_DELAYED_GCODE ID=_AUTO_RESUME DURATION=0
|
||||
{% if on and 'AFC' in printer %}
|
||||
# Old messages would be read as this print's fault: start empty
|
||||
AFC_CLEAR_ALL_MESSAGES
|
||||
{% endif %}
|
||||
|
||||
# Called by PAUSE when it pauses a print. AFC's message queue shows its oldest
|
||||
# message first; _RESUME_PRINT removes a buffer fault message once resumed, so
|
||||
# the oldest one is this pause's.
|
||||
[gcode_macro _AUTO_RESUME_ARM]
|
||||
description: Start the automatic resume timer when AFC paused for a buffer fault and the limits allow it
|
||||
gcode:
|
||||
{% set cfg = printer["gcode_macro _AUTO_RESUME_CFG"] %}
|
||||
{% set has_afc = 'AFC' in printer %}
|
||||
{% set msg = printer.AFC.message.message|default('') if has_afc else '' %}
|
||||
{% set fault = (cfg.faults|select('in', msg)|list + [''])[0] %}
|
||||
{% set now = printer.print_stats.print_duration|float %}
|
||||
{% if cfg.enabled and cfg.active and has_afc and printer.AFC.error_state and fault %}
|
||||
{% if cfg.count >= cfg.max_per_print %}
|
||||
_WARN MSG="Auto-resume: not resuming after AFC {fault}, already {cfg.count} automatic resumes in this print. Check the lane, then RESUME." DISPLAY="AFC {fault}: check, then RESUME"
|
||||
{% elif cfg.last_at >= 0 and now - cfg.last_at < cfg.min_interval * 60 %}
|
||||
_WARN MSG="Auto-resume: not resuming after AFC {fault}, the last automatic resume was only {((now - cfg.last_at) / 60)|round(1)} min of printing ago. Check the lane, then RESUME." DISPLAY="AFC {fault} again: check, then RESUME"
|
||||
{% else %}
|
||||
SET_GCODE_VARIABLE MACRO=_AUTO_RESUME_CFG VARIABLE=pending VALUE="'{fault}'"
|
||||
RESPOND MSG="Auto-resume: AFC {fault}, resuming in {cfg.delay} s with the purge check ({cfg.count + 1}/{cfg.max_per_print})"
|
||||
UPDATE_DELAYED_GCODE ID=_AUTO_RESUME DURATION={cfg.delay}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
[delayed_gcode _AUTO_RESUME]
|
||||
gcode:
|
||||
{% set cfg = printer["gcode_macro _AUTO_RESUME_CFG"] %}
|
||||
{% set fault = cfg.pending %}
|
||||
SET_GCODE_VARIABLE MACRO=_AUTO_RESUME_CFG VARIABLE=pending VALUE="''"
|
||||
# Only when nothing changed since the pause: still paused, still AFC's
|
||||
# error (a manual RESUME or CANCEL in the meantime ends it)
|
||||
{% if fault and cfg.active and printer.print_stats.state == 'paused'
|
||||
and printer.pause_resume.is_paused and printer.AFC.error_state %}
|
||||
SET_GCODE_VARIABLE MACRO=_AUTO_RESUME_CFG VARIABLE=count VALUE={cfg.count + 1}
|
||||
SET_GCODE_VARIABLE MACRO=_AUTO_RESUME_CFG VARIABLE=last_at VALUE={printer.print_stats.print_duration|float}
|
||||
RESPOND MSG="Auto-resume {cfg.count + 1}/{cfg.max_per_print} after AFC {fault}"
|
||||
M117 Auto-resume {cfg.count + 1}/{cfg.max_per_print}: AFC {fault}
|
||||
RESUME
|
||||
{% endif %}
|
||||
|
||||
# Called by _RESUME_PRINT after a resume: remove a buffer fault message from
|
||||
# the front of AFC's queue, so the next pause reads its own message. Also a
|
||||
# CLOG message after a manual RESUME: left at the front, it would hide the next
|
||||
# NOT FEEDING message and block that automatic resume.
|
||||
[gcode_macro _AUTO_RESUME_CLEAR_FAULT]
|
||||
description: Helper: drop AFC's buffer fault message after a resume
|
||||
gcode:
|
||||
{% set cfg = printer["gcode_macro _AUTO_RESUME_CFG"] %}
|
||||
{% set msg = printer.AFC.message.message|default('') if 'AFC' in printer else '' %}
|
||||
{% if msg and cfg.clear_faults|select('in', msg)|list %}
|
||||
AFC_CLEAR_MESSAGE
|
||||
{% endif %}
|
||||
@@ -9,10 +9,15 @@
|
||||
# the nozzle pressure stayed above the threshold. Catches filament
|
||||
# that never reached the melt zone. Skipped automatically on stock
|
||||
# firmware or when bdpressure_check.py is not installed.
|
||||
# A blocked nozzle builds pressure too, so that alone passes it. The
|
||||
# pressure left when the check stops (delta, a few seconds after the
|
||||
# purge, once the blob is dropped) catches some: it bleeds off slowly
|
||||
# through a blocked nozzle (pressure_max_delta).
|
||||
#
|
||||
# Needs: bdwidth_status.py in ~/klipper/klippy/extras/
|
||||
# bdpressure_check.py in ~/klipper/klippy/extras/ (optional)
|
||||
# (klipper/install.sh links both; guide: klipper/load_check/afc_blobifier/README.md)
|
||||
# (this repo's install.sh links bdwidth_status.py; bdpressure_check.py
|
||||
# comes from the bd_pressure repo, its klipper/install.sh links it)
|
||||
# Hook: in [AFC] (AFC/AFC.cfg) change poop_cmd: BLOBIFIER
|
||||
# to poop_cmd: BLOBIFIER_CHECKED
|
||||
#
|
||||
@@ -45,6 +50,11 @@ variable_motion_check: False # False: skip the bdwidth motion check, pressure
|
||||
variable_min_ratio: 0.4 # placeholder: sensed mm / extruded mm below this = not feeding
|
||||
variable_min_extrude: 20 # skip the checks for purges shorter than this (mm)
|
||||
variable_pressure_min_ms: 5000 # placeholder: longest continuous pressure needed (ms)
|
||||
# Pressure still above the baseline when the check stops = nozzle (partly)
|
||||
# blocked; 0 = off. Data 2026-11-12..17: 16 good purges -3..+10, the two long
|
||||
# purges into a blocked nozzle (2026-11-17) +19 and +21; the two 40 mm purges
|
||||
# into that nozzle gave -2 and -12, so it does not catch every blockage.
|
||||
variable_pressure_max_delta: 15
|
||||
# bdwidth is not reading after SET_BDWIDTH ... COMMAND=DISABLE and after
|
||||
# every Klipper restart until an ENABLE (outside a print, often early in a
|
||||
# print start). The check then switches it on and waits this long for the
|
||||
@@ -53,6 +63,7 @@ variable_bdwidth_warmup_ms: 15000
|
||||
variable_start_counts: 0
|
||||
variable_start_e: 0.0
|
||||
variable_last_failed: False # last check failed in enforce mode (read by _RESUME_PURGE_VERIFY)
|
||||
variable_swap_failed: False # failed during an infinite spool swap (read by _PURGE_CHECK_SWAP_STOP)
|
||||
variable_ignore_missing_sensor: False # set by PURGE_CHECK_IGNORE_SENSOR, cleared at print end
|
||||
# Hotter purge: the leftover of the previous filament (the piece below the
|
||||
# cutter) has to melt to be pushed out. When the filament that last went
|
||||
@@ -117,6 +128,7 @@ gcode:
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
_PURGE_FLUSH_DONE
|
||||
_PURGE_CHECK_SWAP_STOP
|
||||
|
||||
# Separate macros so the status is read when they run, not when
|
||||
# BLOBIFIER_CHECKED is rendered
|
||||
@@ -185,10 +197,13 @@ gcode:
|
||||
{% endif %}
|
||||
{% if 'bdpressure_check' in printer and printer.bdpressure_check.available %}
|
||||
{% set p = printer.bdpressure_check %}
|
||||
{% set press = "pressure longest %d ms, total %d ms, peak %d" % (p.longest_ms, p.above_ms, p.peak) %}
|
||||
{% set press = "pressure longest %d ms, total %d ms, peak %d, left %d" % (p.longest_ms, p.above_ms, p.peak, p.delta) %}
|
||||
{% if p.longest_ms < cfg.pressure_min_ms %}
|
||||
{% set _ = failed.append("no sustained nozzle pressure") %}
|
||||
{% endif %}
|
||||
{% if cfg.pressure_max_delta > 0 and p.delta > cfg.pressure_max_delta %}
|
||||
{% set _ = failed.append("pressure stays high after the purge (%d > %d): nozzle blocked?" % (p.delta, cfg.pressure_max_delta)) %}
|
||||
{% endif %}
|
||||
{% elif 'bdpressure_check' in printer %}
|
||||
{% if cfg.ignore_missing_sensor %}
|
||||
{% set press = "pressure skipped: bd_pressure not answering (ignored, PURGE_CHECK_IGNORE_SENSOR)" %}
|
||||
@@ -205,10 +220,39 @@ gcode:
|
||||
{% if failed and cfg.mode == "enforce" %}
|
||||
_WARN MSG="PURGE_CHECK: {lane} {failed|join(', ')} - check extruder and lane" DISPLAY="Purge check failed: {lane}, paused"
|
||||
SET_GCODE_VARIABLE MACRO=_PURGE_CHECK_CFG VARIABLE=last_failed VALUE=True
|
||||
PAUSE ; no effect while already paused (resume purge): see _RESUME_PURGE_VERIFY
|
||||
# Infinite spool swap: AFC paused the file itself, without PAUSE
|
||||
{% if printer.print_stats.state == "paused" and not printer.pause_resume.is_paused %}
|
||||
SET_GCODE_VARIABLE MACRO=_PURGE_CHECK_CFG VARIABLE=swap_failed VALUE=True
|
||||
{% else %}
|
||||
PAUSE ; no effect while already paused (resume purge): see _RESUME_PURGE_VERIFY
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
# A failed check during an infinite spool swap. PAUSE alone would not stop it:
|
||||
# AFC only looks at its own error state, so it would remap, go back to the print
|
||||
# and restart the file while the printer counts as paused. An error reaches AFC's
|
||||
# CHANGE_TOOL, which then pauses through AFC_error and sets that state, so the
|
||||
# swap stops. Last in BLOBIFIER_CHECKED: the error skips everything after it. It
|
||||
# also skips the rest of AFC's TOOL_LOAD, so the buffer's fault detection may stay
|
||||
# off until the next tool load, and AFC's remap, which the message asks for.
|
||||
[gcode_macro _PURGE_CHECK_SWAP_STOP]
|
||||
description: Helper for BLOBIFIER_CHECKED: stop an infinite spool swap after a failed check
|
||||
gcode:
|
||||
{% if printer["gcode_macro _PURGE_CHECK_CFG"].swap_failed %}
|
||||
SET_GCODE_VARIABLE MACRO=_PURGE_CHECK_CFG VARIABLE=swap_failed VALUE=False
|
||||
{% set lane = printer.AFC.current_load|default("", true) %}
|
||||
{% set ns = namespace(tool="") %}
|
||||
{% for name in printer.AFC.lanes %}
|
||||
{% set obj = printer["AFC_stepper " ~ name] if ("AFC_stepper " ~ name) in printer else {} %}
|
||||
{% if lane and obj.runout_lane|default("", true) == lane and not ns.tool %}
|
||||
{% set ns.tool = obj.map %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% set remap = "SET_MAP LANE=%s MAP=%s, then " % (lane, ns.tool) if ns.tool else "set the tool map with SET_MAP, then " %}
|
||||
_ERROR MSG="Spool swap stopped: the purge check failed on {lane}. Check the extruder and lane, run {remap}RESUME. AFC also reports an unexpected CHANGE_TOOL error: that is this stop." DISPLAY="Swap stopped: purge check failed on {lane}"
|
||||
{% endif %}
|
||||
|
||||
[gcode_macro PURGE_CHECK_IGNORE_SENSOR]
|
||||
description: Let purges pass without bd_pressure until the print ends (ENABLE=0 to undo)
|
||||
gcode:
|
||||
|
||||
@@ -63,6 +63,10 @@
|
||||
# if you experience excessive oozing.
|
||||
# variable_purge_spd: 250 #300 # Speed, in mm/min, of the purge.
|
||||
variable_purge_spd: 150 # Speed, in mm/min, of the purge.
|
||||
# Purge speed (mm/min) per nozzle size, chosen by the save variable pa_nozzle
|
||||
# (SET_NOZZLE). 150 mm/min is about 6 mm3/s, too much for a 0.2 nozzle.
|
||||
# A size not listed uses purge_spd.
|
||||
variable_purge_spd_nozzle: {"0.4": 150, "0.2": 75}
|
||||
variable_purge_temp_min: 200 # Minimum nozzle purge temperature.
|
||||
variable_toolhead_x: 70 # From the nozzle to the left of your toolhead
|
||||
variable_toolhead_y: 50 # From the nozzle to the front of your toolhead
|
||||
@@ -278,6 +282,10 @@ variable_shaker_arm_z: 4
|
||||
|
||||
gcode:
|
||||
|
||||
# Purge speed for the fitted nozzle (purge_spd_nozzle above)
|
||||
{% set nozzle = "%g" % printer.save_variables.variables["pa_nozzle"]|default(0.4)|float %}
|
||||
{% set purge_rate = purge_spd_nozzle[nozzle]|float if nozzle in purge_spd_nozzle else purge_spd|float %}
|
||||
|
||||
# ======================================================================================
|
||||
# ==================== RECORD STATE (INCL. FANS, SPEEDS, ETC...) =======================
|
||||
# ======================================================================================
|
||||
@@ -444,8 +452,8 @@ gcode:
|
||||
{% set pulses_per_retract = (purge_per_blob / retracts_per_blob / 5)|round(0, 'ceil')|int %}
|
||||
{% set pulses_per_blob = (purge_per_blob / 5)|round(0, 'ceil')|int %}
|
||||
{% set purge_per_pulse = purge_per_blob / pulses_per_blob %}
|
||||
{% set pulse_time_constant = purge_per_pulse * 0.95 / purge_spd / (purge_per_pulse * 0.95 / purge_spd + purge_per_pulse * 0.05 / 50) %}
|
||||
{% set pulse_duration = purge_per_pulse / purge_spd %}
|
||||
{% set pulse_time_constant = purge_per_pulse * 0.95 / purge_rate / (purge_per_pulse * 0.95 / purge_rate + purge_per_pulse * 0.05 / 50) %}
|
||||
{% set pulse_duration = purge_per_pulse / purge_rate %}
|
||||
|
||||
# Repeat the process until purge_len is reached
|
||||
{% for blob in range(blobs) %}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
# Bed check: scan the bed and warn about bumps, dips or too much height range
|
||||
# (needs extras/mesh_check.py, which explains the method and the limits)
|
||||
#
|
||||
# BED_SCAN_CHECK [BUMP=0.03] [RANGE=0.30]
|
||||
# Scan now and report. Warns only, for use between prints. No heating and
|
||||
# no contact: X and Y home if needed, Z homes with the Beacon's proximity
|
||||
# mode. Replaces the active mesh, like any scan.
|
||||
#
|
||||
# BED_MESH_CHECK [BUMP=0.03] [RANGE=0.30] (extras/mesh_check.py)
|
||||
# Only check the mesh that is loaded now.
|
||||
#
|
||||
# In PRINT_START a failed check pauses the print before the nozzle heats up:
|
||||
# the toolhead goes up and out of the way so the plate can be cleaned.
|
||||
# Resume levels, homes and scans again, and checks again
|
||||
# BED_CHECK_IGNORE then Resume: the next failed check only warns
|
||||
# Cancel works as usual.
|
||||
#
|
||||
# How the retry works: a PAUSE in a macro only stops the print file, the rest
|
||||
# of the macro still runs, so everything after the check sits in
|
||||
# _PRINT_START_FINISH and is only called when the check allows it. While a
|
||||
# line of the file runs, virtual_sdcard.file_position is the start of that
|
||||
# line. Resume sets the file back there (M26) and resumes, so the file runs
|
||||
# PRINT_START again, as normal print file G-code: an error stops the print as
|
||||
# it always does, which an error in a delayed_gcode would not (the file would
|
||||
# carry on with the first layer).
|
||||
#
|
||||
# The pause goes through PAUSE, so through AFC_PAUSE: AFC_RESUME always restores
|
||||
# AFC's saved position after a pause. Without saving it here, that could be a
|
||||
# stale position from an earlier print, or X0 Y0 (seen after HEAT_SOAK).
|
||||
# RESET_FAILURE first, because AFC does not save over a position it still holds.
|
||||
# PAUSE sees _BED_CHECK_STATE.pending and only pauses: no retract, no park at
|
||||
# the bucket, and RESUME skips _RESUME_PRINT and its purge (the filament is not
|
||||
# loaded yet at this point).
|
||||
|
||||
[mesh_check]
|
||||
bump_limit: 0.03
|
||||
range_limit: 0.30
|
||||
|
||||
[gcode_macro _BED_CHECK_STATE]
|
||||
description: Variables of the print start bed check
|
||||
variable_pending: False # paused by the check, the next RESUME retries
|
||||
variable_ignore: False # BED_CHECK_IGNORE: the next failed check only warns
|
||||
variable_file_position: 0 # start of the PRINT_START line in the print file
|
||||
variable_park_z: 100 # room to reach the plate; free of the bucket above Z10
|
||||
gcode:
|
||||
|
||||
[gcode_macro _BED_CHECK_RESET]
|
||||
description: Forget a pending bed check (start and end of a print)
|
||||
gcode:
|
||||
SET_GCODE_VARIABLE MACRO=_BED_CHECK_STATE VARIABLE=pending VALUE=False
|
||||
SET_GCODE_VARIABLE MACRO=_BED_CHECK_STATE VARIABLE=ignore VALUE=False
|
||||
|
||||
[gcode_macro BED_SCAN_CHECK]
|
||||
description: Scan the bed and warn about bumps, dips or too much height range (not during a print)
|
||||
gcode:
|
||||
{% set state = printer.print_stats.state %}
|
||||
{% if state in ('printing', 'paused') %}
|
||||
_ERROR MSG="BED_SCAN_CHECK: not during a print ({state})" DISPLAY="Bed scan: not during a print"
|
||||
{% else %}
|
||||
SAVE_GCODE_STATE NAME=_bed_scan_check
|
||||
G90
|
||||
{% if 'xy' not in printer.toolhead.homed_axes %}
|
||||
_GUARD_ON PHASE=bed_check_home_xy
|
||||
G28 X Y
|
||||
_GUARD_OFF
|
||||
{% endif %}
|
||||
{% if 'z' not in printer.toolhead.homed_axes %}
|
||||
_GUARD_ON PHASE=bed_check_home_z
|
||||
G28 Z METHOD=PROXIMITY
|
||||
_GUARD_OFF
|
||||
{% endif %}
|
||||
_GUARD_ON PHASE=bed_check_qgl
|
||||
QUAD_GANTRY_LEVEL
|
||||
_GUARD_ON PHASE=bed_check_z
|
||||
G28 Z METHOD=PROXIMITY
|
||||
_GUARD_ON PHASE=bed_check_mesh
|
||||
BED_MESH_CALIBRATE RUNS=2
|
||||
G1 Z10 F1200
|
||||
_GUARD_OFF
|
||||
RESTORE_GCODE_STATE NAME=_bed_scan_check
|
||||
BED_MESH_CHECK {rawparams}
|
||||
_BED_SCAN_CHECK_REPORT
|
||||
{% endif %}
|
||||
|
||||
# Separate macro: rendered after BED_MESH_CHECK has run
|
||||
[gcode_macro _BED_SCAN_CHECK_REPORT]
|
||||
description: Helper for BED_SCAN_CHECK: warn when the check failed
|
||||
gcode:
|
||||
{% set check = printer.mesh_check %}
|
||||
{% if check.result == 'fail' %}
|
||||
_WARN MSG="Bed check: {check.summary}. A bump usually means something on the plate: clean it and scan again." DISPLAY="Bed check failed, see console"
|
||||
{% elif check.result == 'none' %}
|
||||
_WARN MSG="Bed check not done: {check.summary}" DISPLAY="Bed check not done"
|
||||
{% else %}
|
||||
M117 Bed check OK
|
||||
{% endif %}
|
||||
|
||||
[gcode_macro BED_CHECK_IGNORE]
|
||||
description: After the print start bed check paused the print: the next failed check only warns (press Resume after this)
|
||||
gcode:
|
||||
{% if printer["gcode_macro _BED_CHECK_STATE"].pending %}
|
||||
SET_GCODE_VARIABLE MACRO=_BED_CHECK_STATE VARIABLE=ignore VALUE=True
|
||||
RESPOND MSG="Bed check: press Resume. It scans once more and continues even if the check still fails."
|
||||
{% else %}
|
||||
RESPOND MSG="Bed check: the print is not paused by the check, nothing to ignore"
|
||||
{% endif %}
|
||||
|
||||
# Called by _PRINT_START_GATE. FILE_POS: start of the PRINT_START line.
|
||||
[gcode_macro _BED_CHECK_PAUSE]
|
||||
description: Helper for PRINT_START: move away from the plate and pause, RESUME scans again
|
||||
gcode:
|
||||
{% set cfg = printer["gcode_macro _BED_CHECK_STATE"] %}
|
||||
{% set summary = printer.mesh_check.summary %}
|
||||
SET_GCODE_VARIABLE MACRO=_BED_CHECK_STATE VARIABLE=pending VALUE=True
|
||||
SET_GCODE_VARIABLE MACRO=_BED_CHECK_STATE VARIABLE=file_position VALUE={params.FILE_POS|int}
|
||||
G90
|
||||
_GUARD_ON PHASE=bed_check_park
|
||||
G1 Z{[cfg.park_z, printer.toolhead.axis_maximum.z - 5]|min} F1200
|
||||
G1 X175 Y340 F6000
|
||||
_GUARD_OFF
|
||||
RESET_FAILURE
|
||||
PAUSE
|
||||
_STATUS STATE=paused
|
||||
_WARN MSG="Bed check failed, print paused: {summary}. Clean the plate and press Resume to scan again. To print anyway: BED_CHECK_IGNORE, then Resume." DISPLAY="Bed check failed: clean plate, Resume"
|
||||
|
||||
# Called by RESUME instead of its normal chain while a check is pending.
|
||||
# AFC_RESUME then restores the position that AFC_PAUSE saved in _BED_CHECK_PAUSE.
|
||||
[gcode_macro _BED_CHECK_RETRY]
|
||||
description: Helper for RESUME: go back to the PRINT_START line of the print file and resume
|
||||
gcode:
|
||||
{% set cfg = printer["gcode_macro _BED_CHECK_STATE"] %}
|
||||
SET_GCODE_VARIABLE MACRO=_BED_CHECK_STATE VARIABLE=pending VALUE=False
|
||||
# Clear the pause reason from the display
|
||||
M117
|
||||
RESPOND MSG="Bed check: levelling and scanning again"
|
||||
M26 S{cfg.file_position|int}
|
||||
RESUME_BASE
|
||||
@@ -0,0 +1,115 @@
|
||||
# Axis twist calibration from Mainsail: run TWIST_CALIBRATE and follow the
|
||||
# windows. Starts scripts/twist_check.py (see there) in the background: inside
|
||||
# a macro it would deadlock, because the macro holds the G-code queue that the
|
||||
# script needs.
|
||||
#
|
||||
# TWIST_CALIBRATE the start: explains, checks, shows progress while running
|
||||
# TWIST_STOP stop a run: lifts the nozzle, nozzle heater off. It waits
|
||||
# for the command that is running (homing, QGL: up to a
|
||||
# minute); use the emergency stop in a real emergency.
|
||||
#
|
||||
# While running: progress on the status line (M117) and in TWIST_CALIBRATE,
|
||||
# logo as for Z calibration, the result opens a window. Reports and the
|
||||
# values to apply are in config/twist_data/. Nothing here changes printer.cfg.
|
||||
#
|
||||
# Started from Klipper, so restarting the Klipper service ends the run.
|
||||
|
||||
[gcode_shell_command _twist_start]
|
||||
command: bash -c 'setsid nohup python3 "$HOME/printer_data/config/klipper-macros-scripts/twist_check.py" "$1" >/dev/null 2>&1 </dev/null &' twist
|
||||
timeout: 5.0
|
||||
verbose: False
|
||||
|
||||
# [t]: otherwise pkill also matches this bash command itself
|
||||
[gcode_shell_command _twist_stop]
|
||||
command: bash -c 'pkill -TERM -f "[t]wist_check.py (measure|verify)" || true'
|
||||
timeout: 5.0
|
||||
verbose: False
|
||||
|
||||
# Set by the script; a RESTART clears it
|
||||
[gcode_macro _TWIST_STATE]
|
||||
variable_running: 0
|
||||
variable_mode: ''
|
||||
variable_done: 0
|
||||
variable_total: 0
|
||||
gcode:
|
||||
|
||||
[gcode_macro _TWIST_CLOSE]
|
||||
description: Close the twist calibration window
|
||||
gcode:
|
||||
RESPOND TYPE=command MSG="action:prompt_end"
|
||||
|
||||
[gcode_macro TWIST_CALIBRATE]
|
||||
description: Axis twist calibration (nozzle vs Beacon): explains the steps, starts them, shows progress
|
||||
gcode:
|
||||
{% set st = printer['gcode_macro _TWIST_STATE'] %}
|
||||
{% if st.running %}
|
||||
{% set pct = (100 * st.done / st.total)|int if st.total else 0 %}
|
||||
{% set n = pct // 5 %}
|
||||
RESPOND TYPE=command MSG="action:prompt_begin Twist {st.mode} is running"
|
||||
RESPOND TYPE=command MSG="action:prompt_text Point {st.done} of {st.total}"
|
||||
RESPOND TYPE=command MSG="action:prompt_text [{'=' * n}{'.' * (20 - n)}] {pct} percent"
|
||||
RESPOND TYPE=command MSG="action:prompt_text You can close this window: the run continues. The status line shows the progress, and a window opens with the result."
|
||||
RESPOND TYPE=command MSG="action:prompt_footer_button Stop the run|TWIST_STOP|error"
|
||||
RESPOND TYPE=command MSG="action:prompt_footer_button Close|_TWIST_CLOSE|secondary"
|
||||
RESPOND TYPE=command MSG="action:prompt_show"
|
||||
{% elif printer.print_stats.state in ("printing", "paused") %}
|
||||
RESPOND TYPE=command MSG="action:prompt_begin Not during a print"
|
||||
RESPOND TYPE=command MSG="action:prompt_text The calibration moves the nozzle onto the bed. Start it when the print has finished."
|
||||
RESPOND TYPE=command MSG="action:prompt_footer_button Close|_TWIST_CLOSE|secondary"
|
||||
RESPOND TYPE=command MSG="action:prompt_show"
|
||||
{% else %}
|
||||
RESPOND TYPE=command MSG="action:prompt_begin Axis twist calibration"
|
||||
RESPOND TYPE=command MSG="action:prompt_text Checks that the nozzle and the Beacon agree across the bed. Run it after work on the X rail, carriage, toolhead, belts or Beacon mount, or when first layers differ left vs right."
|
||||
RESPOND TYPE=command MSG="action:prompt_text Measure (25 min): measures and tells you whether new values are needed. Start here."
|
||||
RESPOND TYPE=command MSG="action:prompt_text Verify (17 min): checks the active values with bd_pressure. Run it after applying new values."
|
||||
RESPOND TYPE=command MSG="action:prompt_button Measure|_TWIST_CHECKLIST MODE=measure|primary"
|
||||
RESPOND TYPE=command MSG="action:prompt_button Verify|_TWIST_CHECKLIST MODE=verify|secondary"
|
||||
RESPOND TYPE=command MSG="action:prompt_footer_button Close|_TWIST_CLOSE|secondary"
|
||||
RESPOND TYPE=command MSG="action:prompt_show"
|
||||
{% endif %}
|
||||
|
||||
[gcode_macro _TWIST_CHECKLIST]
|
||||
description: Twist calibration: what to check before starting
|
||||
gcode:
|
||||
{% set mode = params.MODE|default('measure')|lower %}
|
||||
{% set bed = printer.heater_bed.temperature %}
|
||||
RESPOND TYPE=command MSG="action:prompt_begin Before you start {mode}"
|
||||
RESPOND TYPE=command MSG="action:prompt_text 1. Nothing on the bed: no parts, no tools, plate seated."
|
||||
RESPOND TYPE=command MSG="action:prompt_text 2. Nozzle clean, no blob: it touches the bed at every point."
|
||||
RESPOND TYPE=command MSG="action:prompt_text 3. Keep hands out of the printer while it runs."
|
||||
{% if bed > 40 %}
|
||||
RESPOND TYPE=command MSG="action:prompt_text Note: the bed is at {bed|int} C. The reference runs were on a cold bed, so wait for it to cool unless you want this on purpose."
|
||||
{% endif %}
|
||||
RESPOND TYPE=command MSG="action:prompt_text It heats the nozzle to 150 C, homes, levels, wipes the nozzle on the brush and takes {'25' if mode == 'measure' else '17'} minutes. The configuration is not changed."
|
||||
RESPOND TYPE=command MSG="action:prompt_footer_button Back|TWIST_CALIBRATE|secondary"
|
||||
RESPOND TYPE=command MSG="action:prompt_footer_button All checked, start|_TWIST_START MODE={mode}|primary"
|
||||
RESPOND TYPE=command MSG="action:prompt_show"
|
||||
|
||||
[gcode_macro _TWIST_START]
|
||||
description: Start the twist script in the background (use TWIST_CALIBRATE)
|
||||
gcode:
|
||||
{% set mode = params.MODE|default('')|lower %}
|
||||
{% if mode not in ("measure", "verify") %}
|
||||
_ERROR MSG="_TWIST_START: MODE must be measure or verify"
|
||||
{% elif printer.print_stats.state in ("printing", "paused") %}
|
||||
_ERROR MSG="Twist calibration: a print is running" DISPLAY="Twist: not during a print"
|
||||
{% elif printer['gcode_macro _TWIST_STATE'].running %}
|
||||
_ERROR MSG="Twist calibration is already running. TWIST_CALIBRATE shows it, TWIST_STOP stops it." DISPLAY="Twist: already running"
|
||||
{% else %}
|
||||
M117 Twist {mode}: starting
|
||||
RESPOND TYPE=command MSG="action:prompt_begin Twist {mode} started"
|
||||
RESPOND TYPE=command MSG="action:prompt_text You can close this window: the run continues. The status line shows the progress, and a window opens with the result."
|
||||
RESPOND TYPE=command MSG="action:prompt_footer_button Stop the run|TWIST_STOP|error"
|
||||
RESPOND TYPE=command MSG="action:prompt_footer_button Close|_TWIST_CLOSE|secondary"
|
||||
RESPOND TYPE=command MSG="action:prompt_show"
|
||||
RUN_SHELL_COMMAND CMD=_twist_start PARAMS={mode}
|
||||
{% endif %}
|
||||
|
||||
[gcode_macro TWIST_STOP]
|
||||
description: Stop a running twist calibration: lifts the nozzle, nozzle heater off
|
||||
gcode:
|
||||
RESPOND TYPE=command MSG="action:prompt_end"
|
||||
M117 Twist: stopping
|
||||
RUN_SHELL_COMMAND CMD=_twist_stop
|
||||
# Also clears the flag when a run has died without clearing it itself
|
||||
SET_GCODE_VARIABLE MACRO=_TWIST_STATE VARIABLE=running VALUE=0
|
||||
@@ -1,4 +1,9 @@
|
||||
# Bed fans driven by the bed heater (based on Ellis' bed fan macros)
|
||||
#
|
||||
# During a print without a heated chamber the fans stay off while the bed heats,
|
||||
# soaks and prints: with the chamber open they only blow room air past the bed.
|
||||
# PRINT_WARMUP sets print_fans_off, _PRINT_CLEANUP clears it. The cooldown after
|
||||
# the print and heating the bed outside a print are not affected.
|
||||
|
||||
############### Config options ##################
|
||||
|
||||
@@ -7,6 +12,7 @@ variable_threshold: 50 # If bed temp target is above this threshold, fans will
|
||||
variable_fast: 1.0 # Fan speed once bed temp is reached
|
||||
variable_slow: 0.5 # Fan speed while bed is heating
|
||||
variable_cooldown_temp: 40 # NEW: fans stop below this temp
|
||||
variable_print_fans_off: False # set by PRINT_WARMUP for a print without a heated chamber
|
||||
gcode:
|
||||
|
||||
########## Aliases #########
|
||||
@@ -41,7 +47,8 @@ gcode:
|
||||
# Vars
|
||||
{% set THRESHOLD = printer["gcode_macro _BEDFANVARS"].threshold|int %}
|
||||
{% set COOLDOWN = printer["gcode_macro _BEDFANVARS"].cooldown_temp|int %}
|
||||
|
||||
{% set FANS_OFF = printer["gcode_macro _BEDFANVARS"].print_fans_off %}
|
||||
|
||||
{% if HEATER|lower == "extruder" %}
|
||||
M104 S{TARGET}
|
||||
|
||||
@@ -67,13 +74,13 @@ gcode:
|
||||
# Stop normal heating loop if running
|
||||
UPDATE_DELAYED_GCODE ID=bedfanloop DURATION=0
|
||||
|
||||
{% elif TARGET >= THRESHOLD %}
|
||||
{% elif TARGET >= THRESHOLD and not FANS_OFF %}
|
||||
# Heating above threshold
|
||||
BEDFANSSLOW
|
||||
UPDATE_DELAYED_GCODE ID=bedfanloop DURATION=1
|
||||
|
||||
{% else %}
|
||||
# Low temp request
|
||||
# Low temp request, or a print without a heated chamber
|
||||
BEDFANSOFF
|
||||
UPDATE_DELAYED_GCODE ID=bedfanloop DURATION=0
|
||||
{% endif %}
|
||||
@@ -93,9 +100,10 @@ gcode:
|
||||
{% set S = params.S|int %}
|
||||
# Vars
|
||||
{% set THRESHOLD = printer["gcode_macro _BEDFANVARS"].threshold|int %}
|
||||
|
||||
{% if S >= THRESHOLD %}
|
||||
BEDFANSSLOW # >= Threshold temp: Low speed fans while heating
|
||||
{% set FANS_ON = S >= THRESHOLD and not printer["gcode_macro _BEDFANVARS"].print_fans_off %}
|
||||
|
||||
{% if FANS_ON %}
|
||||
BEDFANSSLOW # >= Threshold temp: Low speed fans while heating
|
||||
{% else %}
|
||||
BEDFANSOFF # < Threshold temp: Turn bed fans off
|
||||
{% endif %}
|
||||
@@ -109,8 +117,8 @@ gcode:
|
||||
{% endif %}
|
||||
|
||||
# Post-heating fan speeds
|
||||
{% if S >= THRESHOLD %}
|
||||
BEDFANSFAST # >= Threshold temp: Higher speed fans after heating finished
|
||||
{% if FANS_ON %}
|
||||
BEDFANSFAST # >= Threshold temp: Higher speed fans after heating finished
|
||||
{% endif %}
|
||||
|
||||
# Replace M140 (Set Bed Temperature) to just be an alias of SET_HEATER_TEMPERATURE (which has associated bed fan logic if enabled)
|
||||
@@ -152,7 +160,7 @@ gcode:
|
||||
# Vars
|
||||
{% set THRESHOLD = printer["gcode_macro _BEDFANVARS"].threshold|int %}
|
||||
|
||||
{% if printer.heater_bed.target >= THRESHOLD %} # Continue only if target temp greater than threshold.
|
||||
{% if printer.heater_bed.target >= THRESHOLD and not printer["gcode_macro _BEDFANVARS"].print_fans_off %} # Continue only if target temp greater than threshold.
|
||||
{% if printer.heater_bed.temperature|int >= (printer.heater_bed.target|int - 1) %}
|
||||
BEDFANSFAST # If within 1 degree of target temp: Higher speed fans
|
||||
{% else %}
|
||||
|
||||
@@ -293,8 +293,12 @@ gcode:
|
||||
{% if heat_soak.complete %}
|
||||
{heat_soak.complete}
|
||||
{% endif %}
|
||||
# Not RESUME: that goes through AFC_RESUME, which restores AFC's saved
|
||||
# position. HEAT_SOAK pauses with PAUSE_BASE, so AFC saved nothing and
|
||||
# (seen 2026-11-04) sends the toolhead to X0 Y0 at up to 350 mm/s, just
|
||||
# before the _Z_CHECK guard arms.
|
||||
{% if printer['pause_resume'].is_paused %}
|
||||
RESUME
|
||||
_RESUME_PRINT
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% else %}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
# Printing
|
||||
[include print/pause_resume.cfg]
|
||||
[include print/filament.cfg]
|
||||
[include print/nozzle_guard.cfg] # bd_pressure nozzle collision guard (needs extras/bdp_guard.py)
|
||||
[include print/nozzle_guard.cfg] # bd_pressure nozzle collision guard (needs bdp_guard.py, bd_pressure repo)
|
||||
[include print/homing.cfg]
|
||||
[include print/idle_timeout.cfg]
|
||||
[include print/print_start_end.cfg]
|
||||
@@ -37,6 +37,7 @@
|
||||
[include afc/xy_safety_check.cfg]
|
||||
[include afc/lane_tools.cfg]
|
||||
[include afc/purge_check.cfg]
|
||||
[include afc/auto_resume.cfg] # resume by itself after an AFC buffer fault (purge check first, limited)
|
||||
[include afc/purge_until_empty.cfg]
|
||||
[include afc/flex_lanes.cfg] # TPU/TPE lanes: slower long moves
|
||||
|
||||
@@ -51,3 +52,7 @@
|
||||
[include leds/stealthburner_leds.cfg]
|
||||
[include sensors/motion_sensor.cfg]
|
||||
[include sensors/touch_compare.cfg] # TOUCH_COMPARE: Beacon contact vs bd_pressure (needs extras/bdp_touch.py)
|
||||
|
||||
# Calibration
|
||||
[include calibration/twist_check.cfg] # TWIST_CALIBRATE: axis twist compensation, with windows in Mainsail (runs scripts/twist_check.py)
|
||||
[include calibration/bed_scan_check.cfg] # BED_SCAN_CHECK, BED_MESH_CHECK: bumps and flatness; PRINT_START pauses on a failed check (needs extras/mesh_check.py)
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/bin/bash
|
||||
BASE_URL=$1
|
||||
FIELD=$2
|
||||
curl -sf -X POST "${BASE_URL}/api/v1/field/spool/${FIELD}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"name\": \"Pressure Advance\", \"field_type\": \"float\", \"default_value\": \"0\"}" \
|
||||
> /tmp/pa_setup_result 2>&1
|
||||
@@ -171,6 +171,9 @@
|
||||
# To see what's cached, and which lanes are missing a tracked
|
||||
# spool_id:
|
||||
# PA_STATUS
|
||||
#
|
||||
# After fitting another nozzle (values are saved per nozzle):
|
||||
# SET_NOZZLE SIZE=0.2
|
||||
########################################################################
|
||||
|
||||
# [save_variables] is defined once in ../save_variables.cfg (shared with Blobifier)
|
||||
@@ -190,18 +193,36 @@ variable_lane_names: "lane1,lane2,lane3,lane4,lane5"
|
||||
variable_fallback_nozzle_temp: 260
|
||||
# bd_pressure PA_CALIBRATE parameters -- tune to your printer/filament.
|
||||
# See https://pandapi3d.cn/bdpressure/home for guidance on these values.
|
||||
variable_max_volumetric: 25
|
||||
# Per nozzle, and only these sizes are accepted by SET_NOZZLE:
|
||||
# max_volumetric: test flow (mm3/s). The test time follows it: about 2 min a
|
||||
# lane at 25, 9 min at 5.
|
||||
# pa_step: PA_CALIBRATE tests 50 values, 0..49 x step (0.002: 0-0.098,
|
||||
# 0.004: 0-0.196).
|
||||
# The 0.2 values are starting estimates, not measured yet.
|
||||
variable_nozzle_test: {"0.4": {"max_volumetric": 25, "pa_step": 0.002}, "0.2": {"max_volumetric": 5, "pa_step": 0.004}}
|
||||
# Lower test flow (mm3/s) for materials that cannot extrude max_volumetric:
|
||||
# soft TPU buckles or slips in the extruder at 25. A key contained in the
|
||||
# lane's material (any case) applies; with several matches the lowest wins.
|
||||
variable_material_max_volumetric: {"tpu": 8, "tpe": 8, "flex": 8}
|
||||
# soft TPU buckles or slips in the extruder at 25; PETG (also PETG-CF) is
|
||||
# more viscous at its temperature, 12 matches its slicer flow limit
|
||||
# (spool 35, PETG-CF at 250C: PA 0.058 at 12, 2026-11-09). A key contained
|
||||
# in the lane's material (any case) applies; the lowest of these and the
|
||||
# nozzle's flow wins.
|
||||
variable_material_max_volumetric: {"tpu": 8, "tpe": 8, "flex": 8, "petg": 12}
|
||||
# Nozzle height (mm) for the test lines (PA_CALIBRATE keeps the current Z).
|
||||
# At 5 they are extruded in the air, clear of the bed and plate.
|
||||
variable_test_z: 5
|
||||
# AFC buffer fault detection during the test lines (0-10, 0 = off). At the
|
||||
# normal 8 the buffer faults after 30 mm in one state, and during the test it
|
||||
# needs far more to reach its other sensor (2026-11-07: ~80 s for the first
|
||||
# change), so every test paused with AFC NOT FEEDING. 2 still catches a lane
|
||||
# that stops feeding. Restored to the [AFC_buffer] config value after
|
||||
# PA_CALIBRATE, or by _PRINT_CLEANUP if the test stops with an error.
|
||||
variable_test_error_sensitivity: 2
|
||||
variable_acc_wall: 5000
|
||||
variable_travel_speed: 300
|
||||
variable_acc_to_decel_factor: 50
|
||||
# Minimum PA delta before we bother re-saving the cached value
|
||||
variable_write_threshold: 0.002
|
||||
# A calibration is rejected (nothing cached or written to Spoolman, the
|
||||
# previous PA is kept) when:
|
||||
# A calibration is rejected (nothing saved, the previous PA is kept) when:
|
||||
# - its result is the last PA_CALIBRATE test value: bdpressure.py found no
|
||||
# result and left the extruder at the end of its scan (0..49 x the PA
|
||||
# step: 0.098 at the default step, 0.196 for flexibles),
|
||||
@@ -209,94 +230,74 @@ variable_write_threshold: 0.002
|
||||
# - bd_pressure gave fewer than min_points readings or fewer than
|
||||
# min_distinct different ones (sensor silent or hung; needs
|
||||
# bdpressure_check.py, otherwise this check is skipped).
|
||||
variable_pa_step: 0.002 # PA_CALIBRATE tests 50 values: 0..49 x step
|
||||
# Wider range for materials whose PA can be above 0.098 (soft TPU measured
|
||||
# 0.094): same 50 lines and test time, coarser steps. Key contained in the
|
||||
# lane's material (any case); with several matches the largest step wins.
|
||||
# lane's material (any case); the largest of these and the nozzle's step wins.
|
||||
variable_material_pa_step: {"tpu": 0.004, "tpe": 0.004, "flex": 0.004}
|
||||
variable_min_points: 10
|
||||
variable_min_distinct: 8
|
||||
# PA applied when a rejected lane has no earlier cached value
|
||||
variable_fallback_pa: 0.04
|
||||
# Spoolman URL and the custom "extra" field name used to push calibrated
|
||||
# PA values back to the spool record (so the value travels with the
|
||||
# spool, not just with this printer's local save_variables cache).
|
||||
# Create the field once with: _PA_SETUP_SPOOLMAN_FIELD (see below).
|
||||
variable_spoolman_url: "http://localhost:7912"
|
||||
variable_spoolman_field: "pa_value"
|
||||
gcode: # intentionally empty -- variables only
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Spoolman write-back: push a calibrated PA value to a spool's "extra"
|
||||
# field, so the value travels with the spool (e.g. if you move it to a
|
||||
# different printer, or reinstall save_variables from scratch).
|
||||
#
|
||||
# Requires the custom field to exist once -- run _PA_SETUP_SPOOLMAN_FIELD
|
||||
# (below) a single time, or create it manually:
|
||||
# curl -X POST http://<spoolman_ip>:7912/api/v1/field/spool/pa_value -H "Content-Type: application/json" -d '{"name": "Pressure Advance", "field_type": "float", "default_value": "0"}'
|
||||
#
|
||||
# UNVERIFIED -- needs live testing the same way everything else in this
|
||||
# file has needed it. In particular: confirm curl and python3 are both
|
||||
# available in the shell shell_command runs in (they're standard on
|
||||
# MainsailOS/FluiddOS, but worth confirming), and confirm the merge-write
|
||||
# below doesn't clobber any other custom Spoolman fields you may have.
|
||||
# Fitted nozzle. A PA value only holds for the nozzle it was measured with, so
|
||||
# values are saved per nozzle and spool: pa_value_0_4_spool_15. The size is the
|
||||
# saved variable pa_nozzle, set by SET_NOZZLE after a swap. The slicer sends the
|
||||
# size of its profile to PRINT_WARMUP, and a mismatch stops the print before
|
||||
# anything heats. G-code without a size uses the saved one.
|
||||
# ---------------------------------------------------------------------------
|
||||
[gcode_shell_command _pa_write_spoolman]
|
||||
# HISTORICAL NOTE ON ARGUMENT OFFSET (no longer applicable here, kept
|
||||
# for context): an earlier version of this command ran the script
|
||||
# inline via `bash -c '<script>' arg1 arg2 ...`, which makes the FIRST
|
||||
# argument after the script string become $0 inside the script, not $1
|
||||
# -- a well-known bash gotcha, confirmed empirically while building
|
||||
# this file:
|
||||
# bash -c 'echo "0=$0 1=$1 2=$2"' alpha beta gamma
|
||||
# -> 0=alpha 1=beta 2=gamma (gamma, the 3rd arg, never reaches $3)
|
||||
# This command now invokes a real .sh FILE instead (`bash script.sh
|
||||
# arg1 arg2 ...`), which does NOT have this offset -- $1 really is the
|
||||
# first argument in that invocation form (also confirmed empirically).
|
||||
# So RUN_SHELL_COMMAND ... PARAMS="a b c d" maps cleanly to $1-$4 in
|
||||
# the script with no placeholder needed.
|
||||
#
|
||||
# WHY THIS CALLS AN EXTERNAL .sh FILE INSTEAD OF EMBEDDING PYTHON
|
||||
# INLINE: Klipper's config parser (Python's configparser) requires
|
||||
# EVERY physical line of a multi-line value to be indented, and strips
|
||||
# that indentation uniformly before passing the value to the shell.
|
||||
# Confirmed empirically while building this file: this dedenting
|
||||
# flattens ALL lines to the same level, which destroys the relative
|
||||
# indentation Python's try/except blocks need to remain valid syntax --
|
||||
# there is no way to embed multi-line, block-structured Python directly
|
||||
# inside a Klipper command: value. Putting the logic in a separate .sh
|
||||
# file sidesteps this entirely, since that file is never touched by
|
||||
# Klipper's config parser.
|
||||
#
|
||||
# The script ships in this folder (klipper-macros/pressure_advance/bd_pa_write_spoolman.sh);
|
||||
# install.sh makes it executable.
|
||||
command: bash ~/printer_data/config/klipper-macros/pressure_advance/bd_pa_write_spoolman.sh
|
||||
verbose: False
|
||||
|
||||
|
||||
[gcode_shell_command _pa_create_spoolman_field]
|
||||
# Same reasoning as _pa_write_spoolman above for using an external
|
||||
# script file -- see the note there. This one has no embedded Python,
|
||||
# so the only real issue was the closing quote sitting at column 0
|
||||
# (un-indented), which is also a config parsing error in Klipper's
|
||||
# parser -- every line of a multi-line value must be indented,
|
||||
# including the very last line.
|
||||
command: bash ~/printer_data/config/klipper-macros/pressure_advance/bd_pa_create_spoolman_field.sh
|
||||
verbose: False
|
||||
|
||||
|
||||
[gcode_macro _PA_SETUP_SPOOLMAN_FIELD]
|
||||
description: One-time setup -- creates the pa_value custom field in Spoolman
|
||||
# REQUIRES bd_pa_create_spoolman_field.sh to already exist on disk at
|
||||
# ~/printer_data/config/ -- see the one-time SSH setup instructions
|
||||
# given alongside this file. This macro just invokes that script; it
|
||||
# does not create it.
|
||||
[gcode_macro SET_NOZZLE]
|
||||
description: Set the fitted nozzle size, which selects its saved PA values (without SIZE: show it)
|
||||
# [SIZE=<mm>]
|
||||
gcode:
|
||||
{% set cfg = printer["gcode_macro _PA_CFG"] %}
|
||||
{action_respond_info("Creating Spoolman field '%s' at %s ..." % (cfg.spoolman_field, cfg.spoolman_url))}
|
||||
RUN_SHELL_COMMAND CMD=_pa_create_spoolman_field PARAMS="{cfg.spoolman_url} {cfg.spoolman_field}"
|
||||
{action_respond_info("Done. Verify with: curl %s/api/v1/field/spool" % cfg.spoolman_url)}
|
||||
{% set vars = printer.save_variables.variables %}
|
||||
{% set current = "%g" % vars["pa_nozzle"]|default(0.4)|float %}
|
||||
{% if not params.SIZE %}
|
||||
RESPOND MSG="Nozzle set: {current} mm. Change it with SET_NOZZLE SIZE=<mm>, sizes: {cfg.nozzle_test.keys()|join(', ')}"
|
||||
{% else %}
|
||||
{% set size = "%g" % params.SIZE|float %}
|
||||
{% if size not in cfg.nozzle_test %}
|
||||
_ERROR MSG="SET_NOZZLE: no PA test settings for {size} mm. Sizes: {cfg.nozzle_test.keys()|join(', ')} (variable_nozzle_test in _PA_CFG)" DISPLAY="Unknown nozzle size"
|
||||
{% elif printer.print_stats.state in ("printing", "paused") %}
|
||||
_ERROR MSG="SET_NOZZLE: not during a print, the nozzle stays {current} mm" DISPLAY="No SET_NOZZLE in a print"
|
||||
{% else %}
|
||||
SAVE_VARIABLE VARIABLE=pa_nozzle VALUE={size}
|
||||
RESPOND MSG="Nozzle set: {size} mm (was {current} mm)"
|
||||
_PA_APPLY_LOADED_LANE
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
[gcode_macro _PA_CHECK_NOZZLE]
|
||||
description: Stop the print when the size from the slicer is not the fitted nozzle
|
||||
# NOZZLE=<mm>
|
||||
gcode:
|
||||
{% set vars = printer.save_variables.variables %}
|
||||
{% set fitted = vars["pa_nozzle"]|default(0.4)|float %}
|
||||
{% set sliced = params.NOZZLE|float %}
|
||||
{% if (sliced - fitted)|abs > 0.001 %}
|
||||
_ERROR MSG="Print stopped: sliced for a {'%g' % sliced} mm nozzle, the printer is set to {'%g' % fitted} mm. Slice with the matching profile, or fit that nozzle and run SET_NOZZLE SIZE={'%g' % sliced}" DISPLAY="Nozzle mismatch, print stopped"
|
||||
{% endif %}
|
||||
|
||||
# Once: values saved before there were per-nozzle values were all measured with
|
||||
# the 0.4 nozzle. Copied at the first start with this macro, so the first print
|
||||
# does not calibrate every lane again. The old pa_value_spool_<id> lines stay in
|
||||
# the variables file; nothing reads them any more.
|
||||
[delayed_gcode _PA_MIGRATE_NOZZLE]
|
||||
initial_duration: 1
|
||||
gcode:
|
||||
{% set vars = printer.save_variables.variables %}
|
||||
{% if "pa_nozzle" not in vars %}
|
||||
{% for name, value in vars.items() %}
|
||||
{% if name.startswith("pa_value_spool_") and ("pa_value_0_4_spool_" ~ name[15:]) not in vars %}
|
||||
SAVE_VARIABLE VARIABLE={"pa_value_0_4_spool_" ~ name[15:]} VALUE={value}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
SAVE_VARIABLE VARIABLE=pa_nozzle VALUE=0.4
|
||||
RESPOND MSG="PA values moved to the 0.4 mm nozzle. Nozzle set: 0.4 mm"
|
||||
{% endif %}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -375,7 +376,7 @@ gcode:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PA cache, keyed by spool_id, stored via Klipper's own save_variables.
|
||||
# PA cache, keyed by nozzle and spool_id, stored via Klipper's own save_variables.
|
||||
# Requires [save_variables] (save_variables.cfg, see header notes).
|
||||
#
|
||||
# IMPORTANT: printer.save_variables.variables is read DIRECTLY inline in
|
||||
@@ -392,12 +393,13 @@ gcode:
|
||||
# value set earlier in the same template render.
|
||||
# ---------------------------------------------------------------------------
|
||||
[gcode_macro _PA_CACHE_SET]
|
||||
description: Internal -- stores a PA value for a spool_id
|
||||
# SPOOL_ID=<int> PA=<float>
|
||||
description: Internal -- stores a PA value for a nozzle and spool_id
|
||||
# SPOOL_ID=<int> NOZZLE=<mm> PA=<float>
|
||||
gcode:
|
||||
{% set spool_id = params.SPOOL_ID|default(0)|int %}
|
||||
{% set nozzle = "%g" % params.NOZZLE|float %}
|
||||
{% set pa = params.PA|default(0.0)|float %}
|
||||
{% set varname = "pa_value_spool_" ~ spool_id %}
|
||||
{% set varname = "pa_value_" ~ nozzle|replace(".", "_") ~ "_spool_" ~ spool_id %}
|
||||
SAVE_VARIABLE VARIABLE={varname} VALUE={pa}
|
||||
|
||||
|
||||
@@ -418,7 +420,8 @@ gcode:
|
||||
{% set force = params.FORCE|default(0)|int %}
|
||||
{% set vars = printer.save_variables.variables %}
|
||||
{% set spool_id = vars["pa_lane_" ~ lane ~ "_spool_id"]|default(0)|int %}
|
||||
{% set cached = ("pa_value_spool_" ~ spool_id) in vars %}
|
||||
{% set nozzle = "%g" % vars["pa_nozzle"]|default(0.4)|float %}
|
||||
{% set cached = ("pa_value_" ~ nozzle|replace(".", "_") ~ "_spool_" ~ spool_id) in vars %}
|
||||
{% set key = "AFC_stepper " ~ lane %}
|
||||
{% set afc_spool = printer[key].spool_id|default(none, true) if key in printer else none %}
|
||||
{% if lane and spool_id > 0 and (force or not cached) and afc_spool %}
|
||||
@@ -443,12 +446,14 @@ gcode:
|
||||
{% elif spool_id == 0 %}
|
||||
{action_respond_info("LANE_CALIBRATE_PA: no spool_id recorded for %s yet. Run SET_SPOOL_ID LANE=%s SPOOL_ID=<id> then _PA_TRACK_LANE_SPOOL LANE=%s SPOOL_ID=<id>." % (lane, lane, lane))}
|
||||
{% else %}
|
||||
{% set pa_varname = "pa_value_spool_" ~ spool_id %}
|
||||
{% set nozzle = "%g" % vars["pa_nozzle"]|default(0.4)|float %}
|
||||
{% set test = cfg.nozzle_test[nozzle] %}
|
||||
{% set pa_varname = "pa_value_" ~ nozzle|replace(".", "_") ~ "_spool_" ~ spool_id %}
|
||||
{% set cache_found = pa_varname in vars %}
|
||||
{% set cached_pa = vars[pa_varname]|float if cache_found else 0.0 %}
|
||||
|
||||
{% if cache_found and force == 0 %}
|
||||
{action_respond_info("Using cached PA=%.4f for %s (spool %d)" % (cached_pa, lane, spool_id))}
|
||||
{action_respond_info("Using cached PA=%.4f for %s (spool %d, %s mm nozzle)" % (cached_pa, lane, spool_id, nozzle))}
|
||||
SET_PRESSURE_ADVANCE ADVANCE={cached_pa}
|
||||
{% else %}
|
||||
CHANGE_TOOL LANE={lane}
|
||||
@@ -462,30 +467,44 @@ gcode:
|
||||
{% set target = printer.extruder.target|default(0)|float %}
|
||||
{% set nozzle_temp = lane_temp if lane_temp > 0 else (target if target > 0 else cfg.fallback_nozzle_temp|float) %}
|
||||
{% set material = lane_obj.material|default("", true)|string|lower %}
|
||||
{% set vol = namespace(max=cfg.max_volumetric|float) %}
|
||||
{% set vol = namespace(max=test.max_volumetric|float) %}
|
||||
{% for key, flow in cfg.material_max_volumetric.items() %}
|
||||
{% if key in material and flow|float < vol.max %}
|
||||
{% set vol.max = flow|float %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
{% set step = namespace(pa=cfg.pa_step|float) %}
|
||||
{% set step = namespace(pa=test.pa_step|float) %}
|
||||
{% for key, s in cfg.material_pa_step.items() %}
|
||||
{% if key in material and s|float > step.pa %}
|
||||
{% set step.pa = s|float %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
{action_respond_info("Calibrating PA for %s (spool %d) at %.0fC, %g mm3/s, PA 0-%.3f..." % (lane, spool_id, nozzle_temp, vol.max, 49 * step.pa))}
|
||||
{action_respond_info("Calibrating PA for %s (spool %d, %s mm nozzle) at %.0fC, %g mm3/s, PA 0-%.3f..." % (lane, spool_id, nozzle, nozzle_temp, vol.max, 49 * step.pa))}
|
||||
M117 Calibrating PA: {lane}
|
||||
|
||||
G1 Z50 F3000
|
||||
G4 P400
|
||||
G1 X30 Y349 Z10 F3000
|
||||
G4 P400
|
||||
G1 Z0 F3000
|
||||
G1 Z{cfg.test_z} F3000
|
||||
G4 P400
|
||||
# Buffer fault detection for the test (see test_error_sensitivity).
|
||||
# lowered=True lets _FIRST_LAYER_FAULT_DETECTION ON=0 restore it,
|
||||
# here and in _PRINT_CLEANUP when the test stops with an error.
|
||||
{% set fl = printer["gcode_macro _FIRST_LAYER_FAULT_DETECTION"] %}
|
||||
{% set buf_key = "afc_buffer " ~ fl.buffer|lower %}
|
||||
{% set normal_sens = printer.configfile.settings[buf_key].filament_error_sensitivity|default(0)|float if buf_key in printer.configfile.settings else 0 %}
|
||||
{% set lower_sens = normal_sens > 0 and cfg.test_error_sensitivity|float != normal_sens %}
|
||||
{% if lower_sens %}
|
||||
AFC_SET_ERROR_SENSITIVITY BUFFER={fl.buffer} SENSITIVITY={cfg.test_error_sensitivity}
|
||||
SET_GCODE_VARIABLE MACRO=_FIRST_LAYER_FAULT_DETECTION VARIABLE=lowered VALUE=True
|
||||
{% endif %}
|
||||
PA_CALIBRATE NOZZLE_TEMP={nozzle_temp} MAX_VOLUMETRIC={vol.max} ACC_WALL={cfg.acc_wall} TRAVEL_SPEED={cfg.travel_speed} ACC_TO_DECEL_FACTOR={cfg.acc_to_decel_factor} PA_STEP={step.pa}
|
||||
{% if lower_sens %}
|
||||
_FIRST_LAYER_FAULT_DETECTION ON=0
|
||||
{% endif %}
|
||||
|
||||
# IMPORTANT: we do NOT read printer.extruder.pressure_advance
|
||||
# here. Klipper fully evaluates a macro's Jinja2 template
|
||||
@@ -505,7 +524,7 @@ gcode:
|
||||
# triggered (and its own template is rendered), PA_CALIBRATE
|
||||
# above has already finished and printer.extruder.pressure_advance
|
||||
# is current.
|
||||
_PA_AFTER_CALIBRATE LANE={lane} SPOOL_ID={spool_id} CACHE_FOUND={1 if cache_found else 0} CACHED_PA={cached_pa} SWEEP_END={49 * step.pa}
|
||||
_PA_AFTER_CALIBRATE LANE={lane} SPOOL_ID={spool_id} NOZZLE={nozzle} CACHE_FOUND={1 if cache_found else 0} CACHED_PA={cached_pa} SWEEP_END={49 * step.pa}
|
||||
BLOBIFIER_CLEAN
|
||||
G4 P400
|
||||
G1 Z10 F3000
|
||||
@@ -516,14 +535,15 @@ gcode:
|
||||
|
||||
[gcode_macro _PA_AFTER_CALIBRATE]
|
||||
description: Internal -- runs immediately after PA_CALIBRATE completes; reads the fresh PA value and caches it
|
||||
# LANE=<lane_name> SPOOL_ID=<int> CACHE_FOUND=<0|1> CACHED_PA=<float> SWEEP_END=<last PA tested>
|
||||
# LANE=<lane_name> SPOOL_ID=<int> NOZZLE=<mm> CACHE_FOUND=<0|1> CACHED_PA=<float> SWEEP_END=<last PA tested>
|
||||
gcode:
|
||||
{% set lane = params.LANE|default("")|string %}
|
||||
{% set spool_id = params.SPOOL_ID|default(0)|int %}
|
||||
{% set cache_found = params.CACHE_FOUND|default(0)|int %}
|
||||
{% set cached_pa = params.CACHED_PA|default(0.0)|float %}
|
||||
{% set cfg = printer["gcode_macro _PA_CFG"] %}
|
||||
{% set sweep_end = params.SWEEP_END|default(49 * cfg.pa_step|float)|float %}
|
||||
{% set sweep_end = params.SWEEP_END|float %}
|
||||
{% set nozzle = "%g" % params.NOZZLE|float %}
|
||||
|
||||
# This template is evaluated only once this macro is actually
|
||||
# triggered -- which happens after PA_CALIBRATE (queued earlier by
|
||||
@@ -556,16 +576,14 @@ gcode:
|
||||
_WARN MSG="PA calibration for {lane} (spool {spool_id}) rejected: {problems|join('; ')}. Nothing saved; using PA={'%.4f' % keep} ({'cached' if use_cache else 'fallback'}). Fix the cause, then LANE_CALIBRATE_PA LANE={lane} FORCE=1" DISPLAY="PA cal rejected: {lane}, see console"
|
||||
SET_PRESSURE_ADVANCE ADVANCE={keep}
|
||||
{% else %}
|
||||
{action_respond_info("Calibration complete for %s: PA=%.4f" % (lane, new_pa))}
|
||||
{action_respond_info("Calibration complete for %s (%s mm nozzle): PA=%.4f" % (lane, nozzle, new_pa))}
|
||||
M117 PA cal done: {new_pa|round(4)}
|
||||
|
||||
{% set delta = (new_pa - cached_pa)|abs if cache_found else 999 %}
|
||||
{% if delta > cfg.write_threshold|float %}
|
||||
_PA_CACHE_SET SPOOL_ID={spool_id} PA={new_pa}
|
||||
{action_respond_info("Writing PA=%.4f to Spoolman spool %d" % (new_pa, spool_id))}
|
||||
RUN_SHELL_COMMAND CMD=_pa_write_spoolman PARAMS="{spool_id} {cfg.spoolman_url} {cfg.spoolman_field} {new_pa}"
|
||||
_PA_CACHE_SET SPOOL_ID={spool_id} NOZZLE={nozzle} PA={new_pa}
|
||||
{% else %}
|
||||
{action_respond_info("PA change below threshold (%.4f), skipping cache/Spoolman write" % cfg.write_threshold|float)}
|
||||
{action_respond_info("PA change below threshold (%.4f), keeping the saved value" % cfg.write_threshold|float)}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
@@ -691,14 +709,15 @@ gcode:
|
||||
{% set spool_id = vars[lane_varname]|default(0)|int if lane_varname in vars else 0 %}
|
||||
|
||||
{% if spool_id > 0 %}
|
||||
{% set pa_varname = "pa_value_spool_" ~ spool_id %}
|
||||
{% set nozzle = "%g" % vars["pa_nozzle"]|default(0.4)|float %}
|
||||
{% set pa_varname = "pa_value_" ~ nozzle|replace(".", "_") ~ "_spool_" ~ spool_id %}
|
||||
{% if pa_varname in vars %}
|
||||
{% set cached_pa = vars[pa_varname]|float %}
|
||||
SET_PRESSURE_ADVANCE ADVANCE={cached_pa}
|
||||
{action_respond_info("Lane %s loaded: applied cached PA=%.4f (spool %d)" % (lane, cached_pa, spool_id))}
|
||||
{action_respond_info("Lane %s loaded: applied cached PA=%.4f (spool %d, %s mm nozzle)" % (lane, cached_pa, spool_id, nozzle))}
|
||||
M117 PA: {lane} = {cached_pa|round(4)}
|
||||
{% else %}
|
||||
{action_respond_info("Lane %s loaded: spool %d has no cached PA yet. Run LANE_CALIBRATE_PA LANE=%s or PA_CALIBRATE_ALL_LANES." % (lane, spool_id, lane))}
|
||||
{action_respond_info("Lane %s loaded: spool %d has no PA for the %s mm nozzle yet, PA stays %.4f. Run LANE_CALIBRATE_PA LANE=%s or PA_CALIBRATE_ALL_LANES; a print start does this itself." % (lane, spool_id, nozzle, printer.extruder.pressure_advance|float, lane))}
|
||||
{% endif %}
|
||||
{% else %}
|
||||
{action_respond_info("Lane %s loaded: no spool_id recorded yet (run SET_SPOOL_ID first)." % lane)}
|
||||
@@ -726,15 +745,16 @@ gcode:
|
||||
{% set cfg = printer["gcode_macro _PA_CFG"] %}
|
||||
{% set lane_list = cfg.lane_names.split(",") %}
|
||||
{% set vars = printer.save_variables.variables %}
|
||||
{% set nozzle = "%g" % vars["pa_nozzle"]|default(0.4)|float %}
|
||||
|
||||
{action_respond_info("=== PA Status ===")}
|
||||
{action_respond_info("=== PA Status, %s mm nozzle ===" % nozzle)}
|
||||
{% for lane in lane_list %}
|
||||
{% set lane = lane.strip() %}
|
||||
{% if lane != "" %}
|
||||
{% set spool_varname = "pa_lane_" ~ lane ~ "_spool_id" %}
|
||||
{% set spool_id = vars[spool_varname]|default(0)|int if spool_varname in vars else 0 %}
|
||||
{% if spool_id > 0 %}
|
||||
{% set pa_varname = "pa_value_spool_" ~ spool_id %}
|
||||
{% set pa_varname = "pa_value_" ~ nozzle|replace(".", "_") ~ "_spool_" ~ spool_id %}
|
||||
{% if pa_varname in vars %}
|
||||
{action_respond_info(" %s (spool %d): PA=%.4f cached" % (lane, spool_id, vars[pa_varname]|float))}
|
||||
{% else %}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
#!/bin/bash
|
||||
SPOOL_ID=$1
|
||||
BASE_URL=$2
|
||||
FIELD=$3
|
||||
PA_VALUE=$4
|
||||
CURRENT=$(curl -sf "${BASE_URL}/api/v1/spool/${SPOOL_ID}" 2>/dev/null)
|
||||
EXTRA=$(echo "$CURRENT" | python3 -c "
|
||||
import sys, json
|
||||
try:
|
||||
d = json.load(sys.stdin)
|
||||
e = d.get('extra', {})
|
||||
e['$FIELD'] = '$PA_VALUE'
|
||||
print(json.dumps(e))
|
||||
except Exception:
|
||||
print(json.dumps({'$FIELD': '$PA_VALUE'}))
|
||||
" 2>/dev/null)
|
||||
if [ -z "$EXTRA" ]; then
|
||||
EXTRA="{\"$FIELD\": \"$PA_VALUE\"}"
|
||||
fi
|
||||
curl -sf -X PATCH "${BASE_URL}/api/v1/spool/${SPOOL_ID}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"extra\": $EXTRA}" > /tmp/pa_spoolman_write_result 2>&1
|
||||
@@ -117,7 +117,9 @@ gcode:
|
||||
G21
|
||||
M83
|
||||
M109 S{NOZZLE_TEMP}
|
||||
G1 E4
|
||||
# At the test flow. Without F this ran at the speed of the move before
|
||||
# (F3000 in LANE_CALIBRATE_PA: 120 mm3/s), too much for a small nozzle.
|
||||
G1 E4 F{MAX_VOLUMETRIC / 2.405 * 60}
|
||||
SET_PRESSURE_ADVANCE ADVANCE=0.04; Override pressure advance value
|
||||
SET_VELOCITY_LIMIT ACCEL={ACC_WALL} ACCEL_TO_DECEL={ACC_TO_DEC}
|
||||
SET_VELOCITY_LIMIT ACCEL={ACC_WALL} MINIMUM_CRUISE_RATIO={MIN_CRUISE}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Nozzle collision guard: bd_pressure watches the nozzle force during moves
|
||||
# that must not touch anything (needs extras/bdp_guard.py and the bd_pressure
|
||||
# load-check firmware). See extras/bdp_guard.py.
|
||||
# that must not touch anything (needs bdp_guard.py from the bd_pressure repo,
|
||||
# klipper/, and its load-check firmware). See klipper/load_check/README.md there.
|
||||
#
|
||||
# mode: stop shuts Klipper down on a touch; log only measures and reports
|
||||
# each phase (console and klippy.log, "bdp_guard:"). A phase can override it
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
# PAUSE -> AFC_PAUSE (saves position, z-hop) -> this PAUSE -> PAUSE_BASE
|
||||
# RESUME -> AFC_RESUME -> this RESUME -> HEAT_SOAK_RESUME -> _RESUME_PRINT
|
||||
# -> RESUME_BASE, then AFC restores the saved position
|
||||
# A finished HEAT_SOAK calls _RESUME_PRINT directly: AFC saved no position for
|
||||
# its pause, so AFC_RESUME would send the toolhead to X0 Y0.
|
||||
# RESUME is defined only here: heating/heat_soak.cfg used to define its own,
|
||||
# which replaced this one completely (no unretract, no fan restore).
|
||||
# After a PAUSE, _RESUME_PRINT purges into the Blobifier with the purge check
|
||||
@@ -14,6 +16,12 @@
|
||||
# (the lane AFC was loading when a tool change failed, otherwise the loaded
|
||||
# lane), and RESUME stops with an error when another lane (or none) is loaded.
|
||||
# RESUME LANE_CHECK=0 resumes anyway (e.g. after remapping with SET_MAP).
|
||||
# An AFC "NOT FEEDING" buffer fault pause (not "CLOG DETECTED") during a
|
||||
# print runs this RESUME by itself after a few seconds, within limits
|
||||
# (afc/auto_resume.cfg).
|
||||
# A failed bed check in PRINT_START (calibration/bed_scan_check.cfg) pauses with
|
||||
# _BED_CHECK_STATE.pending set: PAUSE then only pauses, and RESUME runs
|
||||
# PRINT_START again instead of this chain's purge and lane check.
|
||||
|
||||
# https://klipperscreen.readthedocs.io/en/latest/macros/#recommended
|
||||
[gcode_macro PAUSE]
|
||||
@@ -23,7 +31,9 @@ variable_saved_fan_speed: 0.0
|
||||
variable_parked: False # set by PAUSE, used by _RESUME_PRINT
|
||||
variable_expected_lane: '' # AFC lane the print needs after RESUME ('' = no check)
|
||||
gcode:
|
||||
{% if not printer.pause_resume.is_paused %}
|
||||
{% if printer["gcode_macro _BED_CHECK_STATE"].pending %}
|
||||
PAUSE_BASE
|
||||
{% elif not printer.pause_resume.is_paused %}
|
||||
# AFC sets next_lane during a tool change and still has it when a failed
|
||||
# change pauses the print; it clears it once CHANGE_TOOL returns
|
||||
{% if 'AFC' in printer %}
|
||||
@@ -44,6 +54,9 @@ gcode:
|
||||
_STATUS STATE=paused
|
||||
# Set fan to S28 (28/255 ≈ 0.1098)
|
||||
M106 S28
|
||||
{% if 'gcode_macro _AUTO_RESUME_ARM' in printer %}
|
||||
_AUTO_RESUME_ARM ; AFC buffer fault: resume by itself after the purge check (afc/auto_resume.cfg)
|
||||
{% endif %}
|
||||
{% else %}
|
||||
PAUSE_BASE
|
||||
{% endif %}
|
||||
@@ -52,7 +65,11 @@ gcode:
|
||||
description: Resume the print (while HEAT_SOAK runs: skip the soak phase)
|
||||
rename_existing: RESUME_BASE
|
||||
gcode:
|
||||
HEAT_SOAK_RESUME ON_RESUME=_RESUME_PRINT {rawparams}
|
||||
{% if printer["gcode_macro _BED_CHECK_STATE"].pending %}
|
||||
_BED_CHECK_RETRY
|
||||
{% else %}
|
||||
HEAT_SOAK_RESUME ON_RESUME=_RESUME_PRINT {rawparams}
|
||||
{% endif %}
|
||||
|
||||
[gcode_macro _RESUME_PRINT]
|
||||
description: Resume after PAUSE: purge and check (or unretract), restore the part fan, continue the print
|
||||
@@ -92,6 +109,9 @@ gcode:
|
||||
{% endif %}
|
||||
SET_GCODE_VARIABLE MACRO=PAUSE VARIABLE=parked VALUE=False
|
||||
SET_GCODE_VARIABLE MACRO=PAUSE VARIABLE=expected_lane VALUE="''"
|
||||
{% if 'gcode_macro _AUTO_RESUME_CLEAR_FAULT' in printer %}
|
||||
_AUTO_RESUME_CLEAR_FAULT
|
||||
{% endif %}
|
||||
# Clear the pause reason from the display (no comment on an M117 line: it would show)
|
||||
M117
|
||||
{% endif %}
|
||||
|
||||
@@ -9,8 +9,10 @@
|
||||
# PRINT_START runs on a soaked bed:
|
||||
# PRINT_WARMUP bed heats while the nozzle cools and the printer homes,
|
||||
# wait for the bed, HEAT_SOAK
|
||||
# PRINT_START QGL, Z, contact Z calibration, mesh, load the initial tool,
|
||||
# PA for all lanes, XY reference
|
||||
# PRINT_START QGL, Z, contact Z calibration, mesh, bed check (a failed
|
||||
# check pauses, RESUME runs PRINT_START again, see
|
||||
# calibration/bed_scan_check.cfg), then _PRINT_START_FINISH:
|
||||
# load the initial tool, PA for all lanes, XY reference
|
||||
# The filament is loaded after the Z calibration, so the contact always
|
||||
# touches a clean nozzle that has not been oozing at 150C for minutes.
|
||||
# Chamber prints are the exception: PRINT_WARMUP loads and purges the first
|
||||
@@ -24,8 +26,14 @@ gcode:
|
||||
{% set target_chamber = params.CHAMBER|default("0")|int %}
|
||||
{% set initial_tool = params.TOOL|default("0")|int %}
|
||||
|
||||
# First, so a wrong nozzle stops the print before anything heats
|
||||
{% if params.NOZZLE %}
|
||||
_PA_CHECK_NOZZLE NOZZLE={params.NOZZLE}
|
||||
{% endif %}
|
||||
|
||||
RESET_FAILURE
|
||||
CLEAR_PAUSE
|
||||
_BED_CHECK_RESET
|
||||
# Clear what an earlier print or error left on the display
|
||||
M117
|
||||
|
||||
@@ -37,14 +45,12 @@ gcode:
|
||||
SKEW_PROFILE LOAD=Califlower
|
||||
M106 S0
|
||||
|
||||
# Bed fans only help to heat a closed chamber: off for this print without
|
||||
# one (heating/bed_fans.cfg). Set before the bed target, which reads it.
|
||||
SET_GCODE_VARIABLE MACRO=_BEDFANVARS VARIABLE=print_fans_off VALUE={target_chamber <= 30}
|
||||
|
||||
# Bed first, so it heats during the rest of the warmup
|
||||
{% if target_bed < 60 %}
|
||||
RESPOND MSG="Using PID for <60°C bed"
|
||||
SET_HEATER_TEMPERATURE HEATER=heater_bed TARGET={target_bed} PID_KP=33.606 PID_KI=0.694 PID_KD=407.058
|
||||
{% else %}
|
||||
RESPOND MSG="Using PID for ≥60°C bed"
|
||||
SET_HEATER_TEMPERATURE HEATER=heater_bed TARGET={target_bed} pid_Kp=46.843 pid_Ki=2.002 pid_Kd=274.034
|
||||
{% endif %}
|
||||
SET_HEATER_TEMPERATURE HEATER=heater_bed TARGET={target_bed}
|
||||
|
||||
# Only to get the toolhead over the bed for the soak; the Z that counts
|
||||
# is the contact calibration in PRINT_START on the soaked bed
|
||||
@@ -193,10 +199,14 @@ gcode:
|
||||
RESUME_BASE
|
||||
|
||||
[gcode_macro PRINT_START]
|
||||
description: Print start after HEAT_SOAK: QGL, Z calibration, mesh, load the initial tool, PA
|
||||
description: Print start after HEAT_SOAK: QGL, Z calibration, mesh, bed check, then _PRINT_START_FINISH
|
||||
gcode:
|
||||
{% set target_extruder = params.EXTRUDER|int %}
|
||||
{% set initial_tool = params.TOOL|default("0")|int %}
|
||||
# Rendered while this line of the print file runs: the start of the line,
|
||||
# where a retry after a failed bed check goes back to. -1: not from a file.
|
||||
{% set sd = printer.virtual_sdcard %}
|
||||
{% set file_pos = sd.file_position if sd.is_active else -1 %}
|
||||
|
||||
RESPOND MSG="print start macro continued"
|
||||
_LIGHTS_ON
|
||||
@@ -235,6 +245,35 @@ gcode:
|
||||
# From here on the nozzle extrudes and AFC cuts and loads: guard off
|
||||
_GUARD_OFF
|
||||
|
||||
BED_MESH_CHECK
|
||||
_PRINT_START_GATE EXTRUDER={target_extruder} TOOL={initial_tool} FILE_POS={file_pos}
|
||||
|
||||
# Separate macro: rendered after BED_MESH_CHECK has run. Pausing does not stop
|
||||
# a running macro, so what follows the check must not be in PRINT_START itself.
|
||||
[gcode_macro _PRINT_START_GATE]
|
||||
description: Helper for PRINT_START: pause when the bed check failed, else go on with _PRINT_START_FINISH
|
||||
gcode:
|
||||
{% set check = printer.mesh_check %}
|
||||
{% set ignore = printer["gcode_macro _BED_CHECK_STATE"].ignore %}
|
||||
{% set file_pos = params.FILE_POS|int %}
|
||||
{% if check.result == 'fail' and not ignore and file_pos >= 0 %}
|
||||
_BED_CHECK_PAUSE FILE_POS={file_pos}
|
||||
{% else %}
|
||||
{% if check.result == 'fail' %}
|
||||
_WARN MSG="Bed check failed, continuing: {check.summary}" DISPLAY="Bed check failed, continuing"
|
||||
{% elif check.result != 'ok' %}
|
||||
_WARN MSG="Bed check not done, continuing: {check.summary}" DISPLAY="Bed check not done"
|
||||
{% endif %}
|
||||
_BED_CHECK_RESET
|
||||
_PRINT_START_FINISH EXTRUDER={params.EXTRUDER} TOOL={params.TOOL}
|
||||
{% endif %}
|
||||
|
||||
[gcode_macro _PRINT_START_FINISH]
|
||||
description: Helper for PRINT_START after the bed check: load the initial tool, PA, XY reference
|
||||
gcode:
|
||||
{% set target_extruder = params.EXTRUDER|int %}
|
||||
{% set initial_tool = params.TOOL|default("0")|int %}
|
||||
|
||||
# Heat over the bucket, then undo the retracts of the previous PRINT_END
|
||||
_STATUS STATE=heating_extruder
|
||||
BLOBIFIER_PARK
|
||||
@@ -267,6 +306,11 @@ gcode:
|
||||
# ("AFC NOT FEEDING"); the slicer switches it back at layer 2
|
||||
_FIRST_LAYER_FAULT_DETECTION ON=1
|
||||
|
||||
# From here on an AFC buffer fault pause resumes by itself (afc/auto_resume.cfg)
|
||||
{% if 'gcode_macro _AUTO_RESUME_ACTIVE' in printer %}
|
||||
_AUTO_RESUME_ACTIVE ON=1
|
||||
{% endif %}
|
||||
|
||||
RESPOND MSG="starting"
|
||||
_STATUS STATE=printing
|
||||
|
||||
@@ -286,7 +330,7 @@ gcode:
|
||||
|
||||
M400 ; wait for buffer to clear
|
||||
G92 E0 ; zero the extruder
|
||||
_NOZZLE_RETRACT ; so the nozzle does not leak while cooling down
|
||||
_NOZZLE_RETRACT LENGTH=2 ; so the nozzle does not leak while cooling down (plus the slicer's own retract)
|
||||
|
||||
TURN_OFF_HEATERS
|
||||
iHEATER_OFF ; Turns off the chamber heater
|
||||
@@ -307,9 +351,11 @@ gcode:
|
||||
|
||||
# End-of-print cleanup shared by PRINT_END and CANCEL_PRINT
|
||||
[gcode_macro _PRINT_CLEANUP]
|
||||
description: Heaters (incl. chamber heater) and part fan off, flow back to 100%, bdwidth off, mesh and skew cleared, nozzle guard off
|
||||
description: Heaters (incl. chamber heater) and part fan off, flow back to 100%, bdwidth off, mesh and skew cleared, nozzle guard off, AFC runouts cleared, auto-resume off, SpoolSense tag update
|
||||
gcode:
|
||||
_GUARD_OFF ; a print start that failed while it was armed
|
||||
_BED_CHECK_RESET ; cancelled while the bed check had it paused
|
||||
SET_GCODE_VARIABLE MACRO=_BEDFANVARS VARIABLE=print_fans_off VALUE=False
|
||||
TURN_OFF_HEATERS
|
||||
iHEATER_OFF ; stops the chamber heater control loop too
|
||||
M107
|
||||
@@ -323,6 +369,21 @@ gcode:
|
||||
SET_GCODE_VARIABLE MACRO=_PURGE_CHECK_CFG VARIABLE=ignore_missing_sensor VALUE=False
|
||||
{% endif %}
|
||||
_FIRST_LAYER_FAULT_DETECTION ON=0 ; a print that ended during the first layer
|
||||
{% if 'gcode_macro _AUTO_RESUME_ACTIVE' in printer %}
|
||||
_AUTO_RESUME_ACTIVE ON=0 ; also stops a pending automatic resume
|
||||
{% endif %}
|
||||
# Infinite spool is set up per print (SET_RUNOUT): clear every lane's runout
|
||||
{% if 'AFC' in printer %}
|
||||
{% for lane in printer.AFC.lanes|default([]) if printer["AFC_stepper " ~ lane].runout_lane|default(none) %}
|
||||
SET_RUNOUT LANE={lane} RUNOUT=NONE
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
# SpoolSense (spoolsense.cfg in the config folder, not in this repo): the
|
||||
# middleware deducts the filament of this print (also a cancelled one) and
|
||||
# writes it to the spool's NFC tag at its next scan
|
||||
{% if 'gcode_macro UPDATE_TAG' in printer %}
|
||||
UPDATE_TAG
|
||||
{% endif %}
|
||||
|
||||
# AFC buffer fault detection (filament_error_sensitivity, 0-10, higher =
|
||||
# pauses sooner) with its own value during the first layer.
|
||||
|
||||
+67
-5
@@ -1,9 +1,71 @@
|
||||
# MCU firmware update scripts
|
||||
# Scripts
|
||||
|
||||
`twist_check.py` is the axis twist calibration: start it with the macro
|
||||
`TWIST_CALIBRATE` in Mainsail, and see [twist_check.md](twist_check.md) for how
|
||||
to use it. The rest of this page is about MCU firmware updates.
|
||||
|
||||
# MCU firmware updates: aldis
|
||||
|
||||
Klipper firmware on the MCUs is updated with
|
||||
[aldis](https://github.com/mjonuschat/aldis) (GPL-3.0). It finds every MCU in
|
||||
the running Klipper/Moonraker setup, compares its firmware with the Klipper
|
||||
checkout in `~/klipper`, and builds and flashes only the ones that are out of
|
||||
date, using the build config each MCU reports itself. It stops Klipper only
|
||||
for the flash, and shows its plan first. It also updates Beacon's firmware.
|
||||
|
||||
Its source is included as a git submodule in `external/aldis`, pinned to the
|
||||
release in use (v0.4.0). On the Pi you run the released program instead,
|
||||
installed in `~/aldis`; the submodule stays empty there (Moonraker does not
|
||||
fetch submodules), which is fine. To get the source on a PC:
|
||||
`git submodule update --init`.
|
||||
|
||||
## Install (once, on the Pi)
|
||||
|
||||
```bash
|
||||
mkdir -p ~/aldis && curl -fL "https://github.com/mjonuschat/aldis/releases/latest/download/aldis-$(uname -m)-linux.tar.xz" | tar xJ -C ~/aldis --strip-components=1 && chmod +x ~/aldis/aldis
|
||||
```
|
||||
|
||||
```bash
|
||||
sudo ~/aldis/aldis setup
|
||||
```
|
||||
|
||||
`setup` installs udev rules for the USB bootloaders and a narrow sudo rule so
|
||||
aldis can stop and start Klipper. `sudo ~/aldis/aldis setup --check` verifies
|
||||
them. Optional: `sudo ~/aldis/aldis setup --agent` runs it as a service that
|
||||
the web UI can manage (restart Moonraker once afterwards).
|
||||
|
||||
## Use (between prints only)
|
||||
|
||||
```bash
|
||||
~/aldis/aldis status
|
||||
```
|
||||
|
||||
```bash
|
||||
~/aldis/aldis update
|
||||
```
|
||||
|
||||
- `status`: which MCUs it found and whether their firmware is current (reads only).
|
||||
- `update`: builds and flashes the outdated MCUs, asking per MCU.
|
||||
`update --pull` also pulls Klipper first; `update <mcu>` limits it.
|
||||
- `self-update`: installs a newer aldis release (`--check` only reports).
|
||||
|
||||
Notes for this printer (checked 2026-11-07):
|
||||
- All Klipper MCUs (`mcu` Leviathan, `Turtle_1`, `MC_1`, `EBB42`, `nhk`,
|
||||
`iHeater`) run `v0.13.0-777`, and Beacon 2.1.0; all report `mcu_kconfig`,
|
||||
which aldis needs (Klipper `v0.13.0-753` or newer).
|
||||
- Every board has Katapult (CAN or USB), which aldis supports.
|
||||
- Flashing the Leviathan (USB-CAN bridge) resets the CAN bus.
|
||||
- aldis writes each MCU's build config to `~/klipper/.config`. The named build
|
||||
configs used by the old script (`leviathan`, `EBB42`, ...) are not touched.
|
||||
- Not covered: the bd_pressure sensor (not a Klipper MCU; it has its own
|
||||
`stm32flash` procedure in the bd_pressure repo) and Katapult itself (see below).
|
||||
|
||||
# Old scripts
|
||||
|
||||
| Script | Does |
|
||||
|---|---|
|
||||
| `update_all_mcus.sh` | Pulls Klipper, builds and flashes **Klipper** to every MCU, prints a summary, restarts Klipper |
|
||||
| `update_katapult_all_mcus.sh` | Builds and flashes **Katapult** (the bootloader) to every MCU |
|
||||
| `archive/update_all_mcus.sh` | **Archived 2026-11-07, replaced by aldis.** Pulls Klipper, builds and flashes **Klipper** to every MCU, prints a summary, restarts Klipper |
|
||||
| `update_katapult_all_mcus.sh` | Builds and flashes **Katapult** (the bootloader) to every MCU. Still in use: aldis does not update bootloaders |
|
||||
|
||||
Based on the [Voron guide to automating MCU updates](https://docs.vorondesign.com/community/howto/drachenkatze/automating_klipper_mcu_updates.html)
|
||||
and [Esoterical's CANBus guide](https://canbus.esoterical.online/).
|
||||
@@ -11,7 +73,7 @@ and [Esoterical's CANBus guide](https://canbus.esoterical.online/).
|
||||
Run them on the Klipper host, between prints:
|
||||
|
||||
```bash
|
||||
~/klipper-macros/scripts/update_all_mcus.sh
|
||||
~/klipper-macros/scripts/update_katapult_all_mcus.sh
|
||||
```
|
||||
|
||||
They stop Klipper while flashing (and need `sudo` for that).
|
||||
@@ -90,5 +152,5 @@ not used by the flashing itself; they only document the UUIDs.
|
||||
|
||||
`update_katapult_all_mcus.sh` ends after the last board: it does not print
|
||||
the summary and does not start Klipper again. Run `sudo systemctl start
|
||||
klipper` afterwards, or add the last lines of `update_all_mcus.sh`
|
||||
klipper` afterwards, or add the last lines of `archive/update_all_mcus.sh`
|
||||
(`print_summary` and the restart) to it.
|
||||
@@ -1,4 +1,6 @@
|
||||
#!/bin/bash
|
||||
# ARCHIVED 2026-11-07: replaced by aldis (https://github.com/mjonuschat/aldis),
|
||||
# see scripts/README.md. Kept for reference; the IDs below are still this printer's.
|
||||
# https://docs.vorondesign.com/community/howto/drachenkatze/automating_klipper_mcu_updates.html
|
||||
# https://canbus.esoterical.online/mainboard_klipper_updating.html
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
# Axis twist calibration (`TWIST_CALIBRATE`)
|
||||
|
||||
Written 2026-11-03. Tested against a simulated printer and saved runs; the first
|
||||
real run on the printer is still to come, so stay near the emergency stop for
|
||||
that one.
|
||||
|
||||
## What it is for
|
||||
|
||||
Beacon sits 20 mm behind the nozzle. If the toolhead rolls slightly as it moves
|
||||
along the X rail, the nozzle and Beacon disagree about the bed height, by an
|
||||
amount that depends on where the toolhead is. Levelling and meshes inherit that
|
||||
error, so first layers come out thinner on one side. Klipper's
|
||||
`[axis_twist_compensation]` corrects it, and this tool measures the values.
|
||||
|
||||
Run it:
|
||||
|
||||
- after work on the X rail, X carriage, toolhead, belts or Beacon mount
|
||||
- when first layers differ between left and right
|
||||
|
||||
There is no need to run it on a schedule.
|
||||
|
||||
## Step by step
|
||||
|
||||
1. Run **`TWIST_CALIBRATE`** in Mainsail and choose **Measure** (25 min).
|
||||
2. Go through the checklist: nothing on the bed, nozzle clean, hands out of the
|
||||
printer. Nothing moves until you press **All checked, start**.
|
||||
3. You can close the window; the run continues. Progress is on the status line,
|
||||
and running `TWIST_CALIBRATE` again shows a progress bar and a Stop button.
|
||||
4. A window opens with the verdict. If it says **new values recommended**:
|
||||
1. Open `twist_data/twist_suggested.cfg` in Mainsail (Machine page, config
|
||||
files) and copy its contents.
|
||||
2. Make a backup copy of `printer.cfg`.
|
||||
3. In `printer.cfg`, replace the whole `[axis_twist_compensation]` block with
|
||||
the copied one. New values replace the old ones; do not add them together.
|
||||
If there is no block yet, paste it after `[beacon]`, outside the
|
||||
`SAVE_CONFIG` section at the bottom.
|
||||
4. Save and restart.
|
||||
5. Run `TWIST_CALIBRATE` again and choose **Verify** (17 min).
|
||||
|
||||
The calibration clears the active bed mesh (saved profiles stay).
|
||||
`PRINT_START` makes a new one by itself.
|
||||
|
||||
## What the run does
|
||||
|
||||
It heats the nozzle to 150 C, homes, runs QGL, wipes the nozzle on the Blobifier
|
||||
brush and sets Z by contact. It then visits each point twice, the second pass in reverse order to cancel slow drift.
|
||||
The nozzle touches the bed at every point. At the end it lifts to Z10 and turns
|
||||
the nozzle heater off. The bed heater is not touched.
|
||||
|
||||
- **Measure:** compares Beacon proximity with nozzle contact on rows y 55, 175
|
||||
and 295 (x 25-325) and on a line along Y at x=175. Compensation may be active:
|
||||
Beacon adds the same correction to both readings, so the difference is still
|
||||
the raw error.
|
||||
- **Verify:** compares compensated Beacon proximity with `BDP_TOUCH` on rows
|
||||
y 175 and 295. bd_pressure takes Z from the stepper and is not compensated,
|
||||
so it is an independent check.
|
||||
|
||||
## Reading the result
|
||||
|
||||
| Verdict | Meaning | What to do |
|
||||
|---|---|---|
|
||||
| Measure: new values recommended | The active values are off by 0.01 mm or more, or none are active | Apply them as above, then Verify |
|
||||
| Measure: no change needed | The active values are still right | Nothing |
|
||||
| Measure or Verify: run it again | The two passes disagree | Clean the nozzle and bed, run it again |
|
||||
| Measure: do not apply | The error is above 0.3 mm, or does not split into an X and a Y part | Check the X rail, belts, toolhead and Beacon mount |
|
||||
| Verify: compensation is good | The readings are flat along X | Nothing |
|
||||
| Verify: acceptable | Slightly less flat than ideal, but usable | Check a first layer |
|
||||
| Verify: compensation is off | Not flat along X | Run Measure and apply the new values; if it stays, check the mechanics |
|
||||
|
||||
The limits, all in mm:
|
||||
|
||||
| Check | Limit |
|
||||
|---|---|
|
||||
| Each X row against the mean of the rows | 0.015 |
|
||||
| Error left by the X+Y correction | 0.015 |
|
||||
| Same point in the two passes | no more than one point above 0.02, none above 0.04 |
|
||||
| Smaller change than this: leave the values | 0.01 |
|
||||
| Verify, range along one row | good up to 0.025, usable up to 0.035 |
|
||||
|
||||
They are set so the good runs of 2026-11-02 pass (constants at the top of
|
||||
`twist_check.py`).
|
||||
|
||||
## When it stops or refuses
|
||||
|
||||
Nothing in the configuration changes when this happens. Unless a print has
|
||||
started or Klipper is down, it lifts the nozzle and turns the heater off.
|
||||
|
||||
| Message | Likely cause | What to do |
|
||||
|---|---|---|
|
||||
| A print is running or paused | Refused at the start | Try again after the print |
|
||||
| Another twist run is active | A run is active, or one died without clearing its flag | `TWIST_STOP` stops it and clears the flag |
|
||||
| Klipper is not ready | Klipper is in an error state | `FIRMWARE_RESTART`, then start again |
|
||||
| Not found in Klipper: ... | The macros are not up to date or loaded | Update klipper-macros and restart Klipper |
|
||||
| Beacon sees the bed at ... | Something on the bed, or the plate not seated | Clear the bed and start again |
|
||||
| Nozzle and Beacon differ by ... | A blob on the nozzle, or a loose toolhead or Beacon | Clean the nozzle; if it stays, check the mounts |
|
||||
| ... gave no reading, ... failed | A probe or sensor command failed | Read the message; Verify also needs the bd_pressure load-check firmware |
|
||||
| A print started during the run | Stopped, and the printer is left alone | Start again after the print |
|
||||
|
||||
**`TWIST_STOP`** stops a run and shows **Stopped**. It waits for the command
|
||||
that is running, which can take about a minute during homing or QGL. In a real
|
||||
emergency use the emergency stop.
|
||||
|
||||
**Klipper shutdown:** travel moves run under the nozzle guard, so hitting
|
||||
something shuts Klipper down, and very occasionally the guard trips falsely. No
|
||||
window can open then. Clear the cause, run `FIRMWARE_RESTART`, look in
|
||||
`twist_run.log` for what happened, and start again.
|
||||
|
||||
Restarting the Klipper service, which a Moonraker update also does, ends a run
|
||||
that was started from Mainsail.
|
||||
|
||||
## Files
|
||||
|
||||
Everything is in `config/twist_data/` (on the Pi `~/printer_data/config/twist_data/`):
|
||||
|
||||
| File | Contents |
|
||||
|---|---|
|
||||
| `twist_<mode>_<date>.html` | Report with verdict and charts: download it from Mainsail and open it in a browser |
|
||||
| `twist_<mode>_<date>.jsonl` | The raw readings |
|
||||
| `twist_suggested.cfg` | The latest recommended block. Not loaded by anything until you paste it into `printer.cfg` |
|
||||
| `twist_run.log` | All messages of all runs. Look here when a run ended without a window |
|
||||
|
||||
## From a shell
|
||||
|
||||
Over SSH, use `tmux` so the run does not depend on the connection:
|
||||
|
||||
```bash
|
||||
python3 ~/klipper-macros/scripts/twist_check.py measure
|
||||
python3 ~/klipper-macros/scripts/twist_check.py verify
|
||||
python3 ~/klipper-macros/scripts/twist_check.py analyse ~/printer_data/config/twist_data/<file>.jsonl
|
||||
```
|
||||
|
||||
Ctrl-C stops a run the same way `TWIST_STOP` does. `analyse` prints the result of
|
||||
a saved run again and writes its report next to the file; it does not move the
|
||||
printer. From another computer, add `--host http://<printer>:7125` (Moonraker's
|
||||
own port, because nginx ends requests after 60 s). The data folder is then on
|
||||
that computer, under its own home directory.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Mainsail with `[respond]`, for the windows
|
||||
- `gcode_shell_command`, to start the script from a macro
|
||||
- Beacon, used in contact and proximity mode
|
||||
- The Blobifier macros (`BLOBIFIER_CLEAN`) and the nozzle guard (`_GUARD_ON`)
|
||||
- Python 3 on the Pi (standard library only), and Moonraker trusting localhost
|
||||
- For Verify: `[bdp_touch]` and the bd_pressure load-check firmware
|
||||
- `[axis_twist_compensation]` is not needed for the first Measure; the result
|
||||
tells you to add it
|
||||
@@ -0,0 +1,739 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Nozzle vs Beacon offset across the bed (axis twist compensation).
|
||||
|
||||
Beacon sits 20 mm behind the nozzle (y_offset 20). If the toolhead rolls as
|
||||
it moves (X rail twist), Beacon's proximity reading and the nozzle disagree
|
||||
by an amount that depends on X (and a little on Y). Beacon meshes and QGL
|
||||
inherit that error; Klipper's [axis_twist_compensation] corrects it.
|
||||
|
||||
Normally started from Mainsail with the macro TWIST_CALIBRATE, which explains
|
||||
each step (macros/calibration/twist_check.cfg). From a shell on the Pi:
|
||||
|
||||
python3 ~/klipper-macros/scripts/twist_check.py measure
|
||||
python3 ~/klipper-macros/scripts/twist_check.py verify
|
||||
python3 ~/klipper-macros/scripts/twist_check.py analyse <file.jsonl>
|
||||
|
||||
Modes:
|
||||
measure ~25 min. Proximity (nozzle at x, y-20, so Beacon sees bed x,y), then
|
||||
Beacon contact with the nozzle moved onto x,y. Rows y 55/175/295
|
||||
and a Y line at x=175. Works with or without compensation active:
|
||||
Beacon adds the same correction to proximity and contact, so
|
||||
contact - proximity is the raw error. New values replace the old
|
||||
ones. Result: apply, leave it, or re-run. It never changes
|
||||
printer.cfg; a ready block is saved in twist_suggested.cfg.
|
||||
verify ~17 min. Proximity (compensated), then BDP_TOUCH at x,y (bd_pressure,
|
||||
Z from the stepper, not compensated), then Beacon contact. Rows
|
||||
y 175/295. With good compensation, bdp - proximity is flat along X.
|
||||
|
||||
Both: BED_MESH_CLEAR (the active mesh only; saved profiles stay), nozzle 150C,
|
||||
HOME, QGL, G28 Z, nozzle wipe (BLOBIFIER_CLEAN), contact Z, 2 passes (second in reverse order to cancel slow drift),
|
||||
then Z10 and nozzle off. The bed heater is not touched.
|
||||
|
||||
Safety: refuses to start when Klipper is not ready, a print runs or another
|
||||
run is active. Travel moves run under the nozzle guard. Every reading is
|
||||
checked before the nozzle goes low, and anything unexpected stops the run. A
|
||||
stop (TWIST_STOP, Ctrl-C, an error) lifts the nozzle and switches its heater
|
||||
off, except when a print has started: then it leaves the printer alone.
|
||||
|
||||
Writes twist_<mode>_<date>.jsonl and .html (report with charts) in
|
||||
~/printer_data/config/twist_data/, plus twist_run.log with all messages.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import statistics as st
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
XS = [25, 75, 125, 175, 225, 275, 325]
|
||||
YS = [55, 95, 135, 175, 215, 255, 295]
|
||||
PASSES = 2
|
||||
TRIGGER = 2.0 # [beacon] trigger_distance: proximity result - 2 = bed
|
||||
BDP_ABOVE = 0.15 # BDP_TOUCH start height above the expected bed
|
||||
|
||||
# Result checks (mm)
|
||||
# Set so the good 2026-11-02 runs pass: rows 0.012, residual 0.012, one point
|
||||
# with pass spread 0.031 (the next 0.012, median 0.004), verify flat 0.022.
|
||||
ROWS_AGREE = 0.015 # each X row vs the mean: else X and Y are not separable
|
||||
RESIDUAL = 0.015 # worst error left by the X+Y model
|
||||
PASS_SPREAD = 0.02 # same point in the two passes: dirty nozzle or bed when
|
||||
PASS_OUTLIERS = 1 # more points than this are above it,
|
||||
PASS_WORST = 0.04 # or any point above this
|
||||
MIN_CHANGE = 0.01 # smaller differences to the active values: leave it
|
||||
MAX_COMP = 0.3 # larger: something is mechanically wrong, do not correct
|
||||
FLAT_GOOD = 0.025 # verify: bdp - proximity range along one row
|
||||
FLAT_MAX = 0.035
|
||||
|
||||
# Reading checks during the run (mm); outside these the run stops
|
||||
PROX_LIMIT = 0.5 # bed height from Beacon vs Z 0: something on the bed?
|
||||
CONTACT_LIMIT = 0.25 # nozzle contact vs Beacon: blob on the nozzle?
|
||||
BED_WARN = 40 # C: all reference runs were on a cold bed
|
||||
|
||||
DATA_DIR = os.path.expanduser("~/printer_data/config/twist_data")
|
||||
LOG = None
|
||||
|
||||
|
||||
class Problem(Exception):
|
||||
"""Something the user has to look at; the run stops."""
|
||||
|
||||
|
||||
class Stopped(Exception):
|
||||
"""TWIST_STOP or Ctrl-C."""
|
||||
|
||||
|
||||
def log(text):
|
||||
line = "%s %s" % (time.strftime("%H:%M:%S"), text)
|
||||
try:
|
||||
print(line, flush=True)
|
||||
except OSError:
|
||||
pass # SSH window closed: the run continues, the log file stays
|
||||
if LOG:
|
||||
LOG.write(line + "\n")
|
||||
LOG.flush()
|
||||
|
||||
|
||||
def clean(text):
|
||||
# Double quotes end a G-code parameter and ; starts a comment
|
||||
return str(text).replace('"', "'").replace(";", ",")
|
||||
|
||||
|
||||
class Printer:
|
||||
def __init__(self, host):
|
||||
self.host = host
|
||||
|
||||
def get(self, path, timeout=10):
|
||||
try:
|
||||
with urllib.request.urlopen(self.host + path,
|
||||
timeout=timeout) as r:
|
||||
return json.load(r)["result"]
|
||||
except (OSError, ValueError, KeyError) as e:
|
||||
raise Problem("No answer from Moonraker at %s (%s)"
|
||||
% (self.host, e))
|
||||
|
||||
def query(self, *objects):
|
||||
path = "/printer/objects/query?" + "&".join(
|
||||
urllib.parse.quote(o) for o in objects)
|
||||
return self.get(path)["status"]
|
||||
|
||||
def gcode(self, script, timeout=900):
|
||||
t0 = time.time()
|
||||
url = (self.host + "/printer/gcode/script?script="
|
||||
+ urllib.parse.quote(script))
|
||||
req = urllib.request.Request(url, method="POST")
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=timeout).read()
|
||||
except urllib.error.HTTPError as e:
|
||||
raise Problem(self.error_text(e, script))
|
||||
except OSError as e:
|
||||
raise Problem("Lost the connection during %s (%s)" % (script, e))
|
||||
store = self.get("/server/gcode_store?count=40")["gcode_store"]
|
||||
return [e["message"] for e in store
|
||||
if e["time"] >= t0 - 1 and e["type"] == "response"]
|
||||
|
||||
def error_text(self, e, script):
|
||||
try:
|
||||
text = json.load(e)["error"]["message"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
text = "HTTP %d" % e.code
|
||||
return "%s failed: %s" % (script.split()[0], text)
|
||||
|
||||
def say(self, text):
|
||||
log(text)
|
||||
self.gcode('RESPOND MSG="Twist: %s"' % clean(text), timeout=60)
|
||||
|
||||
def dialog(self, title, lines, buttons=()):
|
||||
# Mainsail shows this as a window (needs [respond])
|
||||
out = ["action:prompt_begin " + title]
|
||||
out += ["action:prompt_text " + line for line in lines]
|
||||
out += ["action:prompt_button %s|%s|%s" % b for b in buttons]
|
||||
out += ["action:prompt_footer_button Close|_TWIST_CLOSE|secondary",
|
||||
"action:prompt_show"]
|
||||
self.gcode("\n".join('RESPOND TYPE=command MSG="%s"' % clean(m)
|
||||
for m in out), timeout=60)
|
||||
|
||||
def state(self, running, mode=None, done=None, total=None):
|
||||
cmd = "SET_GCODE_VARIABLE MACRO=_TWIST_STATE VARIABLE=%s VALUE=%s"
|
||||
out = [cmd % ("running", running)]
|
||||
if mode is not None:
|
||||
out.append(cmd % ("mode", "\"'%s'\"" % mode))
|
||||
if done is not None:
|
||||
out.append(cmd % ("done", done))
|
||||
if total is not None:
|
||||
out.append(cmd % ("total", total))
|
||||
return "\n".join(out)
|
||||
|
||||
def logo(self, status):
|
||||
# The Stealthburner logo: visible from across the room
|
||||
objects = self.get("/printer/objects/list")["objects"]
|
||||
if status == "error":
|
||||
if "gcode_macro _STATUS_FLASH" in objects:
|
||||
return "_STATUS_FLASH STATE=error"
|
||||
elif "gcode_macro _STATUS" in objects:
|
||||
return "_STATUS STATE=" + status
|
||||
return ""
|
||||
|
||||
|
||||
def num(lines, pattern, what):
|
||||
for line in reversed(lines):
|
||||
m = re.search(pattern, line)
|
||||
if m:
|
||||
return float(m.group(1))
|
||||
raise Problem("%s gave no reading (expected %s in the answer)"
|
||||
% (what, pattern))
|
||||
|
||||
|
||||
def print_active(p):
|
||||
s = p.query("print_stats", "pause_resume", "virtual_sdcard")
|
||||
return (s["print_stats"]["state"] in ("printing", "paused")
|
||||
or s["pause_resume"]["is_paused"]
|
||||
or s["virtual_sdcard"]["is_active"])
|
||||
|
||||
|
||||
def check_ready(p):
|
||||
info = p.get("/printer/info")
|
||||
if info["state"] != "ready":
|
||||
raise Problem("Klipper is not ready (%s): %s"
|
||||
% (info["state"], info.get("state_message", "").strip()))
|
||||
|
||||
|
||||
def preflight(p, mode):
|
||||
check_ready(p)
|
||||
if print_active(p):
|
||||
raise Problem("A print is running or paused. Try again afterwards.")
|
||||
objects = p.get("/printer/objects/list")["objects"]
|
||||
settings = p.query("configfile")["configfile"]["settings"]
|
||||
missing = [m for m in ("HOME", "_NOZZLE_CONTACT_TEMP", "_TWIST_STATE",
|
||||
"_GUARD_ON", "BLOBIFIER_CLEAN")
|
||||
if "gcode_macro " + m not in objects]
|
||||
missing += [s for s in ["beacon"] + (["bdp_touch"] * (mode == "verify"))
|
||||
if s not in settings]
|
||||
if missing:
|
||||
raise Problem("Not found in Klipper: %s. Is klipper-macros up to "
|
||||
"date and Klipper restarted?" % ", ".join(missing))
|
||||
if p.query("gcode_macro _TWIST_STATE")[
|
||||
"gcode_macro _TWIST_STATE"]["running"]:
|
||||
raise Problem("Another twist run is active. TWIST_STOP stops it (and "
|
||||
"clears this flag if that run has died).")
|
||||
bed = p.query("heater_bed")["heater_bed"]["temperature"]
|
||||
if bed > BED_WARN:
|
||||
p.say("Note: bed at %d C. The reference runs were on a cold bed."
|
||||
% bed)
|
||||
|
||||
|
||||
def bar(done, total, width=20):
|
||||
n = width * done // total if total else 0
|
||||
return "[%s%s]" % ("=" * n, "." * (width - n))
|
||||
|
||||
|
||||
def eta(start, done, total):
|
||||
if not done:
|
||||
return ""
|
||||
left = (time.time() - start) / done * (total - done)
|
||||
return ", ~%d min left" % (left // 60 + 1)
|
||||
|
||||
|
||||
def travel(p, x, y):
|
||||
# Nothing may touch the nozzle here: an object on the bed stops Klipper
|
||||
p.gcode("_GUARD_ON PHASE=twist_travel\nG1 X%d Y%d Z5 F9000\n_GUARD_OFF"
|
||||
% (x, y))
|
||||
|
||||
|
||||
def measure_point(p, mode, x, y):
|
||||
r = {"x": x, "y": y, "t": time.time()}
|
||||
travel(p, x, y - 20)
|
||||
r["prox"] = num(p.gcode("PROBE PROBE_METHOD=proximity"),
|
||||
r"z=(-?[\d.]+)", "Beacon proximity")
|
||||
bed = r["prox"] - TRIGGER
|
||||
if abs(bed) > PROX_LIMIT:
|
||||
raise Problem("Beacon sees the bed at %+.3f mm at x=%d y=%d (limit "
|
||||
"%.1f). Is something on the bed, or the plate not "
|
||||
"seated?" % (bed, x, y, PROX_LIMIT))
|
||||
p.gcode("G1 Z5 F600")
|
||||
travel(p, x, y)
|
||||
if mode == "verify":
|
||||
p.gcode("G1 Z%.3f F300" % (bed + BDP_ABOVE))
|
||||
r["bdp"] = num(p.gcode("BDP_TOUCH FLOOR=0.7"), r"fit z (-?[\d.]+)",
|
||||
"BDP_TOUCH")
|
||||
p.gcode("G1 Z5 F600")
|
||||
r["contact"] = num(p.gcode("PROBE PROBE_METHOD=contact SAMPLES=1"),
|
||||
r"z=(-?[\d.]+)", "Beacon contact")
|
||||
p.gcode("G1 Z5 F600")
|
||||
if abs(r["contact"] - bed) > CONTACT_LIMIT:
|
||||
raise Problem("Nozzle and Beacon differ by %.3f mm at x=%d y=%d (limit"
|
||||
" %.2f). Clean the nozzle; if it stays, check the "
|
||||
"toolhead and Beacon mount."
|
||||
% (abs(r["contact"] - bed), x, y, CONTACT_LIMIT))
|
||||
return r
|
||||
|
||||
|
||||
def run_points(p, mode, path):
|
||||
if mode == "measure":
|
||||
pts = [(x, y) for y in (55, 175, 295) for x in XS]
|
||||
pts += [(175, y) for y in YS if y not in (55, 175, 295)]
|
||||
else:
|
||||
pts = [(x, y) for y in (175, 295) for x in XS]
|
||||
total = len(pts) * PASSES
|
||||
p.gcode(p.state(1, mode, 0, total))
|
||||
p.gcode("M117 Twist %s: heating, homing, QGL" % mode)
|
||||
p.say("%s started: heating the nozzle to 150C, homing, levelling" % mode)
|
||||
p.gcode("BED_MESH_CLEAR")
|
||||
p.gcode("_NOZZLE_CONTACT_TEMP WAIT=1")
|
||||
p.gcode("HOME")
|
||||
p.gcode("QUAD_GANTRY_LEVEL")
|
||||
# As in PRINT_START. Plastic left on the nozzle sets the contact Z too high
|
||||
# and squeezes away during the run: the touches then sink by ~0.004 mm per
|
||||
# point (2026-11-04). QGL moved Z, so home again before the brush takes the
|
||||
# nozzle below Z0. The bristles press on the nozzle: guard in log mode.
|
||||
p.gcode("M117 Twist %s: cleaning the nozzle" % mode)
|
||||
p.gcode("G28 Z")
|
||||
p.gcode("_GUARD_ON PHASE=brush MODE=log\nBLOBIFIER_CLEAN\n_GUARD_OFF")
|
||||
p.gcode("G28 Z METHOD=CONTACT CALIBRATE=1")
|
||||
p.gcode("G90")
|
||||
p.say("%d points, %d passes. The nozzle will touch the bed at each one."
|
||||
% (len(pts), PASSES))
|
||||
done = 0
|
||||
start = time.time()
|
||||
with open(path, "w") as out:
|
||||
for rep in range(PASSES):
|
||||
for (x, y) in (pts if rep == 0 else pts[::-1]):
|
||||
check_ready(p)
|
||||
if print_active(p):
|
||||
raise Problem("A print started during the run.")
|
||||
r = measure_point(p, mode, x, y)
|
||||
r["rep"] = rep
|
||||
out.write(json.dumps(r) + "\n")
|
||||
out.flush()
|
||||
done += 1
|
||||
text = "%s %d%% %s%s" % (mode, 100 * done // total,
|
||||
bar(done, total, 10),
|
||||
eta(start, done, total))
|
||||
p.gcode(p.state(1, done=done) + "\nM117 Twist " + clean(text))
|
||||
log("%d/%d %s" % (done, total, r))
|
||||
if done % 10 == 0:
|
||||
p.say(text)
|
||||
|
||||
|
||||
def load(path):
|
||||
groups = {}
|
||||
with open(path) as f:
|
||||
for line in f:
|
||||
r = json.loads(line)
|
||||
groups.setdefault((r["x"], r["y"]), []).append(r)
|
||||
return groups
|
||||
|
||||
|
||||
def mean(groups, key, fn):
|
||||
out = {}
|
||||
for k, rs in groups.items():
|
||||
v = [fn(r) for r in rs if r.get(key) is not None
|
||||
and r.get("prox") is not None]
|
||||
if v:
|
||||
out[k] = (st.mean(v), max(v) - min(v))
|
||||
return out
|
||||
|
||||
|
||||
def noisy_passes(spreads):
|
||||
return (max(spreads) > PASS_WORST
|
||||
or sum(v > PASS_SPREAD for v in spreads) > PASS_OUTLIERS)
|
||||
|
||||
|
||||
def analyse_verify(groups):
|
||||
rows = sorted({y for x, y in groups}, reverse=True)
|
||||
prox = mean(groups, "bdp", lambda r: r["bdp"] - (r["prox"] - TRIGGER))
|
||||
cont = mean(groups, "bdp", lambda r: r["bdp"] - r["contact"])
|
||||
spreads = [v[1] for v in prox.values()] + [v[1] for v in cont.values()]
|
||||
spread = max(spreads)
|
||||
flat = {y: max(prox[(x, y)][0] for x in XS)
|
||||
- min(prox[(x, y)][0] for x in XS) for y in rows}
|
||||
worst = max(flat.values())
|
||||
res = {"mode": "verify", "rows": rows,
|
||||
"series": {y: [prox[(x, y)][0] for x in XS] for y in rows},
|
||||
"contact": {y: [cont[(x, y)][0] for x in XS] for y in rows},
|
||||
"block": None}
|
||||
facts = ["Flat along X: worst row varies %.3f mm (good: up to %.3f)."
|
||||
% (worst, FLAT_GOOD),
|
||||
"Same point between passes: up to %.3f mm." % spread]
|
||||
if noisy_passes(spreads):
|
||||
res.update(level="bad", title="Verify: run it again", lines=facts + [
|
||||
"The two passes disagree: clean the nozzle and bed, then run "
|
||||
"Verify again."], retry="verify")
|
||||
elif worst <= FLAT_GOOD:
|
||||
res.update(level="good", title="Verify: compensation is good",
|
||||
lines=facts + ["Nothing to do. PRINT_START makes a new "
|
||||
"mesh by itself."])
|
||||
elif worst <= FLAT_MAX:
|
||||
res.update(level="warn", title="Verify: acceptable", lines=facts + [
|
||||
"Slightly more than ideal but usable. Check a first layer."])
|
||||
else:
|
||||
res.update(level="bad", title="Verify: compensation is off",
|
||||
lines=facts + ["Run Measure again and apply the new "
|
||||
"values. If it stays, check the X rail, "
|
||||
"belts and Beacon mount."], retry="measure")
|
||||
return res
|
||||
|
||||
|
||||
def analyse_measure(groups, current):
|
||||
full = mean(groups, "contact",
|
||||
lambda r: r["contact"] - (r["prox"] - TRIGGER))
|
||||
d = {k: v[0] for k, v in full.items()}
|
||||
spreads = [v[1] for v in full.values()]
|
||||
spread = max(spreads)
|
||||
xrows = [y for y in (55, 175, 295) if all((x, y) in d for x in XS)]
|
||||
if not xrows or not all((175, y) in d for y in YS):
|
||||
raise Problem("Not all points were measured; nothing to conclude.")
|
||||
rel = {y: [d[(x, y)] - d[(175, y)] for x in XS] for y in xrows}
|
||||
xprof = [st.mean(rel[y][i] for y in xrows) for i in range(len(XS))]
|
||||
yprof = [d[(175, y)] - d[(175, 175)] for y in YS]
|
||||
agree = max(abs(rel[y][i] - xprof[i]) for y in xrows
|
||||
for i in range(len(XS)))
|
||||
worst = 0.
|
||||
for y in xrows:
|
||||
for i, x in enumerate(XS):
|
||||
left = d[(x, y)] - d[(175, 175)] - xprof[i] - yprof[YS.index(y)]
|
||||
worst = max(worst, abs(left))
|
||||
biggest = max(abs(v) for v in xprof + yprof)
|
||||
change = None
|
||||
if current and (current.get("z_compensations") or [])[:1] != []:
|
||||
old_x = current.get("z_compensations") or []
|
||||
old_y = current.get("zy_compensations") or []
|
||||
if len(old_x) == len(XS) and len(old_y) == len(YS):
|
||||
change = max(abs(a - b) for a, b in zip(xprof + yprof,
|
||||
old_x + old_y))
|
||||
fmt = lambda vals: ", ".join("%.4f" % (v + 0.) for v in vals)
|
||||
block = """[axis_twist_compensation]
|
||||
# Measured %s with scripts/twist_check.py measure:
|
||||
# nozzle contact vs Beacon proximity, 0 at 175,175
|
||||
calibrate_start_x: %d
|
||||
calibrate_end_x: %d
|
||||
calibrate_y: 175
|
||||
z_compensations: %s
|
||||
compensation_start_x: %d
|
||||
compensation_end_x: %d
|
||||
calibrate_start_y: %d
|
||||
calibrate_end_y: %d
|
||||
calibrate_x: 175
|
||||
zy_compensations: %s
|
||||
compensation_start_y: %d
|
||||
compensation_end_y: %d
|
||||
""" % (datetime.date.today().isoformat(), XS[0], XS[-1], fmt(xprof), XS[0],
|
||||
XS[-1], YS[0], YS[-1], fmt(yprof), YS[0], YS[-1])
|
||||
res = {"mode": "measure", "xprof": xprof, "yprof": yprof, "rel": rel,
|
||||
"block": None, "suggested": block}
|
||||
facts = [
|
||||
"Largest error: %.3f mm. The rows agree within %.3f (limit %.3f)."
|
||||
% (biggest, agree, ROWS_AGREE),
|
||||
"Left after correction: %.3f (limit %.3f). Passes: up to %.3f."
|
||||
% (worst, RESIDUAL, spread)]
|
||||
if noisy_passes(spreads):
|
||||
res.update(level="bad", title="Measure: run it again", lines=facts + [
|
||||
"The two passes disagree: clean the nozzle and bed, then run "
|
||||
"Measure again. Nothing changed."], retry="measure")
|
||||
elif biggest > MAX_COMP:
|
||||
res.update(level="bad", title="Measure: do not apply", lines=facts + [
|
||||
"This error is too large to correct safely. Check the X rail, "
|
||||
"belts, toolhead and Beacon mount. Nothing changed."])
|
||||
elif agree > ROWS_AGREE or worst > RESIDUAL:
|
||||
res.update(level="bad", title="Measure: do not apply", lines=facts + [
|
||||
"The error does not split into an X and a Y part, so this "
|
||||
"compensation cannot correct it. Check the mechanics first. "
|
||||
"Nothing changed."])
|
||||
elif change is not None and change < MIN_CHANGE:
|
||||
res.update(level="good", title="Measure: no change needed",
|
||||
lines=facts + ["The active values are still right (largest"
|
||||
" difference %.3f mm). Nothing to do."
|
||||
% change])
|
||||
else:
|
||||
how = ("Largest difference to the active values: %.3f mm." % change
|
||||
if change is not None else "No compensation is active yet.")
|
||||
res.update(level="warn", title="Measure: new values recommended",
|
||||
block=block, lines=facts + [
|
||||
how,
|
||||
"1. Open twist_data/twist_suggested.cfg in Mainsail "
|
||||
"(Machine, config files) and copy it.",
|
||||
"2. In printer.cfg replace the [axis_twist_compensation"
|
||||
"] block with it (a backup copy of printer.cfg first).",
|
||||
"3. Save and Restart, then run Verify here."])
|
||||
return res
|
||||
|
||||
|
||||
def analyse(path, current=None):
|
||||
groups = load(path)
|
||||
if any("bdp" in r for rs in groups.values() for r in rs):
|
||||
res = analyse_verify(groups)
|
||||
else:
|
||||
res = analyse_measure(groups, current)
|
||||
res["file"] = os.path.basename(path)
|
||||
return res
|
||||
|
||||
|
||||
def report_console(res):
|
||||
print()
|
||||
if res["mode"] == "verify":
|
||||
print("bdp fit - proximity (flat = compensation good):")
|
||||
for y in res["rows"]:
|
||||
print("y=%3d " % y + " ".join("%+.3f" % v
|
||||
for v in res["series"][y]))
|
||||
print("bdp fit - Beacon contact (shows Beacon's contact correction):")
|
||||
for y in res["rows"]:
|
||||
print("y=%3d " % y + " ".join("%+.3f" % v
|
||||
for v in res["contact"][y]))
|
||||
else:
|
||||
print("contact - proximity, each row minus its own x=175:")
|
||||
for y, vals in res["rel"].items():
|
||||
print("y=%3d " % y + " ".join("%+.3f" % v for v in vals))
|
||||
print("X profile:", " ".join("%+.4f" % v for v in res["xprof"]))
|
||||
print("Y profile:", " ".join("%+.4f" % v for v in res["yprof"]))
|
||||
print("\n" + res["title"].upper())
|
||||
for line in res["lines"]:
|
||||
print(" " + line)
|
||||
if res["block"]:
|
||||
print("\n" + res["block"])
|
||||
|
||||
|
||||
COLORS = ["#2a78c6", "#d95f02", "#1b9e77", "#7570b3"]
|
||||
|
||||
|
||||
def chart(title, xs, series, xlabel):
|
||||
# series: list of (name, values); a plain SVG line chart in mm
|
||||
w, h, ml, mr, mt, mb = 640, 300, 62, 16, 54, 44
|
||||
vals = [v for _, vs in series for v in vs]
|
||||
lo, hi = min(vals + [-0.02]), max(vals + [0.02])
|
||||
pad = (hi - lo) * 0.1
|
||||
lo, hi = lo - pad, hi + pad
|
||||
px = lambda x: ml + (x - xs[0]) * (w - ml - mr) / (xs[-1] - xs[0])
|
||||
py = lambda v: mt + (hi - v) * (h - mt - mb) / (hi - lo)
|
||||
out = ['<svg viewBox="0 0 %d %d" role="img" aria-label="%s">'
|
||||
% (w, h, html.escape(title)),
|
||||
'<text x="%d" y="20" class="t">%s</text>' % (ml, html.escape(title))]
|
||||
step = 0.01 if hi - lo < 0.08 else (0.02 if hi - lo < 0.16 else 0.05)
|
||||
v = int(lo / step) * step
|
||||
while v <= hi:
|
||||
if v >= lo:
|
||||
out.append('<line x1="%d" x2="%d" y1="%.1f" y2="%.1f" class="%s"/>'
|
||||
% (ml, w - mr, py(v), py(v),
|
||||
"z" if abs(v) < step / 2 else "g"))
|
||||
out.append('<text x="%d" y="%.1f" class="l" text-anchor="end">'
|
||||
'%+.2f</text>' % (ml - 6, py(v) + 4, v + 0.))
|
||||
v += step
|
||||
for x in xs:
|
||||
out.append('<text x="%.1f" y="%d" class="l" text-anchor="middle">%d'
|
||||
'</text>' % (px(x), h - mb + 16, x))
|
||||
out.append('<text x="%d" y="%d" class="l" text-anchor="middle">%s (mm)'
|
||||
'</text>' % ((ml + w - mr) // 2, h - 8, xlabel))
|
||||
for i, (name, vs) in enumerate(series):
|
||||
c = COLORS[i % len(COLORS)]
|
||||
pts = " ".join("%.1f,%.1f" % (px(x), py(v)) for x, v in zip(xs, vs))
|
||||
out.append('<polyline points="%s" fill="none" stroke="%s" '
|
||||
'stroke-width="2"/>' % (pts, c))
|
||||
out += ['<circle cx="%.1f" cy="%.1f" r="3" fill="%s"><title>%s, %d: '
|
||||
'%+.3f mm</title></circle>'
|
||||
% (px(x), py(v), c, html.escape(name), x, v)
|
||||
for x, v in zip(xs, vs)]
|
||||
out.append('<text x="%d" y="%d" class="l" fill="%s" style="fill:%s">'
|
||||
'%s</text>' % (ml + i * 70, 40, c, c, html.escape(name)))
|
||||
out.append("</svg>")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def report_html(res, path):
|
||||
if res["mode"] == "verify":
|
||||
charts = [
|
||||
chart("bdp fit - proximity: should be a flat line", XS,
|
||||
[("y=%d" % y, res["series"][y]) for y in res["rows"]], "X"),
|
||||
chart("bdp fit - Beacon contact: minus the correction", XS,
|
||||
[("y=%d" % y, res["contact"][y]) for y in res["rows"]], "X")]
|
||||
else:
|
||||
charts = [
|
||||
chart("Error along X, per row: lines should overlap", XS,
|
||||
[("y=%d" % y, v) for y, v in res["rel"].items()]
|
||||
+ [("mean", res["xprof"])], "X"),
|
||||
chart("Error along Y at x=175", YS, [("Y", res["yprof"])], "Y")]
|
||||
block = res["block"] or res.get("suggested") or ""
|
||||
page = """<!doctype html>
|
||||
<html><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Twist %s</title>
|
||||
<style>
|
||||
:root{--bg:#fff;--fg:#1c2024;--dim:#5f6b76;--grid:#e3e6e8;--box:#f4f5f6}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#16191c;--fg:#e6e8ea;
|
||||
--dim:#98a2ab;--grid:#2c3136;--box:#212529}}
|
||||
body{margin:0 auto;max-width:720px;padding:16px;background:var(--bg);
|
||||
color:var(--fg);font:16px/1.5 system-ui,sans-serif}
|
||||
.v{padding:12px 16px;border-radius:8px;border-left:6px solid;
|
||||
background:var(--box);margin:12px 0}
|
||||
.good{border-color:#1b9e77}.warn{border-color:#e6a100}.bad{border-color:#d62728}
|
||||
h1{font-size:1.3em;margin:0 0 6px}p{margin:4px 0}svg{width:100%%;margin:12px 0}
|
||||
.t{font-size:14px;font-weight:600;fill:var(--fg)}
|
||||
.l{font-size:12px;fill:var(--dim)}.g{stroke:var(--grid)}.z{stroke:var(--dim)}
|
||||
pre{background:var(--box);padding:12px;overflow-x:auto;font-size:13px}
|
||||
small{color:var(--dim)}
|
||||
</style></head><body>
|
||||
<div class="v %s"><h1>%s</h1>%s</div>
|
||||
%s
|
||||
%s
|
||||
<small>%s, written %s</small>
|
||||
</body></html>
|
||||
""" % (res["mode"], res["level"], html.escape(res["title"]),
|
||||
"".join("<p>%s</p>" % html.escape(s) for s in res["lines"]),
|
||||
"\n".join(charts),
|
||||
("<pre>%s</pre>" % html.escape(block)) if block else "",
|
||||
html.escape(res["file"]),
|
||||
datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(page)
|
||||
|
||||
|
||||
def cleanup(p):
|
||||
# Never fight a print that has started, and do not raise from here
|
||||
try:
|
||||
check_ready(p)
|
||||
if print_active(p):
|
||||
log("A print is active: leaving the printer alone.")
|
||||
return True
|
||||
homed = p.query("toolhead")["toolhead"]["homed_axes"]
|
||||
p.gcode("_GUARD_OFF", timeout=120)
|
||||
if "z" in homed:
|
||||
p.gcode("G90\nG1 Z10 F600", timeout=120)
|
||||
p.gcode("M104 S0", timeout=120)
|
||||
return True
|
||||
except Exception as e:
|
||||
log("Could not finish cleanly: %s" % e)
|
||||
log("Check the printer: the nozzle heater may still be on until "
|
||||
"Klipper restarts.")
|
||||
return False
|
||||
|
||||
|
||||
def on_signal(signum, frame):
|
||||
raise Stopped()
|
||||
|
||||
|
||||
def run(mode, host):
|
||||
global LOG
|
||||
os.makedirs(DATA_DIR, exist_ok=True)
|
||||
LOG = open(os.path.join(DATA_DIR, "twist_run.log"), "a")
|
||||
p = Printer(host)
|
||||
stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M")
|
||||
path = os.path.join(DATA_DIR, "twist_%s_%s.jsonl" % (mode, stamp))
|
||||
report = path[:-len(".jsonl")] + ".html"
|
||||
log("=== %s, writing %s" % (mode, path))
|
||||
failure = None
|
||||
res = None
|
||||
started = False
|
||||
signal.signal(signal.SIGTERM, on_signal)
|
||||
signal.signal(signal.SIGINT, on_signal)
|
||||
if hasattr(signal, "SIGHUP"):
|
||||
# A closed SSH window must not end the run halfway
|
||||
signal.signal(signal.SIGHUP, signal.SIG_IGN)
|
||||
try:
|
||||
preflight(p, mode)
|
||||
started = True
|
||||
p.gcode(p.logo("calibrating_z") or "M400")
|
||||
run_points(p, mode, path)
|
||||
res = analyse(path, p.query("configfile")["configfile"]["settings"]
|
||||
.get("axis_twist_compensation"))
|
||||
except Stopped:
|
||||
failure = ("Stopped", ["Stopped on request. The result is not used "
|
||||
"and nothing changed."])
|
||||
except Problem as e:
|
||||
failure = ("Twist %s stopped" % mode, [
|
||||
str(e), "Nothing changed in the configuration. "
|
||||
"Fix this, then start again with TWIST_CALIBRATE."])
|
||||
except Exception as e:
|
||||
# Whatever went wrong, the nozzle must still be lifted and switched off
|
||||
failure = ("Twist %s stopped" % mode, [
|
||||
"Unexpected error: %r" % e, "Nothing changed in the configuration."
|
||||
" See twist_data/twist_run.log."])
|
||||
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
if started:
|
||||
cleanup(p)
|
||||
if res:
|
||||
try:
|
||||
if res["block"]:
|
||||
with open(os.path.join(DATA_DIR, "twist_suggested.cfg"),
|
||||
"w") as f:
|
||||
f.write(res["block"])
|
||||
report_html(res, report)
|
||||
report_console(res)
|
||||
except Exception as e:
|
||||
log("Could not write the report: %r" % e)
|
||||
log(res["title"])
|
||||
return finish(p, res, failure, os.path.basename(report), started)
|
||||
|
||||
|
||||
def finish(p, res, failure, report_name, started):
|
||||
# Klipper may be down here; the log and the shell keep the message
|
||||
try:
|
||||
if res:
|
||||
buttons = []
|
||||
if res.get("retry"):
|
||||
buttons.append(("Run %s again" % res["retry"],
|
||||
"_TWIST_CHECKLIST MODE=%s" % res["retry"],
|
||||
"primary"))
|
||||
elif res["level"] == "warn" and res["mode"] == "measure":
|
||||
buttons.append(("Run Verify (after restart)",
|
||||
"_TWIST_CHECKLIST MODE=verify", "primary"))
|
||||
p.gcode(p.state(0))
|
||||
logo = p.logo("error" if res["level"] == "bad" else "ready")
|
||||
p.gcode(logo or "M400")
|
||||
p.gcode("M117 %s" % clean(res["title"]))
|
||||
for line in res["lines"]:
|
||||
p.say(line)
|
||||
p.dialog(res["title"], res["lines"] + [
|
||||
"Report with charts: twist_data/" + report_name], buttons)
|
||||
else:
|
||||
title, lines = failure
|
||||
# Refused at the start: an active run or print keeps its flag,
|
||||
# status line and logo
|
||||
if started:
|
||||
p.gcode(p.state(0))
|
||||
logo = p.logo("error" if title != "Stopped" else "ready")
|
||||
p.gcode(logo or "M400")
|
||||
p.gcode("M117 %s" % clean(title))
|
||||
p.dialog(title, lines)
|
||||
except Exception as e:
|
||||
log("Could not show the result in Mainsail: %s" % e)
|
||||
if failure:
|
||||
log(failure[0] + ": " + " ".join(failure[1]))
|
||||
return 1
|
||||
return 0 if res["level"] != "bad" else 2
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Measure and verify axis twist compensation (nozzle vs "
|
||||
"Beacon). Normally started with the macro TWIST_CALIBRATE.")
|
||||
ap.add_argument("mode", choices=("measure", "verify", "analyse"))
|
||||
ap.add_argument("file", nargs="?", help="analyse: a saved .jsonl")
|
||||
ap.add_argument("--host", default="http://localhost:7125",
|
||||
help="Moonraker (its own port: nginx ends requests after "
|
||||
"60 s)")
|
||||
a = ap.parse_args()
|
||||
if a.mode != "analyse":
|
||||
return run(a.mode, a.host.rstrip("/"))
|
||||
if not a.file:
|
||||
ap.error("analyse needs a file")
|
||||
current = None
|
||||
try:
|
||||
current = Printer(a.host.rstrip("/")).query("configfile")[
|
||||
"configfile"]["settings"].get("axis_twist_compensation")
|
||||
except Problem:
|
||||
print("Printer not reachable: not comparing with the active values")
|
||||
res = analyse(a.file, current)
|
||||
report_console(res)
|
||||
report = os.path.splitext(a.file)[0] + ".html"
|
||||
report_html(res, report)
|
||||
print("\nReport:", report)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user