[force_move]
enable_force_move: True

# NOTE If you're using a Raspberry Pi, you can uncomment the next 2 lines, optionally.
# [temperature_sensor raspberry_pi]
# sensor_type: temperature_host

# NOTE If you're using a an Orange Pi, you can uncomment the next 2 lines, optionally.
# [temperature_sensor Orange_Pi]
# sensor_type: temperature_host
# sensor_path: /sys/class/thermal/thermal_zone0/temp

[virtual_sdcard]
path: /home/pi/printer_data/gcodes

# NOTE Cancel objects feature is enabled. If you're using a low powered device, comment out [exclude_object].
# Also see [file_manager] section in moonraker.conf.
[exclude_object]

[pause_resume]
[display_status]

[delayed_gcode DISABLEFILAMENTSENSOR]
initial_duration: 1
gcode:
    SET_FILAMENT_SENSOR SENSOR=filament_sensor ENABLE=0

[gcode_macro _globals]
variable_filament_sensor_enabled: 1 # NOTE Enable(1) or disable(0) the filament sensor, if one is connected
variable_beeping_enabled: 0 # NOTE Enable(1) or disable(0) beeping everywhere except during gantry calibration
variable_bed_temp_over: 10 # NOTE Start print if bed temperature is over by this amount, otherwise wait for temperature drop
variable_pre_purge_prime_length: 1.40
gcode:
    # DELETEME This section is unnecessary
    SET_GCODE_VARIABLE MACRO=_globals VARIABLE=pre_purge_prime_length VALUE={ variable_pre_purge_prime_length }
    SET_GCODE_VARIABLE MACRO=_globals VARIABLE=filament_sensor_enabled VALUE={ variable_filament_sensor_enabled }
    SET_GCODE_VARIABLE MACRO=_globals VARIABLE=beeping_enabled VALUE={ variable_beeping_enabled }
    SET_GCODE_VARIABLE MACRO=_globals VARIABLE=bed_temp_over VALUE={ variable_bed_temp_over }

[gcode_macro CONDITIONAL_BEEP]
gcode:
    # Parameters
    {% set i = params.I|default(1)|int %}           ; Iterations (number of times to beep).
    {% set dur = params.DUR|default(100)|int %}     ; Duration/wait of each beep in ms. Default 100ms.
    {% set freq = params.FREQ|default(2000)|int %}  ; Frequency in Hz. Default 2kHz.

    {% set BEEPING_ENABLED=printer["gcode_macro _globals"].beeping_enabled|default(-1)|int %}

    {% if BEEPING_ENABLED == 1 %}
        BEEP I={i} DUR={dur} FREQ={freq}
    {% endif %}

[gcode_macro ADJUST_FILAMENT_SENSOR_STATUS]
gcode:
    # Parameters
    {% set NEWSTATUS = params.ENABLE|default(-1)|int %}

    {% set FILAMENT_SENSOR_ENABLED=printer["gcode_macro _globals"].filament_sensor_enabled|default(-1)|int %}

    {% if FILAMENT_SENSOR_ENABLED == 1 and NEWSTATUS != -1 %}
        SET_FILAMENT_SENSOR SENSOR=filament_sensor ENABLE={NEWSTATUS}
    {% endif %}

[gcode_macro M109]
rename_existing: M99109
gcode:
    #Parameters
    {% set s = params.S|float %}
    
    M104 {% for p in params %}{'%s%s' % (p, params[p])}{% endfor %}  ; Set hotend temp
    {% if s != 0 %}
        TEMPERATURE_WAIT SENSOR=extruder MINIMUM={s} MAXIMUM={s+1}   ; Wait for hotend temp (within 1 degree)
    {% endif %}

[gcode_macro M190]
rename_existing: M99190
gcode:
    #Parameters
    {% set s = params.S|float %}

    M140 {% for p in params %}{'%s%s' % (p, params[p])}{% endfor %}   ; Set bed temp
    {% if s != 0 %}
        TEMPERATURE_WAIT SENSOR=heater_bed MINIMUM={s} MAXIMUM={s+1}  ; Wait for bed temp (within 1 degree)
    {% endif %}

