{% set runout_was = 1 if bdw and printer.bdwidth_status.enabled else 0 %}
{% if runout_was %}
RESPOND MSG="PURGE_UNTIL_EMPTY: bdwidth runout response off during the purges"
SET_FILAMENT_SENSOR SENSOR={bdw} ENABLE=0
{% endif %}
M109 S{params.TEMP}
{% for i in range(params.MAX|int) %}
_PURGE_UNTIL_EMPTY_STEP LENGTH={params.LENGTH}
{% endfor %}
_PURGE_UNTIL_EMPTY_RESULT MAX={params.MAX} BDW={bdw if runout_was else '-'}
# Rendered when it runs, so it sees the result of the previous purge.
[gcode_macro _PURGE_UNTIL_EMPTY_STEP]
gcode:
{% if not printer["gcode_macro PURGE_UNTIL_EMPTY"].done %}
{% set length=params.LENGTH|default(0)|float %}
M400
G4 P500
BDP_CHECK_START
BLOBIFIER {'PURGE_LENGTH=%.1f' % length if length > 0 else ''}
M400
BDP_CHECK_STOP
_PURGE_UNTIL_EMPTY_EVAL
{% endif %}
[gcode_macro _PURGE_UNTIL_EMPTY_EVAL]
gcode:
{% set cfg=printer["gcode_macro PURGE_UNTIL_EMPTY"] %}
{% set p = printer.bdpressure_check %}
{% set n = cfg.count + 1 %}
{% if not p.available %}
{action_raise_error("PURGE_UNTIL_EMPTY: lost the bd_pressure load-check reading, stopped. bdwidth runout response may still be off: SET_FILAMENT_SENSOR SENSOR=<bdwidth name> ENABLE=1")}
{% set cfg=printer["gcode_macro PURGE_UNTIL_EMPTY"] %}
{% if params.BDW|default('-') != '-' %}
SET_FILAMENT_SENSOR SENSOR={params.BDW} ENABLE=1
{% endif %}
{% if cfg.done %}
RESPOND MSG="PURGE_UNTIL_EMPTY: no more filament after {cfg.count} purge{'s' if cfg.count != 1 else ''}. The last bit between the extruder gears and the nozzle is pushed out by the next load."
{% else %}
RESPOND TYPE=error MSG="PURGE_UNTIL_EMPTY: still pressure after {params.MAX} purges. The lane may still be feeding, or the nozzle is blocked - check before running it again."