#  __  __                          
# |  \/  |                         
# | \  / | __ _  ___ _ __ ___  ___ 
# | |\/| |/ _` |/ __| '__/ _ \/ __|
# | |  | | (_| | (__| | | (_) \__ \
# |_|  |_|\__,_|\___|_|  \___/|___/
#
# Macros Configurations - Flsun V400
# Version 3.0
#
# Guislain Cyril


##################################################
# Start and End G-Codes
##################################################

[gcode_macro START_PRINT]
description: Start G-Code
gcode:
  {% set BED_TEMP = params.BED_TEMP|default(60)|float %}
  {% set EXTRUDER_TEMP = params.EXTRUDER_TEMP|default(210)|float %}
  LED_HOTEND_ON
  G21
  G90
  M82
  {% if printer.extruder.target != 0 %}
  M104 S{EXTRUDER_TEMP}
  {% else %}
  M104 S150
  {% endif %}
  M140 S{BED_TEMP}
  {% if printer.toolhead.homed_axes != "xyz" %}
  G28
  {% endif %}
  G1 Z370 F3000
  G1 X-150 F3000
  M190 S{BED_TEMP}
  M109 S{EXTRUDER_TEMP}
  G1 Z1 F3000
  G1 X-150 Y0 Z0.4
  G92 E0
  G3 X0 Y-130 I150 J1 Z0.3 E30 F2000
  G92 E0
  G1 E-1 F2100


[gcode_macro END_PRINT]
description: End G-Code
gcode:
  M106 S0
  M104 S0
  M140 S0
  G92 E0
  G91
  G1 E-1 F2100
  G1 Z+5 F6000
  G28
  G90
  LED_HOTEND_OFF
  M84


##################################################
# Pause / Resume / Cancel Print
##################################################

[gcode_macro PAUSE]
description: Pause the current print
rename_existing: PAUSE_BASE
gcode:
  ##### set defaults #####
  {% set x = params.X|default(0) %}
  {% set y = params.Y|default(-90) %}
  {% set z = params.Z|default(10)|float %}
  {% set e = params.E|default(1) %}
  ##### calculate save lift position #####
  {% set max_z = printer.toolhead.axis_maximum.z|float %}
  {% set act_z = printer.toolhead.position.z|float %}
  {% set lift_z = z|abs %}
  {% if act_z < (max_z - lift_z) %}
  {% set z_safe = lift_z %}
  {% else %}
  {% set z_safe = max_z - act_z %}
  {% endif %}
  ##### end of definitions #####
  RESPOND MSG="Pausing printing..."
  PAUSE_BASE
  G91
  G1 E-{e} F2100
  G1 Z{z_safe}
  G90
  G1 X{x} Y{y} F2500


[gcode_macro RESUME]
description: Resume the current print
rename_existing: RESUME_BASE
gcode:
  ##### set defaults #####
  {% set e = params.E|default(1) %}
  #### get VELOCITY parameter if specified ####
  {% if 'VELOCITY' in params|upper %}
  {% set get_params = ('VELOCITY=' + params.VELOCITY)  %}
  {% else %}
  {% set get_params = "" %}
  {% endif %}
  ##### end of definitions #####
  G91
  {% if printer["gcode_macro M600"].m600_enabled == 1 %}
  RESPOND MSG="Nozzle heating..."
  M109 S{printer["gcode_macro M600"].hotend_temp}
  M106 S{printer["gcode_macro M600"].fan_speed}
  RESPOND MSG="Loading filament..."
  G0 E50 F800
  G0 E30 F300
  M400
  SET_GCODE_VARIABLE MACRO=M600 VARIABLE=m600_enabled VALUE=0
  {% else %}
  G1 E{e} F2100
  {% endif %}
  RESPOND MSG="Resuming printing..."
  SET_IDLE_TIMEOUT TIMEOUT=1800
  RESUME_BASE {get_params}


[gcode_macro CANCEL_PRINT]
description: Cancel the current print
rename_existing: CANCEL_PRINT_BASE
gcode:
  RESPOND MSG="Printing canceled!"
  G28
  M106 S0
  M104 S0
  M140 S0
  CANCEL_PRINT_BASE


##################################################
# Filament / Color Change
##################################################