[gcode_macro PURGE_LINE]
gcode:
    {% set PRE_PURGE_PRIME_LENGTH=printer["gcode_macro _globals"].pre_purge_prime_length|default(1.40)|float %}
    ADJUST_FILAMENT_SENSOR_STATUS ENABLE=1

    #   Misc variables
    {% set extrudeAmount = 26.6 %}
    {% set movementLength = 100.0 %}
    {% set movementSpeed = 15 * 60 %}
    {% set xStart = 0.5 %}
    {% set yStart = 0.5 %}

    #   Set safe speeds
    {% set maxVelocity = printer.configfile.settings.printer.max_velocity|default(200)|int %}
    {% set maxVelocityAdjusted =  (0.95 * maxVelocity * 60)|int  %}

    G92 E0.0                                ; reset extruder
    G90                                     ; Absolute positioning
    G0 X{xStart} Y{yStart} F{maxVelocityAdjusted}         ; move to purge position
    G1 Z0.4 F500.0                          ; move to purge height
    M83                                     ; Relative extrusion mode
    G1 E{PRE_PURGE_PRIME_LENGTH} F500       ; pre-purge prime LENGTH SHOULD MATCH YOUR PRINT_END RETRACT
    G1 X{xStart + movementLength} E{extrudeAmount} F{movementSpeed}       ; intro line 1

    G92 E0.0                                ; reset extruder
    M82                                     ; Absolute extrusion mode
    G1 Z5.0                                 ; move nozzle to prevent scratch

[gcode_macro CANCEL_PRINT]
rename_existing: BASE_CANCEL_PRINT
gcode:
    SET_IDLE_TIMEOUT TIMEOUT={printer.configfile.settings.idle_timeout.timeout} ; set timeout back to configured value
    CLEAR_PAUSE
    SDCARD_RESET_FILE
    PRINT_END
    BASE_CANCEL_PRINT

[gcode_macro PRINT_START]
gcode:
    # Parameters
    {% set bedtemp = params.BED|int %}
    {% set hotendtemp = params.HOTEND|int %}
    {% set chambertemp = params.CHAMBER|default(0)|int %}
    
    # Other variables
    {% set bedtempSlicer = bedtemp %}
    {% set bedtempOver = printer["gcode_macro _globals"].bed_temp_over|default(0)|int %}
    {% set maxVelocity = printer.configfile.settings.printer.max_velocity|default(200)|int %}
    {% set maxVelocityAdjusted =  (0.90 * maxVelocity * 60)|int %}

    {% if printer.configfile.settings.safe_z_home %}
        {% set startX = printer.configfile.settings.safe_z_home.home_xy_position[0]|float %}
        {% set startY = printer.configfile.settings.safe_z_home.home_xy_position[1]|float %}
    {% endif %}

    {% set bedtempAlmost = ((bedtemp - 2, 0, printer.heater_bed.temperature|int)|max, bedtemp)|max %}
    {% set hotendtempStepOne = ((hotendtemp, printer[printer.toolhead.extruder].temperature|int)|min, 150)|max %}
    {% set hotendtempStepTwo = ((hotendtemp, printer[printer.toolhead.extruder].temperature|int)|min, 170)|max %}

    # If bed-temp-almost is higher than bed-temp by a maximum of bed-temp-over
    {% if bedtempAlmost > bedtemp %}
        {% if (bedtempAlmost - bedtempOver) <= bedtemp %}
            {% set bedtemp = bedtempAlmost %}
        {% endif %}
    {% endif %}

    BED_MESH_PROFILE LOAD=default                        ; NOTE if not using a mesh, comment out this line
    ADJUST_FILAMENT_SENSOR_STATUS ENABLE=1

    G90                                                  ; absolute positioning
    M140 S{bedtempAlmost}                                ; set & don't wait for bed temp
    M104 S{hotendtempStepOne}                            ; set & don't wait for hotend temp
    G28 X Y
    {% if printer.configfile.settings.safe_z_home %}
        G1 X{startX} Y{startY} F{maxVelocityAdjusted}
    {% endif %}

    M190 S{bedtempAlmost}                                ; set & wait for bed temp
    M104 S{hotendtempStepTwo}                            ; set & don't wait for hotend temp
    M190 S{bedtemp}                                      ; set & wait for bed temp
    M140 S{bedtempSlicer}                                ; set & don't wait for bed temp ; set temp to sliced setting regardless

    M104 S{hotendtemp}                                   ; set & don't wait for hotend temp
    G28 Z                                                ; final z homing

    G1 X0 Y0 F{maxVelocityAdjusted}
    M109 S{hotendtemp}                                   ; set & wait for hotend temp

    G1 Z20 F3000                                         ; move nozzle away from bed

