Get the correct last_position in GCODE Script

I want to use a custom GCODE Script to Auto-z-calibration on a dual x-carriage setup.
I wrote the following code:

G1 F40000 Z5
G30 X200 Y200
{% set z0 = last_position.z %}
M117 z0 {{z0}}
G1 F40000 Z5
G1 F40000 X-50
G30 X200 Y200
{% set z1 = last_position.z %}
M117 z1 {{z1}}
G1 F40000 Z5
G1 F40000 X500
G1 F40000 X-50 Y400
{% set delta = z0-z1 %}
M117 "Delta: {{delta}}"
M218 T1 Z{{delta}}

The idea was to make a single Z-Probe on each Extruder (Toolhead) and then calculate The Z-Offset of both Nozzles. I need to say, that I have preasure sensitive print bed.
I used a M114 to get the position an then I wanted to read it from last_position.
How ever I tried it, The value comming from last_position is something completly different and does not change during both readings. As a test I used 2 different X-positions and read last_position.x) The result was that I got with M117 the last X-position of G29.

What am I doing wrong? Where is the mistake. I'm thankfull for every hint.


The second call to M114 appears to be commented-out, btw.

It seems that the last_position.z value is gotten from the last M114 command that was given before the script was executed. And not the M114 inside of the script.

I have this problem as well in my scripts.
@foosel : is this something you can change?

It'll be from the last response to M114 that was parsed. Sending a command to OctoPrint does not mean that its result will be immediately available, and due to how buffers are implemented firmware side and differences in firmware interpretations of the protocol there's also no way for OctoPrint to wait for responses for specific commands or somethings like that.

Calculating a delta is way outside of what you can do with a GCODE script. You could do it with a plugin that listens to the PositionUpdated event.

Could you...?

Pause script:

G4 P2 # Wait for two seconds (Marlin, etc)
# Do stuff

Resume script:

# Do stuff
{% set zlast = last_position.z %}
G0 Z{{zlast}}

You could but that is dirty AF and not guaranteed to work depending on what's going on in the firmware buffers.

It seems that any M114 command in a script, can and will not be used in that script. So you can G4 S30000 and still not get the reaction you wanted.
Also there is a new G60 command in marlin, which will store positions in the firmware.
We also asked to report the info of the stored positions to the host: