Changing End G-Code in Cura settings to protect hotend

Hello,

Noticed that the stock g-code settings in Cura have some disadvantages that might lead to problems with the hotend.

This is the original code:

; Disable all extruder M107 ; Turn off fan G91 ; Relative positioning {IF_EXT0}T0 {IF_EXT0}G1 E-1 ; Reduce filament pressure M104 T0 S0 {IF_EXT1}T1 {IF_EXT1}G1 E-1 ; Reduce filament pressure M104 T1 S0 G90 ; Absolute positioning G92 E0 ; Reset extruder position M140 S0 ; Disable heated bed M84 ; Turn steppers off T0 T1 T0

Problem: The fan is turned of first.
As is known, the actual temperature of the hotend is already higher than the thermistor reports due to the fan and the insulation material around the thermistor. If the fan is turned off while the heater is still running, it might lead to a substantial overshoot of the temperature. In my case I saw a rise to 215°C while the printing temperature was 190°C. If I manually pushed some filament into the hotend, I saw a puff of smoke coming out. This leads me to believe that the actual temperature was beyond 220°C. Without the fans running this temperature is held for around 20-30 seconds before it starts to drop very slowly.
While no danger with PLA, a similar behaviour might lead to damage of the PEEK tube when printing with ABS.

Here is my solution:

; Disable all extruder M117 Bah a la la la G0 Z190 ;move platform to bottom G91 ; Relative positioning {IF_EXT0}T0 {IF_EXT0}G1 E-1 ; Reduce filament pressure M104 T0 S0 {IF_EXT1}T1 {IF_EXT1}G1 E-1 ; Reduce filament pressure M104 T1 S0 G90 ; Absolute positioning G92 E0 ; Reset extruder position M140 S0 ; Disable heated bed G4 P30000 M107 M84 ; Turn steppers off T0 T1 T0

M107: disable fan
G4 P30000: Dwell, amount of time defined by Pxxxxx in milliseconds, here 30 seconds.
(M117 and G0 Z190 are added just for fun)

Additionally cura generates a second M107 command in the G-Code:

This should be deleted in the editor.

The 30 second delay before turning off the fans is enough to drop the hotend temperature to around 150-160°C from 190°C print temperature (in reality higher). I would prefer to have an actual script waiting for the temperature instead of waiting a pre-defined amount of time, but have no clue how to do that.