[gcode_macro PRINT_END]
gcode:
    ADJUST_FILAMENT_SENSOR_STATUS ENABLE=0
    CONDITIONAL_BEEP I=2 DUR=30 FREQ=8500
    {% set PRE_PURGE_PRIME_LENGTH=printer["gcode_macro _globals"].pre_purge_prime_length|default(1.40)|float %}

    M400                                    ; wait for buffer to clear
    G92 E0                                  ; zero the extruder
    G1 E-{PRE_PURGE_PRIME_LENGTH} F400      ; retract filament
    G91                                     ; relative positioning

    #   Set safe speeds
    {% set zVelocity = printer.configfile.settings.printer.max_z_velocity|default(15)|int %}
    {% set maxVelocity = printer.configfile.settings.printer.max_velocity|default(200)|int %}
    {% set zVelocityAdjusted =  (0.95 * zVelocity * 60)|int  %}
    {% set maxVelocityAdjusted =  (0.95 * maxVelocity * 60)|int  %}

    #   Get Boundaries
    {% set max_x = printer.configfile.config["stepper_x"]["position_max"]|float %}
    {% set max_y = printer.configfile.config["stepper_y"]["position_max"]|float %}
    {% set max_z = printer.configfile.config["stepper_z"]["position_max"]|float %}

    #   Check end position to determine safe direction to move
    {% if printer.toolhead.position.x < (max_x - 20) %}
        {% set x_safe = 20.0 %}
    {% else %}
        {% set x_safe = -20.0 %}
    {% endif %}

    {% if printer.toolhead.position.y < (max_y - 20) %}
        {% set y_safe = 20.0 %}
    {% else %}
        {% set y_safe = -20.0 %}
    {% endif %}

    {% set lift_height = 25.0 %}
    {% if printer.toolhead.position.z < (max_z - lift_height) %}
        {% set z_safe = lift_height %}
    {% else %}
        {% set z_safe = max_z - printer.toolhead.position.z %}
    {% endif %}

    G0 Z{z_safe} F{zVelocityAdjusted}             ; move nozzle up
    G0 X{x_safe} Y{y_safe} F{maxVelocityAdjusted}   ; move nozzle to remove stringing
    TURN_OFF_HEATERS
    M107                           ; turn off fan
    G90                            ; absolute positioning
    G0 X60 Y{max_y} F3600          ; park nozzle at rear

[gcode_macro LOAD_FILAMENT]
gcode:
    M83                            ; set extruder to relative
    G1 E30 F300                    ; load
    G1 E15 F150                    ; prime nozzle with filament
    M82                            ; set extruder to absolute
    
[gcode_macro UNLOAD_FILAMENT]
gcode:
    M83                            ; set extruder to relative
    G1 E10 F300                    ; extrude a little to soften tip
    G1 E-40 F1800                  ; retract some, but not too much or it will jam
    M82                            ; set extruder to absolute

[gcode_macro M600]
gcode:
    CONDITIONAL_BEEP i=1 dur=300
    CONDITIONAL_BEEP i=1 dur=100
    CONDITIONAL_BEEP i=1 dur=100
    PAUSE                ; Pause

