########################################
# Save Z-Offset
########################################

[save_variables]
filename: /usr/data/printer_data/config/Helper-Script/variables.cfg

[respond]


[gcode_macro SET_GCODE_OFFSET]
description: Saving Z-Offset
rename_existing: _SET_GCODE_OFFSET
gcode:
  {% if printer.save_variables.variables.zoffset %}
  {% set zoffset = printer.save_variables.variables.zoffset %}
  {% else %}
  {% set zoffset = {'z': None} %}
  {% endif %}
  {% set ns = namespace(zoffset={'z': zoffset.z}) %}
  _SET_GCODE_OFFSET {% for p in params %}{'%s=%s '% (p, params[p])}{% endfor %}
  {%if 'Z' in params %}{% set null = ns.zoffset.update({'z': params.Z}) %}{% endif %}
  {%if 'Z_ADJUST' in params %}
  {%if ns.zoffset.z == None %}{% set null = ns.zoffset.update({'z': 0}) %}{% endif %}
  {% set null = ns.zoffset.update({'z': (ns.zoffset.z | float) + (params.Z_ADJUST | float)}) %}
  {% endif %}
  SAVE_VARIABLE VARIABLE=zoffset VALUE="{ns.zoffset}"


[delayed_gcode LOAD_GCODE_OFFSETS]
initial_duration: 2
gcode:
  {% if printer.save_variables.variables.zoffset %}
  {% set zoffset = printer.save_variables.variables.zoffset %}
  _SET_GCODE_OFFSET {% for axis, offset in zoffset.items() if zoffset[axis] %}{ "%s=%s " % (axis, offset) }{% endfor %}
  RESPOND TYPE=command MSG="Loaded Z-Offset from variables.cfg: {zoffset.z}mm"
  {% endif %}
  