[gcode_macro M600]
description: Filament change
variable_hotend_temp: 0
variable_m600_enabled: 0
variable_fan_speed: 0
gcode:
  ##### set defaults #####
  {% set x = params.X|default(0) %}
  {% set y = params.Y|default(-140) %}
  {% set z = params.Z|default(10)|float %}
  {% set e = params.E|default(1) %}
  ##### calculate save lift position #####
  {% set max_z = printer.toolhead.axis_maximum.z|float %}
  {% set act_z = printer.toolhead.position.z|float %}
  {% set lift_z = z|abs %}
  {% if act_z < (max_z - lift_z) %}
  {% set z_safe = lift_z %}
  {% else %}
  {% set z_safe = max_z - act_z %}
  {% endif %}
  ##### end of definitions #####
  SAVE_GCODE_STATE NAME=M600_state
  SET_IDLE_TIMEOUT TIMEOUT=86400
  SET_GCODE_VARIABLE MACRO=M600 VARIABLE=m600_enabled VALUE=1
  SET_GCODE_VARIABLE MACRO=M600 VARIABLE=hotend_temp VALUE={printer.extruder.target}
  SET_GCODE_VARIABLE MACRO=M600 VARIABLE=fan_speed VALUE={printer.fan.speed}
  RESPOND MSG="Pausing printing..."
  PAUSE
  G91
  G1 E-{e} F2100
  G1 Z{z_safe}
  G90
  G1 X{x} Y{y} F2500
  RESPOND MSG="Unloading filament..."
  G91
  G0 E-10 F300
  G0 E-30 F800
  M400
  RESPOND MSG="Nozzle heating stopped!"
  M104 S0
  M106 S0
  RESTORE_GCODE_STATE NAME=M600_state


##################################################
# Load / Unload Filament
##################################################

[gcode_macro UNLOAD_FILAMENT]
description: Filament unloading
gcode:
  {% if printer.idle_timeout.state == "Printing" and not printer.pause_resume.is_paused %}
  RESPOND TYPE=error MSG="This macro cannot be used while printing!"
  {% else %}
  SAVE_GCODE_STATE NAME=unload_state
  {% if printer.extruder.temperature < 200 %}
  RESPOND MSG="Nozzle heating..."
  M109 S200
  {% endif %}
  RESPOND MSG="Unloading filament..."
  G91
  G0 E-10 F300
  G0 E-30 F800
  RESTORE_GCODE_STATE NAME=unload_state
  {% endif %}


[gcode_macro LOAD_FILAMENT]
description: Filament loading
gcode:
  {% if printer.idle_timeout.state == "Printing" and not printer.pause_resume.is_paused %}
  RESPOND TYPE=error MSG="This macro cannot be used while printing!"
  {% else %}
  SAVE_GCODE_STATE NAME=load_state
  {% if printer.extruder.temperature < 200 %}
  RESPOND MSG="Nozzle heating..."
  M109 S200
  {% endif %}
  RESPOND MSG="Loading filament..."
  G91
  G0 E50 F800
  G0 E30 F300
  M400
  RESTORE_GCODE_STATE NAME=load_state
  {% endif %}


##################################################
# Calibrations
##################################################

[gcode_macro Z_OFFSET_CALIBRATION]
description: Measure Z-Offset
gcode:
  SET_GCODE_OFFSET Z=0
  G28
  G1 X0 Y0 Z50 F2500
  M400
  #SET_GCODE_VARIABLE MACRO=_KNOMI_STATUS VARIABLE=probing VALUE=True  # Enable if Knomi is used
  PROBE_CALIBRATE
  #SET_GCODE_VARIABLE MACRO=_KNOMI_STATUS VARIABLE=probing VALUE=False  # Enable if Knomi is used


[gcode_macro ENDSTOPS_CALIBRATION]
description: Endstops Phase Calibration
gcode:
  {% if printer.idle_timeout.state == "Printing" %}
  RESPOND TYPE=error MSG="This macro cannot be used while printing!"
  {% else %}
  {% if printer.toolhead.homed_axes != "xyz" %}
  G28
  {% endif %}
  G91
  G0 Z-80 F1500
  G28
  G91
  G0 Z-80 F1500
  G28
  G91
  G0 Z-80 F1500
  G28
  G91
  G0 Z-80 F1500
  G28
  G91
  G0 Z-80 F1500
  ENDSTOP_PHASE_CALIBRATE stepper=stepper_a
  ENDSTOP_PHASE_CALIBRATE stepper=stepper_b
  ENDSTOP_PHASE_CALIBRATE stepper=stepper_c
  M400
  G28
  {% endif %}