[gcode_macro PAUSE]
rename_existing: BASE_PAUSE
gcode:
    # Parameters
    {% set z = params.Z|default(10)|int %}                                                   ; z hop amount

    {% if printer['pause_resume'].is_paused|int == 0 %}
        SET_GCODE_VARIABLE MACRO=RESUME VARIABLE=zhop VALUE={z}                              ; set z hop variable for reference in resume macro
        SET_GCODE_VARIABLE MACRO=RESUME VARIABLE=etemp VALUE={printer['extruder'].target}    ; set hotend temp variable for reference in resume macro

        ADJUST_FILAMENT_SENSOR_STATUS ENABLE=0

        SAVE_GCODE_STATE NAME=PAUSE                                                          ; save current print position for resume
        BASE_PAUSE                                                                           ; pause print
        {% if (printer.gcode_move.position.z + z) < printer.toolhead.axis_maximum.z %}       ; check that zhop doesn't exceed z max
            G91                                                                              ; relative positioning
            G1 Z{z} F900                                                                     ; raise Z up by z hop amount
        {% else %}
            { action_respond_info("Pause zhop exceeds maximum Z height.") }                  ; if z max is exceeded, show message and set zhop value for resume to 0
            SET_GCODE_VARIABLE MACRO=RESUME VARIABLE=zhop VALUE=0
        {% endif %}
        G90                                                                                  ; absolute positioning
        G1 X{printer.toolhead.axis_maximum.x/2} Y{printer.toolhead.axis_minimum.y+5} F6000   ; park toolhead at front center
        SAVE_GCODE_STATE NAME=PAUSEPARK                                                      ; save parked position in case toolhead is moved during the pause (otherwise the return zhop can error)
        M104 S0                                                                              ; turn off hotend
        SET_IDLE_TIMEOUT TIMEOUT=43200                                                       ; set timeout to 12 hours
    {% endif %}

[gcode_macro RESUME]
rename_existing: BASE_RESUME
variable_zhop: 0
variable_etemp: 0
gcode:
    # Parameters
    {% set e = params.E|default(2.5)|int %}                                          ; hotend prime amount (in mm)

    {% if printer['pause_resume'].is_paused|int == 1 %}
        ADJUST_FILAMENT_SENSOR_STATUS ENABLE=1

        SET_IDLE_TIMEOUT TIMEOUT={printer.configfile.settings.idle_timeout.timeout}  ; set timeout back to configured value
        {% if etemp > 0 %}
            M109 S{etemp|int}                                                        ; wait for hotend to heat back up
        {% endif %}
        RESTORE_GCODE_STATE NAME=PAUSEPARK MOVE=1 MOVE_SPEED=100                     ; go back to parked position in case toolhead was moved during pause (otherwise the return zhop can error)
        G91                                                                          ; relative positioning
        M83                                                                          ; relative extruder positioning
        {% if printer[printer.toolhead.extruder].temperature >= printer.configfile.settings.extruder.min_extrude_temp %}
            G1 Z{zhop * -1} E{e} F900                                                ; prime nozzle by E, lower Z back down
        {% else %}
            G1 Z{zhop * -1} F900                                                     ; lower Z back down without priming (just in case we are testing the macro with cold hotend)
        {% endif %}
        RESTORE_GCODE_STATE NAME=PAUSE MOVE=1 MOVE_SPEED=60                          ; restore position
        BASE_RESUME                                                                  ; resume print
    {% endif %}

[gcode_macro _CG28]
# Conditional homing
gcode:
    {% if "xyz" not in printer.toolhead.homed_axes %}
        G28
    {% endif %}

[gcode_macro BEEP]
description: BEEP I=3 DUR=200 FREQ=2000: Beep 3 times, for 200ms each, at 2kHz frequency.
gcode:
    # Parameters
    {% set i = params.I|default(1)|int %}           ; Iterations (number of times to beep).
    {% set dur = params.DUR|default(100)|int %}     ; Duration/wait of each beep in ms. Default 100ms.
    {% set freq = params.FREQ|default(2000)|int %}  ; Frequency in Hz. Default 2kHz.

    {% for iteration in range(i|int) %}
        SET_PIN PIN=beeper VALUE=0.8 CYCLE_TIME={ 1.0/freq if freq > 0 else 1 }
        G4 P{dur}
        SET_PIN PIN=beeper VALUE=0
        G4 P{dur}
    {% endfor %}