[gcode_macro DELTA_CALIBRATION]
description: Delta Calibration
gcode:
  {% if printer.idle_timeout.state == "Printing" %}
  RESPOND TYPE=error MSG="This macro cannot be used while printing!"
  {% else %}
  SET_GCODE_OFFSET Z=0
  BED_MESH_CLEAR
  {% if printer.toolhead.homed_axes != "xyz" %}
  G28
  {% endif %}
  #SET_GCODE_VARIABLE MACRO=_KNOMI_STATUS VARIABLE=probing VALUE=True  # Enable if Knomi is used
  DELTA_CALIBRATE
  #SET_GCODE_VARIABLE MACRO=_KNOMI_STATUS VARIABLE=probing VALUE=False  # Enable if Knomi is used
  M400
  G1 X0 Y0 Z50 F2500
  G28
  {% endif %}


[gcode_macro BED_LEVELING]
description: Bed Leveling
gcode:
  {% if printer.idle_timeout.state == "Printing" %}
  RESPOND TYPE=error MSG="This macro cannot be used while printing!"
  {% else %}
  SET_GCODE_OFFSET Z=0
  {% if printer.toolhead.homed_axes != "xyz" %}
  G28
  {% endif %}
  G1 X0 Y0 Z50 F2500
  #SET_GCODE_VARIABLE MACRO=_KNOMI_STATUS VARIABLE=probing VALUE=True  # Enable if Knomi is used
  BED_MESH_CALIBRATE
  #SET_GCODE_VARIABLE MACRO=_KNOMI_STATUS VARIABLE=probing VALUE=False  # Enable if Knomi is used
  M400
  G1 X0 Y0 Z50 F2500
  G28
  {% endif %}


[gcode_macro PRESSURE_ADVANCE]
description: Pressure Advance
gcode:
  {% if printer.idle_timeout.state == "Printing" %}
  RESPOND TYPE=error MSG="This macro cannot be used while printing!"
  {% else %}
  SET_PRESSURE_ADVANCE ADVANCE=0   
  SET_VELOCITY_LIMIT SQUARE_CORNER_VELOCITY=1 ACCEL=500
  TUNING_TOWER COMMAND=SET_PRESSURE_ADVANCE PARAMETER=ADVANCE START=0 FACTOR=.005
  {% endif %}


##################################################
# Nozzle / Bed PID Calibration
##################################################

[gcode_macro PID_BED]
description: Bed PID
gcode:
  {% if printer.idle_timeout.state == "Printing" %}
  RESPOND TYPE=error MSG="This macro cannot be used while printing!"
  {% else %}
  RESPOND MSG="Bed PID calibration in progress..."
  G28
  G90
  G1 Z50 F1500
  M400
  M106
  PID_CALIBRATE HEATER=heater_bed TARGET={params.TEMP|default(70)}
  M107
  RESPOND MSG="PID calibration complete! Remember to save the configuration!"
  G28
  {% endif %}


[gcode_macro PID_HOTEND]
description: Hotend PID
gcode:
  {% if printer.idle_timeout.state == "Printing" %}
  RESPOND TYPE=error MSG="This macro cannot be used while printing!"
  {% else %}
  RESPOND MSG="Hotend PID calibration in progress..."
  G28
  G90
  G1 Z50 F1500
  M400
  M106
  PID_CALIBRATE HEATER=extruder TARGET={params.TEMP|default(250)}
  M107
  RESPOND MSG="PID calibration complete! Remember to save the configuration!"
  G28
  {% endif %}
  
  
[gcode_macro _PID_KS_START]
description: PID for KlipperScreen
gcode:
  RESPOND MSG="PID calibration in progress..."
  G28
  G90
  G1 Z50 F1500
  M400
  M106


[gcode_macro _PID_KS_END]
description: PID for KlipperScreen
gcode:
  M107
  RESPOND MSG="PID calibration complete! Remember to save the configuration!"
  G28


##################################################
# Verifications and Measurements with ADXL
##################################################

[gcode_macro ADXL_TEST]
description: ADXL Test
gcode:
  ACCELEROMETER_QUERY


[gcode_macro ADXL_NOISE]
description: Measure Accelerometer Noise
gcode:
  MEASURE_AXES_NOISE


[gcode_macro ADXL_AXE_X]
description: Measure X axis resonances
gcode:
  SHAPER_CALIBRATE AXIS=X


[gcode_macro ADXL_AXE_Y]
description: Measure Y axis resonances
gcode:
  SHAPER_CALIBRATE AXIS=Y


##################################################
# Save Configuration
##################################################

[gcode_macro SAVE]
description: Save Configuration
gcode:
  SAVE_CONFIG


##################################################
# Power On/Off LED
##################################################

[gcode_macro LED_HOTEND_ON]
description: Turn on Hotend LEDs
gcode:
  SET_PIN PIN=LED_Hotend VALUE=1


[gcode_macro LED_HOTEND_OFF]
description: Turn off Hotend LEDs
gcode:
  SET_PIN PIN=LED_Hotend VALUE=0


[gcode_macro LED_LOGO_ON]
description: Turn on Logo LEDs
gcode:
  SET_PIN PIN=LED_Logo VALUE=1


[gcode_macro LED_LOGO_OFF]
description: Turn off Logo LEDs
gcode:
  SET_PIN PIN=LED_Logo VALUE=0


##################################################
# Managing Slicer Controls
##################################################

[gcode_macro M204]
description: Sets maximum accelleration
rename_existing: M204.1
gcode:
  {% if 'S' in params %}
  {% set s = params.S|float %}
  SET_VELOCITY_LIMIT ACCEL={s}
  {% else %}
  {% if 'P' in params %}
  {% set p = params.P|float %}
  {% if 'T' in params %}
  {% set t = params.T|float %}
  {% if p < t %}
  SET_VELOCITY_LIMIT ACCEL={p}
  {% else %}
  SET_VELOCITY_LIMIT ACCEL={t}
  {% endif %}
  {% else %}
  SET_VELOCITY_LIMIT ACCEL={p}
  {% endif %}
  {% elif 'T' in params %}
  {% set t = params.T|float %}
  SET_VELOCITY_LIMIT ACCEL={t}
  {% endif %}
  {% endif %}


[gcode_macro M205]
description: Sets square corner velocity
gcode:
  {% if 'X' in params %}
  SET_VELOCITY_LIMIT SQUARE_CORNER_VELOCITY={params.X}
  {% elif 'Y' in params %}
  SET_VELOCITY_LIMIT SQUARE_CORNER_VELOCITY={params.Y}
  {% endif %}
  

##################################################
# Managing Temperatures Controls
##################################################

[gcode_macro M109]
description: Managing extruder temperature
rename_existing: M99109
gcode:
  {% set s = params.S|float %}
  M104 {% for p in params %}{'%s%s' % (p, params[p])}{% endfor %}
  {% if s != 0 %}
  TEMPERATURE_WAIT SENSOR=extruder MINIMUM={s} MAXIMUM={s+1}
  {% endif %}


[gcode_macro M190]
description: Managing bed temperature
rename_existing: M99190
gcode:
  {% set s = params.S|float %}
  M140 {% for p in params %}{'%s%s' % (p, params[p])}{% endfor %}
  {% if s != 0 %}
  TEMPERATURE_WAIT SENSOR=heater_bed MINIMUM={s} MAXIMUM={s+1}
  {% endif %}


##################################################
# Loading default bed mesh at startup
##################################################

[delayed_gcode bed_mesh_init]
initial_duration: .01
gcode:
  BED_MESH_PROFILE LOAD=default


##################################################
# KNOMI
##################################################

# Enable this section if Knomi is used

#[homing_override]
#gcode:
  #SET_GCODE_VARIABLE MACRO=_KNOMI_STATUS VARIABLE=homing VALUE=True
  #G28
  #SET_GCODE_VARIABLE MACRO=_KNOMI_STATUS VARIABLE=homing VALUE=False


#[gcode_macro _KNOMI_STATUS] 
#variable_homing: False  
#variable_probing: False  
#gcode:


##################################################
# Z-Offset Management
##################################################

[gcode_macro SECURITY_OFFSET]
description: Apply a 2mm Safety Offset
gcode:
  SET_GCODE_OFFSET Z=+2
  RESPOND MSG="Safety Offset applied!"


[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 %}
