├── assets
├── q
└── toolchanger.jpg
├── doc
├── 1589F0.png
├── c5f015.png
├── f03c15.png
└── command_ref.md
├── config
├── optional_macros
│ ├── G10.cfg
│ ├── M107.cfg
│ ├── M116.cfg
│ ├── M204.cfg
│ ├── M104.cfg
│ ├── M106.cfg
│ ├── M109.cfg
│ ├── M568.cfg
│ └── readme.md
├── example_simple
│ ├── readme.md
│ └── tools.cfg
├── example_complex
│ ├── readme.md
│ ├── tool_macro.cfg
│ └── tools.cfg
├── SuperSlicer_Custom_Gcode.md
└── readme.md
├── klipper_macros
├── G10.cfg
├── M107.cfg
├── M116.cfg
├── M204.cfg
├── M566.cfg
├── M104.cfg
├── M106.cfg
├── M109.cfg
├── M568.cfg
└── readme.md
├── install.sh
├── toolgroup.py
├── README.md
├── toollock.py
├── LICENSE
└── ktcclog.py
/assets/q:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/doc/1589F0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/Klipper_ToolChanger/HEAD/doc/1589F0.png
--------------------------------------------------------------------------------
/doc/c5f015.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/Klipper_ToolChanger/HEAD/doc/c5f015.png
--------------------------------------------------------------------------------
/doc/f03c15.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/Klipper_ToolChanger/HEAD/doc/f03c15.png
--------------------------------------------------------------------------------
/assets/toolchanger.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/Klipper_ToolChanger/HEAD/assets/toolchanger.jpg
--------------------------------------------------------------------------------
/config/optional_macros/G10.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro G10]
2 | description: See M568. Passtrough to M568.
3 | gcode:
4 | M568 {rawparams}
5 |
--------------------------------------------------------------------------------
/klipper_macros/G10.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro G10]
2 | description: See M568. Passtrough to M568.
3 | gcode:
4 | M568 {rawparams}
5 |
--------------------------------------------------------------------------------
/config/example_simple/readme.md:
--------------------------------------------------------------------------------
1 | # Simple examples
2 |
3 | This are basic example file to get you started.
4 |
5 | the files should be added to your printer.cfg like:
6 |
7 | `[include custom/tools.cfg]`
8 |
9 | This is for use with a Jubilee style printer.
10 |
--------------------------------------------------------------------------------
/config/optional_macros/M107.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M107]
2 | description: Pnnn
3 | Turn off fan.
4 | P = Tool (optional and defaults to the currently selected tool)
5 | gcode:
6 | # P= Tool number and optional T.
7 | {% if params.P is defined %}
8 | {% set p = " P"~params.P %}
9 | {% elif params.T is defined %}
10 | {% set p = " P"~params.T %}
11 | {% endif %}
12 |
13 | M106 {p|default("")} S0
14 |
15 |
--------------------------------------------------------------------------------
/klipper_macros/M107.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M107]
2 | description: Pnnn
3 | Turn off fan.
4 | P = Tool (optional and defaults to the currently selected tool)
5 | gcode:
6 | # P= Tool number and optional T.
7 | {% if params.P is defined %}
8 | {% set p = " P"~params.P %}
9 | {% elif params.T is defined %}
10 | {% set p = " P"~params.T %}
11 | {% endif %}
12 |
13 | M106 {p|default("")} S0
14 |
15 |
--------------------------------------------------------------------------------
/config/example_complex/readme.md:
--------------------------------------------------------------------------------
1 | # More complex example
2 |
3 | This are example files with macros to get you started.
4 | * It uses T0 as a physical tool having T1-T8 as virtual tools.
5 | * T9 and T10 are physical tools without virtual tools.
6 | * T49 is a physical tool without a heater, fan or extruder. Only has a Z probe.
7 |
8 | The files should be added to your printer.cfg like:
9 |
10 | ```
11 | [include custom/tools.cfg]
12 | [include custom/tools.cfg]
13 | ```
14 |
15 | This is for use with a Jubilee style printer.
16 |
--------------------------------------------------------------------------------
/config/optional_macros/M116.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M116]
2 | description: T P H S W
3 | Alias for M109.
4 | Waits for all temperatures, or a specified tool or heater's temperature.
5 | This command can be used without any additional parameters.
6 | Without parameters it waits for bed and current extruder.
7 |
8 | Tnnn Tool number.
9 | Pnnn Alternative to T.
10 | Hnnn Heater number.
11 | Snnn Temperature
12 | Wnnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
13 |
14 | gcode:
15 | M109 {rawparams}
--------------------------------------------------------------------------------
/klipper_macros/M116.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M116]
2 | description: T P H S W
3 | Alias for M109.
4 | Waits for all temperatures, or a specified tool or heater's temperature.
5 | This command can be used without any additional parameters.
6 | Without parameters it waits for bed and current extruder.
7 |
8 | Tnnn Tool number.
9 | Pnnn Alternative to T.
10 | Hnnn Heater number.
11 | Snnn Temperature
12 | Wnnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
13 |
14 | gcode:
15 | M109 {rawparams}
--------------------------------------------------------------------------------
/config/optional_macros/M204.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M204]
2 | rename_existing: M204.1
3 | description: Snnn / Pnnn Tnnn
4 | Set acceleration either S or P and T must be provided.
5 | If P and T provided then will use the lower of the two.
6 | gcode:
7 |
8 | {% if params.S is defined %}
9 | {% set accel = params.S|float %}
10 | {% elif params.P is defined or params.T is defined %}
11 | {% set p = params.P|default(999999)|int %}
12 | {% set t = params.T|default(999999)|int %}
13 | {% if p < t %}
14 | {% set accel = p %}
15 | {% else %}
16 | {% set accel = t %}
17 | {% endif %}
18 | {% else %}
19 | { action_raise_error("M204: Must provide S, P or T parameter.") }
20 | {% endif %}
21 |
22 | SET_VELOCITY_LIMIT ACCEL={accel} ACCEL_TO_DECEL={accel*0.5}
23 |
24 |
--------------------------------------------------------------------------------
/klipper_macros/M204.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M204]
2 | rename_existing: M204.1
3 | description: Snnn / Pnnn Tnnn
4 | Set acceleration either S or P and T must be provided.
5 | If P and T provided then will use the lower of the two.
6 | gcode:
7 |
8 | {% if params.S is defined %}
9 | {% set accel = params.S|float %}
10 | {% elif params.P is defined or params.T is defined %}
11 | {% set p = params.P|default(999999)|int %}
12 | {% set t = params.T|default(999999)|int %}
13 | {% if p < t %}
14 | {% set accel = p %}
15 | {% else %}
16 | {% set accel = t %}
17 | {% endif %}
18 | {% else %}
19 | { action_raise_error("M204: Must provide S, P or T parameter.") }
20 | {% endif %}
21 |
22 | SET_VELOCITY_LIMIT ACCEL={accel} ACCEL_TO_DECEL={accel*0.5}
23 |
24 |
--------------------------------------------------------------------------------
/klipper_macros/M566.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M566]
2 | description: Xnnn Ynnn
3 | Set Square Corner Velocity in RRF style.
4 | Only the lower of required X or Y will be used.
5 | gcode:
6 | # RESPOND MSG="M566: Seting new Square Corner Velocity." #: {rawparams}.
7 | # { action_respond_info("M566: Seting new Square Corner Velocity: "~rawparams) }
8 |
9 | {% if params.X is defined or params.Y is defined %}
10 | {% set x = params.X|default(999999)|int %}
11 | {% set y = params.Y|default(999999)|int %}
12 | {% if x < y %}
13 | {% set square_corenr_velocity = x %}
14 | {% else %}
15 | {% set square_corenr_velocity = y %}
16 | {% endif %}
17 | gcode: SQUARE_CORNER_VELOCITY={square_corenr_velocity/60}
18 | {% else %}
19 | { action_raise_error("M566: At least X or Y must be defined.") }
20 | {% endif %}
21 |
22 |
23 |
--------------------------------------------------------------------------------
/config/optional_macros/M104.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M104]
2 | rename_existing: M104.1
3 | description: [T] [S]
4 | Set tool temperature.
5 | T= Tool number, optional. If this parameter is not provided, the current tool is used.
6 | S= Active temperature(s), optional
7 | gcode:
8 | {% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
9 |
10 | # P= Tool number and optional T.
11 | {% if params.P is defined %}
12 | {% set newparameters = newparameters ~ " P="~params.P %}
13 | {% elif params.T is defined %}
14 | {% set newparameters = newparameters ~ " P="~params.T %}
15 | {% endif %}
16 |
17 | # S= Active temperature
18 | {% if params.S is defined %}
19 | {% set newparameters = newparameters ~ " ACTV_TMP="~params.S %}
20 | {% endif %}
21 |
22 | KTCC_SET_TOOL_TEMPERATURE{newparameters}
23 |
--------------------------------------------------------------------------------
/klipper_macros/M104.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M104]
2 | rename_existing: M104.1
3 | description: [T] [S]
4 | Set tool temperature.
5 | T= Tool number, optional. If this parameter is not provided, the current tool is used.
6 | S= Active temperature(s), optional
7 | gcode:
8 | {% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
9 |
10 | # P= Tool number and optional T.
11 | {% if params.P is defined %}
12 | {% set newparameters = newparameters ~ " P="~params.P %}
13 | {% elif params.T is defined %}
14 | {% set newparameters = newparameters ~ " P="~params.T %}
15 | {% endif %}
16 |
17 | # S= Active temperature
18 | {% if params.S is defined %}
19 | {% set newparameters = newparameters ~ " ACTV_TMP="~params.S %}
20 | {% endif %}
21 |
22 | KTCC_SET_TOOL_TEMPERATURE{newparameters}
23 |
--------------------------------------------------------------------------------
/config/optional_macros/M106.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M106]
2 | variable_fan_speed: 0
3 | description: Snnn Pnnn
4 | Set fan speed. A KTCC tool must be configured for this to work.
5 | S: Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
6 | P: Tool (optional, defaults to the currently selected tool)
7 | The P parameter specifies tool instead of fan number as in RRF.
8 | gcode:
9 | {% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
10 |
11 | # S= Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
12 | {% if params.S is defined %}
13 | {% set newparameters = newparameters ~ " S="~params.S %}
14 | {% endif %}
15 |
16 | # P= Tool number and optional T.
17 | {% if params.P is defined %}
18 | {% set newparameters = newparameters ~ " P="~params.P %}
19 | {% elif params.T is defined %}
20 | {% set newparameters = newparameters ~ " P="~params.T %}
21 | {% endif %}
22 |
23 | KTCC_SET_AND_SAVE_PARTFAN_SPEED{newparameters}
24 |
--------------------------------------------------------------------------------
/klipper_macros/M106.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M106]
2 | variable_fan_speed: 0
3 | description: Snnn Pnnn
4 | Set fan speed. A KTCC tool must be configured for this to work.
5 | S: Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
6 | P: Tool (optional, defaults to the currently selected tool)
7 | The P parameter specifies tool instead of fan number as in RRF.
8 | gcode:
9 | {% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
10 |
11 | # S= Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
12 | {% if params.S is defined %}
13 | {% set newparameters = newparameters ~ " S="~params.S %}
14 | {% endif %}
15 |
16 | # P= Tool number and optional T.
17 | {% if params.P is defined %}
18 | {% set newparameters = newparameters ~ " P="~params.P %}
19 | {% elif params.T is defined %}
20 | {% set newparameters = newparameters ~ " P="~params.T %}
21 | {% endif %}
22 |
23 | KTCC_SET_AND_SAVE_PARTFAN_SPEED{newparameters}
24 |
--------------------------------------------------------------------------------
/install.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Constants
3 | EXTENSION_NAME="klipper_toolchanger"
4 |
5 | # Force script to exit if an error occurs
6 | set -e
7 |
8 | # Find SRCDIR from the pathname of this script
9 | SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/ && pwd )"
10 |
11 | KLIPPER_PATH="${HOME}/klipper"
12 | # Parse command line arguments to allow KLIPPER_PATH override
13 | while getopts "k:" arg; do
14 | case $arg in
15 | k) KLIPPER_PATH=$OPTARG;;
16 | esac
17 | done
18 |
19 | # Verify conditions for the install to take place
20 | check_preconditions()
21 | {
22 | if [ "$EUID" -eq 0 ]; then
23 | echo "This script must not run as root"
24 | exit -1
25 | fi
26 |
27 | if [ "$(sudo systemctl list-units --full -all -t service --no-legend | grep -F "klipper.service")" ]; then
28 | echo "Klipper service found!"
29 | else
30 | echo "Klipper service not found, please install Klipper first"
31 | exit -1
32 | fi
33 | }
34 |
35 | # Step 2: create a symlinks to the extension files in the klippy/extras directory
36 | link_extension()
37 | {
38 | echo "Linking ${EXTENSION_NAME} to Klippy extras..."
39 | ln -sf ${SRCDIR}/*.py ${KLIPPER_PATH}/klippy/extras/
40 | }
41 |
42 | # Step 3: restarting Klipper
43 | restart_klipper()
44 | {
45 | echo "Restarting Klipper..."
46 | sudo systemctl restart klipper
47 | }
48 |
49 | # Installation steps:
50 | check_preconditions
51 | link_extension
52 | restart_klipper
53 |
--------------------------------------------------------------------------------
/config/optional_macros/M109.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M109]
2 | rename_existing: M109.1
3 | description: T P H S W
4 | Waits for all temperatures, or a specified tool or heater's temperature.
5 | This command can be used without any additional parameters.
6 | Without parameters it waits for bed and current extruder.
7 |
8 | Tnnn Tool number.
9 | Pnnn Alternative to T.
10 | Hnnn Heater number.
11 | Snnn Temperature
12 | Wnnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
13 |
14 | gcode:
15 | {% set newparameters = "" %} # Parameters to be passed to subroutine in new format.
16 |
17 | # H= Heater
18 | {% if params.H is defined %}
19 | {% set newparameters = newparameters ~ " HEATER=" ~ params.H %}
20 | {% endif %}
21 |
22 | # P= Tool number and optional T.
23 | {% if params.P is defined %}
24 | {% set newparameters = newparameters ~ " TOOL=" ~ params.P %}
25 | {% elif params.T is defined %}
26 | {% set newparameters = newparameters ~ " TOOL=" ~ params.T %}
27 | {% endif %}
28 |
29 | # S= Active temperature
30 | {% if params.S is defined and ( params.T is defined or params.P is defined) %}
31 | {% set newTempParameters = newparameters ~ " ACTV_TMP="~params.S ~ " CHNG_STATE=2" %} # Set heater_active_temp to new parameters.
32 | KTCC_SET_TOOL_TEMPERATURE{newTempParameters}
33 | {% endif %}
34 |
35 | {% if params.W is defined %}
36 | {% set newparameters = newparameters ~ " TOLERANCE=" ~ params.W %} # Set Tolerance to new parameters.
37 | {% else %}
38 | {% set newparameters = newparameters ~ " TOLERANCE=1" %} # Set Tolerance to default of 1.
39 | {% endif %}
40 |
41 | KTCC_TEMPERATURE_WAIT_WITH_TOLERANCE{newparameters}
42 |
--------------------------------------------------------------------------------
/klipper_macros/M109.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M109]
2 | rename_existing: M109.1
3 | description: T P H S W
4 | Waits for all temperatures, or a specified tool or heater's temperature.
5 | This command can be used without any additional parameters.
6 | Without parameters it waits for bed and current extruder.
7 |
8 | Tnnn Tool number.
9 | Pnnn Alternative to T.
10 | Hnnn Heater number.
11 | Snnn Temperature
12 | Wnnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
13 |
14 | gcode:
15 | {% set newparameters = "" %} # Parameters to be passed to subroutine in new format.
16 |
17 | # H= Heater
18 | {% if params.H is defined %}
19 | {% set newparameters = newparameters ~ " HEATER=" ~ params.H %}
20 | {% endif %}
21 |
22 | # P= Tool number and optional T.
23 | {% if params.P is defined %}
24 | {% set newparameters = newparameters ~ " TOOL=" ~ params.P %}
25 | {% elif params.T is defined %}
26 | {% set newparameters = newparameters ~ " TOOL=" ~ params.T %}
27 | {% endif %}
28 |
29 | # S= Active temperature
30 | {% if params.S is defined and ( params.T is defined or params.P is defined) %}
31 | {% set newTempParameters = newparameters ~ " ACTV_TMP="~params.S ~ " CHNG_STATE=2" %} # Set heater_active_temp to new parameters.
32 | KTCC_SET_TOOL_TEMPERATURE{newTempParameters}
33 | {% endif %}
34 |
35 | {% if params.W is defined %}
36 | {% set newparameters = newparameters ~ " TOLERANCE=" ~ params.W %} # Set Tolerance to new parameters.
37 | {% else %}
38 | {% set newparameters = newparameters ~ " TOLERANCE=1" %} # Set Tolerance to default of 1.
39 | {% endif %}
40 |
41 | KTCC_TEMPERATURE_WAIT_WITH_TOLERANCE{newparameters}
42 |
--------------------------------------------------------------------------------
/config/optional_macros/M568.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M568]
2 | description: Pnnn Tnnn Rnnn Snnn An Nnnn Mnnn
3 | Set tool temperature.
4 | P= Tool number, optional. If this parameter is not provided, the current tool is used.
5 | T= Alternative to P.
6 | R= Standby temperature(s), optional
7 | S= Active temperature(s), optional
8 | A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature(s).
9 | N = Time in seconds to wait between changing heater state to standby and setting heater target temperature to standby temperature when standby temperature is lower than tool temperature.
10 | Use for example 0.1 to change immediately to standby temperature.
11 | O = Time in seconds to wait from docking tool to shutting off the heater, optional.
12 | Use for example 86400 to wait 24h if you want to disable shutdown timer.
13 | gcode:
14 | # RESPOND MSG="M568: Seting new temperature: {rawparams}"
15 | {% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
16 |
17 | # P= Tool number
18 | {% if params.P is defined %}
19 | {% set newparameters = newparameters ~ " TOOL=" ~ params.P %}
20 | {% elif params.T is defined %}
21 | {% set newparameters = newparameters ~ " TOOL=" ~ params.T %}
22 | {% endif %}
23 |
24 | # R= Standby temperature
25 | {% if params.R is defined %}
26 | {% set newparameters = newparameters ~ " STDB_TMP="~params.R %} # Set heater_standby_temp to new parameters.
27 | {% endif %}
28 |
29 | # S= Active temperature
30 | {% if params.S is defined %}
31 | {% set newparameters = newparameters ~ " ACTV_TMP="~params.S %} # Set heater_active_temp to new parameters.
32 | {% endif %}
33 |
34 | # N = Time in seconds to wait from docking tool to putting the heater in standy
35 | {% if params.N is defined %}
36 | {% set newparameters = newparameters ~ " STDB_TIMEOUT="~params.N %} # Set idle_to_standby_time to new parameters.
37 | {% endif %}
38 |
39 | # M = Time in seconds to wait from docking tool to shuting off the heater
40 | {% if params.O is defined %}
41 | {% set newparameters = newparameters ~ " SHTDWN_TIMEOUT="~params.O %} # Set idle_to_powerdown_time to new parameters.
42 | {% endif %}
43 |
44 | # A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature
45 | {% if params.A is defined %}
46 | {% set newparameters = newparameters ~ " CHNG_STATE="~params.A %} # Set idle_to_powerdown_time to new parameters.
47 | {% endif %}
48 |
49 | # {action_respond_info("M568: Running: KTCC_SET_TOOL_TEMPERATURE"~newparameters)}
50 | KTCC_SET_TOOL_TEMPERATURE{newparameters}
51 |
--------------------------------------------------------------------------------
/klipper_macros/M568.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M568]
2 | description: Pnnn Tnnn Rnnn Snnn An Nnnn Mnnn
3 | Set tool temperature.
4 | P= Tool number, optional. If this parameter is not provided, the current tool is used.
5 | T= Alternative to P.
6 | R= Standby temperature(s), optional
7 | S= Active temperature(s), optional
8 | A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature(s).
9 | N = Time in seconds to wait between changing heater state to standby and setting heater target temperature to standby temperature when standby temperature is lower than tool temperature.
10 | Use for example 0.1 to change immediately to standby temperature.
11 | O = Time in seconds to wait from docking tool to shutting off the heater, optional.
12 | Use for example 86400 to wait 24h if you want to disable shutdown timer.
13 | gcode:
14 | # RESPOND MSG="M568: Seting new temperature: {rawparams}"
15 | {% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
16 |
17 | # P= Tool number
18 | {% if params.P is defined %}
19 | {% set newparameters = newparameters ~ " TOOL=" ~ params.P %}
20 | {% elif params.T is defined %}
21 | {% set newparameters = newparameters ~ " TOOL=" ~ params.T %}
22 | {% endif %}
23 |
24 | # R= Standby temperature
25 | {% if params.R is defined %}
26 | {% set newparameters = newparameters ~ " STDB_TMP="~params.R %} # Set heater_standby_temp to new parameters.
27 | {% endif %}
28 |
29 | # S= Active temperature
30 | {% if params.S is defined %}
31 | {% set newparameters = newparameters ~ " ACTV_TMP="~params.S %} # Set heater_active_temp to new parameters.
32 | {% endif %}
33 |
34 | # N = Time in seconds to wait from docking tool to putting the heater in standy
35 | {% if params.N is defined %}
36 | {% set newparameters = newparameters ~ " STDB_TIMEOUT="~params.N %} # Set idle_to_standby_time to new parameters.
37 | {% endif %}
38 |
39 | # M = Time in seconds to wait from docking tool to shuting off the heater
40 | {% if params.O is defined %}
41 | {% set newparameters = newparameters ~ " SHTDWN_TIMEOUT="~params.O %} # Set idle_to_powerdown_time to new parameters.
42 | {% endif %}
43 |
44 | # A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature
45 | {% if params.A is defined %}
46 | {% set newparameters = newparameters ~ " CHNG_STATE="~params.A %} # Set idle_to_powerdown_time to new parameters.
47 | {% endif %}
48 |
49 | # {action_respond_info("M568: Running: KTCC_SET_TOOL_TEMPERATURE"~newparameters)}
50 | KTCC_SET_TOOL_TEMPERATURE{newparameters}
51 |
--------------------------------------------------------------------------------
/config/SuperSlicer_Custom_Gcode.md:
--------------------------------------------------------------------------------
1 | Here are the custom G-codes I use in SuperSlicer on my ToolChanger as an example.
2 |
3 | Start G-code:
4 | - I don't heat the tools before actually using them so I don't degrade filament.
5 | - Using e3d Revo the heatup times for the tools are verry fast.
6 | ```
7 | KTCC_INIT_PRINT_STATS
8 |
9 | ; Don't heat the tools yet. (Using G10 so SuperSlicer and PrusaSlicer recognizes we set a tool temperature)
10 | G10 P0 R0 S0 A0 ; Don't heat the tools yet. (Using G10 so SuperSlicer and PrusaSlicer recognizes we set a tool temperature)
11 | G10 P1 R0 S0 A0 ; Don't heat the tools yet
12 | G10 P2 R0 S0 A0 ; Don't heat the tools yet
13 | ; Heat the bed first
14 | M140 S[first_layer_bed_temperature]
15 | ; Wait for bed to reach temperature with 2 degrees tolerance
16 | M116 H0 S2 ; Wait for bed to reach temperature with 2 degrees tolerance
17 |
18 | M568 P[initial_extruder] R{filament_toolchange_temp[initial_extruder]} S{first_layer_temperature[initial_extruder]+extruder_temperature_offset[initial_extruder]} A1
19 | G28
20 |
21 | ;Custom Mesh only on print area
22 | BED_MESH_CALIBRATE AREA_START={first_layer_print_min[0]},{first_layer_print_min[1]} AREA_END={first_layer_print_max[0]},{first_layer_print_max[1]}
23 |
24 | G0 Z3 F5000 ; Ensure nozzle is at 3mm over the bed
25 | SAVE_POSITION X={first_layer_print_max[0]} Y={first_layer_print_min[1]}
26 | T[initial_extruder] ; Mount extruder first used (even if only one extruder used). Waits for temperature inside the script.
27 |
28 | ;G0 Z3 F5000 ; Ensure nozzle is at 3mm over the bed
29 | G0 X{first_layer_print_max[0]} Y{first_layer_print_min[1]} Z3 F30000
30 | ```
31 |
32 | End G-code
33 | ```
34 | ; Custom gcode to run at end of print
35 | M104 S0 ; turn off temperature
36 | G10 P0 S0 R0 A0 ; turn off extruder 0
37 | G10 P1 S0 R0 A0 ; turn off extruder 1
38 | G10 P2 S0 R0 A0 ; turn off extruder 2
39 | M140 S0 ; turn off bed
40 | T_1 ; dropoff current tool
41 | G91 ; relative moves
42 | G0 Z20 ; move bed down another 30mm
43 | G90 ; absolute moves
44 | G0 X1 Y1 F30000 ; Move toolhead out of the way
45 | SAVE_POSITION ; Reset saved position.
46 | KTCC_DUMP_PRINT_STATS ; Print statistics to console.
47 | ```
48 |
49 | ToolChange G-code
50 | - Sets the temperature before activating the tool in case this is the first time the tool is selected.
51 | - On first layer it sets the temperature for the next tool to first layer temperature.
52 | ```
53 | {if layer_num < 2}M568 P[next_extruder] R{filament_toolchange_temp[next_extruder]} S{first_layer_temperature[next_extruder]+extruder_temperature_offset[next_extruder]} A2 ;First layer temperature for next extruder
54 | {else}M568 P[next_extruder] R{filament_toolchange_temp[next_extruder]} S{temperature[next_extruder]+extruder_temperature_offset[next_extruder]} A2 ;Other layer temperature for next extruder
55 | {endif}
56 | T{next_extruder}```
57 |
--------------------------------------------------------------------------------
/toolgroup.py:
--------------------------------------------------------------------------------
1 | # KTCC - Klipper Tool Changer Code
2 | # Toolgroup module, used to group Tools and derived from Tool.
3 | #
4 | # Copyright (C) 2023 Andrei Ignat
5 | #
6 | # This file may be distributed under the terms of the GNU GPLv3 license.
7 | #
8 |
9 | # To try to keep terms apart:
10 | # Mount: Tool is selected and loaded for use, be it a physical or a virtual on physical.
11 | # Unmopunt: Tool is unselected and unloaded, be it a physical or a virtual on physical.
12 | # Pickup: Tool is physically picked up and attached to the toolchanger head.
13 | # Droppoff: Tool is physically parked and dropped of the toolchanger head.
14 | # ToolLock: Toollock is engaged.
15 | # ToolUnLock: Toollock is disengaged.
16 |
17 |
18 | class ToolGroup:
19 | def __init__(self, config):
20 | self.printer = config.get_printer()
21 | self.name = config.get_name().split(' ')[1]
22 | self.config = config
23 | # gcode_macro = self.printer.load_object(config, 'gcode_macro')
24 |
25 | try:
26 | _, name = config.get_name().split(' ', 1)
27 | self.name = int(name)
28 | except ValueError:
29 | raise config.error(
30 | "Name of section '%s' contains illegal characters. Use only integer ToolGroup number."
31 | % (config.get_name()))
32 |
33 | self.is_virtual = config.getboolean( # If True then must have a physical_parent declared and shares extruder, hotend and fan with the physical_parent
34 | 'is_virtual', False)
35 | self.physical_parent_id = config.getint( # Tool used as a Physical parent for all toos of this group. Only used if the tool i virtual.
36 | 'physical_parent', None)
37 | self.lazy_home_when_parking = config.get('lazy_home_when_parking', 0) # (default: 0) - When set to 1, will home unhomed XY axes if needed and will not move any axis if already homed and parked. 2 Will also home Z if not homed.
38 | # -1 = none, 1= Only load filament, 2= Wipe in front of carriage, 3= Pebble wiper, 4= First Silicone, then pebble. Defaults to 0.
39 | self.pickup_gcode = config.get('pickup_gcode', '')
40 | self.dropoff_gcode = config.get('dropoff_gcode', '')
41 | self.virtual_toolload_gcode = config.get('virtual_toolload_gcode', '')
42 | self.virtual_toolunload_gcode = config.get('virtual_toolunload_gcode', '')
43 | self.meltzonelength = config.get('meltzonelength', 0)
44 | self.idle_to_standby_time = config.getfloat( 'idle_to_standby_time', 30, minval = 0.1)
45 | self.idle_to_powerdown_time = config.getfloat( 'idle_to_powerdown_time', 600, minval = 0.1)
46 |
47 | self.requires_pickup_for_virtual_load = self.config.getboolean("requires_pickup_for_virtual_load", True)
48 | self.requires_pickup_for_virtual_unload = self.config.getboolean("requires_pickup_for_virtual_unload", True)
49 | self.unload_virtual_at_dropoff = self.config.getboolean("unload_virtual_at_dropoff", True)
50 |
51 |
52 | def get_config(self, config_param, default = None):
53 | return self.config.get(config_param, default)
54 |
55 | def get_status(self, eventtime= None):
56 | status = {
57 | "is_virtual": self.is_virtual,
58 | "physical_parent_id": self.physical_parent_id,
59 | "lazy_home_when_parking": self.lazy_home_when_parking,
60 | "meltzonelength": self.meltzonelength,
61 | "idle_to_standby_time": self.idle_to_standby_time,
62 | "idle_to_powerdown_time": self.idle_to_powerdown_time,
63 | "requires_pickup_for_virtual_load": self.requires_pickup_for_virtual_load,
64 | "requires_pickup_for_virtual_unload": self.requires_pickup_for_virtual_unload,
65 | "unload_virtual_at_dropoff": self.unload_virtual_at_dropoff
66 | }
67 | return status
68 |
69 | def load_config_prefix(config):
70 | return ToolGroup(config)
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/config/optional_macros/readme.md:
--------------------------------------------------------------------------------
1 | # Required and Optional G-code macros
2 |
3 | The required macros change how Klipper uses those commands to make use of the toolchanger. They are all backwards compatible. This macros are highly recommended to be included.
4 |
5 | The optional macros are to add more commands for higher compatibility with for example RRF G-code.
6 |
7 | > [!NOTE]
8 | > You can add the whole directory to the printer.cfg by adding the relative path to the macros directory for example:
9 |
10 | ```
11 | [include toolchanger/g-code_macros/*.cfg]
12 | ```
13 |
14 |
15 |
16 | ##    Required macros
17 |
18 | | Command | Description | Parameters |
19 | | ------- | ----------- | ---------- |
20 | | `M104` | Set tool temperature. If Tool number is not provided, current tool is used. If no S parameter is provided it will dump current temperature settings for the tool.| `P[0..n]` Tool number, optional
`T[0..n]` Alternative to P.
`S...` Active temperature to set. |
21 | | `M106` | Set fan speed. If Tool number is not provided, current tool is used. If no S parameter is provided, set full fan speed. | `P[0..n]` Tool number, optional
`T[0..n]` Alternative to P.
`S[0-1]` or `S[2-255]` Fan speed 0-1 or 2-255 |
22 | | `M107` | Turn off fan. If Tool number is not provided, current tool is used| `P[0..n]` Tool number, optional
`T[0..n]` Alternative to P |
23 | | `M109` | Waits temperature with a tolerance defaulting to +//1. Optional temperature can be defined when tool is defined, setting the tool as active with specified temperature. If heater is defined it will wait for that heater. Optional tolerance can be specified. Only waits if target temperature is >40*C | `H[0..n]` Heater number, optional
`T[0..n]` Tool number
`P[0..n]` Alternative to T
`W[-50]` Tolerance in degC |
24 |
25 |
26 |
27 | ##    Optional macros
28 |
29 | | Command | Description | Parameters |
30 | | ------- | ----------- | ---------- |
31 | | `G10` | Alias to M568 | |
32 | | `M116` | Alias to M109 | |
33 | | `M568` |Set tool temperature. If Tool number is not provided, current tool is used | `P[0..n]` Tool number, optional
`T[0..n]` Alternative to P.
`S...` Set active temperature, optional
`R...` Set standby temperature, optional
`A...` Set Heater state, optional
(0= off), (1 = standby temperature), (2 = active temperature)
`N...` Standby timeout is the time to linger at Active temp. after setting the heater to standby. Could be used for a tool with long heatup times and is only put in standby short periods of thme throughout a print and should stay at active temperature longer time.
`O...` Timer from Standby to off. Used for example so a tool used only on first few layers shuts down after 30 minutes of inactivity and won't stay at 175*C standby for the rest of a 72h print. |
34 | | `M204` | Set acceleration to either S or lowest of supplied P and T. | `S...` Acceleration, optional
`P...` Print acceleration, RRF compatible
`T...` Travel acceleration, RRF compatible |
35 | | `M566` | Set Square Corner Velocity in RRF style. Only the lower of required X or Y will be used| `X...` X axis
`Y...` Y axis |
36 |
--------------------------------------------------------------------------------
/klipper_macros/readme.md:
--------------------------------------------------------------------------------
1 | # Required and Optional G-code macros
2 |
3 | The required macros change how Klipper uses those commands to make use of the toolchanger. They are all backwards compatible. This macros are highly recommended to be included.
4 |
5 | The optional macros are to add more commands for higher compatibility with for example RRF G-code.
6 |
7 | > [!NOTE]
8 | > You can add the whole directory to the printer.cfg by adding the relative path to the macros directory for example:
9 |
10 | ```
11 | [include toolchanger/g-code_macros/*.cfg]
12 | ```
13 |
14 |
15 |
16 | ##    Required macros
17 |
18 | | Command | Description | Parameters |
19 | | ------- | ----------- | ---------- |
20 | | `M104` | Set tool temperature. If Tool number is not provided, current tool is used. If no S parameter is provided it will dump current temperature settings for the tool.| `P[0..n]` Tool number, optional
`T[0..n]` Alternative to P.
`S...` Active temperature to set. |
21 | | `M106` | Set fan speed. If Tool number is not provided, current tool is used. If no S parameter is provided, set full fan speed. | `P[0..n]` Tool number, optional
`T[0..n]` Alternative to P.
`S[0-1]` or `S[2-255]` Fan speed 0-1 or 2-255 |
22 | | `M107` | Turn off fan. If Tool number is not provided, current tool is used| `P[0..n]` Tool number, optional
`T[0..n]` Alternative to P |
23 | | `M109` | Waits temperature with a tolerance defaulting to +//1. Optional temperature can be defined when tool is defined, setting the tool as active with specified temperature. If heater is defined it will wait for that heater. Optional tolerance can be specified. Only waits if target temperature is >40*C | `H[0..n]` Heater number, optional
`T[0..n]` Tool number
`P[0..n]` Alternative to T
`W[-50]` Tolerance in degC |
24 |
25 |
26 |
27 | ##    Optional macros
28 |
29 | | Command | Description | Parameters |
30 | | ------- | ----------- | ---------- |
31 | | `G10` | Alias to M568 | |
32 | | `M116` | Alias to M109 | |
33 | | `M568` |Set tool temperature. If Tool number is not provided, current tool is used | `P[0..n]` Tool number, optional
`T[0..n]` Alternative to P.
`S...` Set active temperature, optional
`R...` Set standby temperature, optional
`A...` Set Heater state, optional
(0= off), (1 = standby temperature), (2 = active temperature)
`N...` Standby timeout is the time to linger at Active temp. after setting the heater to standby. Could be used for a tool with long heatup times and is only put in standby short periods of thme throughout a print and should stay at active temperature longer time.
`O...` Timer from Standby to off. Used for example so a tool used only on first few layers shuts down after 30 minutes of inactivity and won't stay at 175*C standby for the rest of a 72h print. |
34 | | `M204` | Set acceleration to either S or lowest of supplied P and T. | `S...` Acceleration, optional
`P...` Print acceleration, RRF compatible
`T...` Travel acceleration, RRF compatible |
35 | | `M566` | Set Square Corner Velocity in RRF style. Only the lower of required X or Y will be used| `X...` X axis
`Y...` Y axis |
36 |
--------------------------------------------------------------------------------
/config/example_simple/tools.cfg:
--------------------------------------------------------------------------------
1 | # Simple sample configuration for getting started with a ToolChanger with 2 tools.
2 |
3 |
4 | # Enables saving of variables between powerdown of machine. Must be configured before [toollock].
5 | [save_variables]
6 | filename: ~/variables.cfg
7 |
8 | [ktcclog] # Log_level & logfile_level can be set to one of (0 = essential, 1 = info, 2 = debug, 3 = trace)
9 | log_level: 2
10 | logfile_level: 3
11 |
12 | [toollock]
13 | tool_lock_gcode:
14 | MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=0 # Set assumed possition as rotated to min
15 | MANUAL_STEPPER STEPPER=tool_lock Move=1 SPEED=30 STOP_ON_ENDSTOP=-1 SYNC=1 # Move until no longer endstop is triggered, max 1degree. If Endstop is not untriggered then raise an error. Wait for the movement before continuing.
16 | MANUAL_STEPPER STEPPER=tool_lock Move=150 SPEED=50 STOP_ON_ENDSTOP=1 SYNC=1 # Move to max and stop on endstop. If Endstop is not triggered then raise an error. Wait for the movement before continuing.
17 | tool_unlock_gcode:
18 | MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=180 # Set assumed possition as rotated to max
19 | MANUAL_STEPPER STEPPER=tool_lock Move=179 SPEED=30 STOP_ON_ENDSTOP=-1 SYNC=1 # Move until no longer endstop is triggered, max 1degree. If Endstop is not untriggered then raise an error. Wait for the movement before continuing.
20 | MANUAL_STEPPER STEPPER=tool_lock Move=0 SPEED=100 STOP_ON_ENDSTOP=1 SYNC=1 # Move to min and stop on endstop. If Endstop is not triggered then raise an error. Wait for the movement before continuing.
21 | MANUAL_STEPPER STEPPER=tool_lock ENABLE=0 # Turn off the stepper while unlocked so it can rest without triggering the endswitch
22 |
23 | [toolgroup 0]
24 | pickup_gcode:
25 | M568 P{myself.name} A2 # Put tool heater in Active mode
26 |
27 | SAVE_GCODE_STATE NAME=TOOL_PICKUP # Save GCODE state. Will be restored at the end of pickup code
28 | G90
29 |
30 | ############## Move in to zone ##############
31 | G0 X500 F40000 # Fast move X inside the safezone, so we don't crash into other tools.
32 | G0 Y{myself.zone[1]} F40000 # Fast move Y in front of parking spot.
33 |
34 | ############## Move in to parking spot ##############
35 | G0 X{myself.park[0]|float - 15} F40000 # Fast Move near the pickup position for tool.
36 | G0 X{myself.park[0]} F3000 # Slow Move to the pickup position for tool.
37 |
38 | ############## Lock Tool ##############
39 | M400 # Wait for all moves to finish.
40 | TOOL_LOCK # Lock the tool.
41 | SET_GCODE_OFFSET Z={myself.offset[2]} MOVE=1 # Set and move the Z offset. Avoid crashing into bed when moving out later.
42 |
43 | ############## Wait for heater ##############
44 | {% if myself.extruder|default("none")|lower !="none" %} # If the tool has an extruder:
45 | TEMPERATURE_WAIT_WITH_TOLERANCE TOOL={myself.name} # Wait for tool to reach target temperature.
46 | {% endif %} # /
47 |
48 | ############## Move out to zone ##############
49 | G0 X{myself.zone[0]} F6000 # Slow Move to the zone position for tool.
50 |
51 | ############## Move out to Safe position ##############
52 | G0 X500 F40000 # Fast Move to the safe position for tools.
53 |
54 | ############## Finnish up ##############
55 | M400 # Wait for current moves to finish.
56 | RESTORE_GCODE_STATE NAME=TOOL_PICKUP MOVE=0 # Restore GCODE state. Was saved at thebegining of SUB_TOOL_PICKUP_START. Move fast to last location.
57 | # Set the toolhead offsets. Z is set and moved before any moves in SUB_TOOL_PICKUP_START. Needs to be after any RESTORE_GCODE_STATE!
58 | SET_GCODE_OFFSET X={myself.offset[0]|float + ktcc.global_offset[0]|float } Y={myself.offset[1]|float + ktcc.global_offset[1]|float } Z={myself.offset[2]|float + ktcc.global_offset[2]|float } MOVE=0
59 | dropoff_gcode:
60 | SUB_TOOL_DROPOFF T={myself.name}
61 |
62 | [tool 0]
63 | tool_group: 0
64 | extruder: extruder
65 | fan: partfan_t0
66 | zone: 550,5
67 | park: 598,5
68 | offset: 11.278,3.766,3.528
69 | meltzonelength: 18
70 |
71 | [tool 1]
72 | tool_group: 0
73 | extruder: extruder1
74 | fan: partfan_t1
75 | zone: 550,100
76 | park: 598,100
77 | offset: -1.447,-0.295,-1.503
78 | meltzonelength: 18
79 |
80 | [gcode_macro SUB_TOOL_DROPOFF]
81 | description: Internal subroutine. Do not use!
82 | # Tnnn: Tool to pickup
83 | gcode:
84 | {%set myself = printer['tool '~params.T]%}
85 |
86 | SET_GCODE_OFFSET X=0 Y=0 # Set XY offset to 0 so we park the tool right.
87 | SAVE_GCODE_STATE NAME=TOOL_DROPOFF_002 # Save GCode state.
88 | G90 # Absolute positions
89 |
90 | # Fast Move to the general pickup position for tools.
91 | G0 X500 F40000 # Move X and lift z so we don't crash the bed or into other tools.
92 | G0 Y{myself.zone[1]} F40000 # Move Y after X and Z
93 | M400 # Wait for current moves to finish
94 |
95 | G0 X{myself.zone[0]} F40000 # Fast Move near the dropoff position for tool.
96 | G0 X{myself.park[0]} F3000 # Slow Move to the dropoff position for tool.
97 |
98 | M400 # Wait for current moves to finish
99 | TOOL_UNLOCK # Unlock the tool
100 |
101 | G0 X{myself.park[0]|float - 15} F6000 # Slow Move to the pickup position for tool.
102 | G0 X500 F40000 # Fast Move to the general pickup position for tools.
103 |
104 | RESTORE_GCODE_STATE NAME=TOOL_DROPOFF_002 MOVE=0 # Restore Gcode state
105 | SET_GCODE_OFFSET Z=0 # Set Z offset to 0 after too is parked.
106 |
--------------------------------------------------------------------------------
/config/example_complex/tool_macro.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro TOOL_LOCK_CHECK]
2 | description: Check so the tool is mounted by slightly advancing the lock again until hit endstop, only if endstop not already hit. Do not wait for it to finish.
3 | gcode:
4 | # If endstop is not triggered then try to lock again for safety. Best to check the endstops before calling this.
5 | {% if printer.query_endstops.last_query['manual_stepper tool_lock']|default(0) == 0 %}
6 | SET_TMC_CURRENT STEPPER=tool_lock CURRENT=1.0
7 | MANUAL_STEPPER STEPPER=tool_lock Move=20 SPEED=50 STOP_ON_ENDSTOP=1 SYNC=0
8 | SET_TMC_CURRENT STEPPER=tool_lock CURRENT=0.8
9 | {% endif %}
10 |
11 |
12 | [gcode_macro M106]
13 | variable_fan_speed: 0
14 | description: Snnn Pnnn
15 | Set fan speed. A tool and toollock must be configured for this to work.
16 | S: Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
17 | P: Tool (optional, defaults to the currently selected tool)
18 | The P parameter specifies tool instead of fan number as in RRF.
19 | gcode:
20 | {% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
21 |
22 | # S= Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
23 | {% if params.S is defined %}
24 | {% set newparameters = newparameters ~ " S="~params.S %} # Set heater_standby_temp to new parameters.
25 | {% endif %}
26 |
27 | # P= Tool number
28 | {% if params.P is defined %}
29 | {% set newparameters = newparameters ~ " P="~params.P %} # Set heater_standby_temp to new parameters.
30 | {% endif %}
31 |
32 | SET_AND_SAVE_FAN_SPEED{newparameters}
33 |
34 | [gcode_macro M107]
35 | description: Pnnn
36 | Turn off fan.
37 | P = Tool (optional and defaults to the currently selected tool)
38 | gcode:
39 | {% if params.P is defined %}
40 | {% set p = " P"~params.P %}
41 | {% endif %}
42 | M106 {p|default("")} S0
43 |
44 | [gcode_macro G10]
45 | description: See M568. Passtrough to M568.
46 | gcode:
47 | M568 {rawparams}
48 |
49 |
50 |
51 | [gcode_macro M568]
52 | description: Pnnn Rnnn Snnn An Nnnn Mnnn
53 | Set tool temperature.
54 | P= Tool number, optional. If this parameter is not provided, the current tool is used.
55 | R= Standby temperature(s), optional
56 | S= Active temperature(s), optional
57 | A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature(s).
58 | N = Time in seconds to wait between changing heater state to standby and setting heater target temperature to standby temperature when standby temperature is lower than tool temperature.
59 | Use for example 0.1 to change immediately to standby temperature.
60 | O = Time in seconds to wait from docking tool to shutting off the heater, optional.
61 | Use for example 86400 to wait 24h if you want to disable shutdown timer.
62 | gcode:
63 | # RESPOND MSG="M568: Seting new temperature: {rawparams}"
64 | {% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
65 |
66 | # P= Tool number
67 | {% if params.P is defined %}
68 | {% set newparameters = newparameters ~ " TOOL="~params.P %} # Set heater_standby_temp to new parameters.
69 | {% endif %}
70 |
71 | # R= Standby temperature
72 | {% if params.R is defined %}
73 | {% set newparameters = newparameters ~ " STDB_TMP="~params.R %} # Set heater_standby_temp to new parameters.
74 | {% endif %}
75 |
76 | # S= Active temperature
77 | {% if params.S is defined %}
78 | {% set newparameters = newparameters ~ " ACTV_TMP="~params.S %} # Set heater_active_temp to new parameters.
79 | {% endif %}
80 |
81 | # N = Time in seconds to wait from docking tool to putting the heater in standy
82 | {% if params.N is defined %}
83 | {% set newparameters = newparameters ~ " STDB_TIMEOUT="~params.N %} # Set idle_to_standby_time to new parameters.
84 | {% endif %}
85 |
86 | # M = Time in seconds to wait from docking tool to shuting off the heater
87 | {% if params.O is defined %}
88 | {% set newparameters = newparameters ~ " SHTDWN_TIMEOUT="~params.O %} # Set idle_to_powerdown_time to new parameters.
89 | {% endif %}
90 |
91 | # A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature
92 | {% if params.A is defined %}
93 | {% set newparameters = newparameters ~ " CHNG_STATE="~params.A %} # Set idle_to_powerdown_time to new parameters.
94 | {% endif %}
95 |
96 | {action_respond_info("M568: Running: SET_TOOL_TEMPERATURE"~newparameters)}
97 | SET_TOOL_TEMPERATURE{newparameters}
98 |
99 | [gcode_macro M116]
100 | description: Pnnn Hnnn Snnn
101 | Waits for all temperatures, or a specified tool or heater's temperature.
102 | This command can be used without any additional parameters.
103 | Without parameters it waits for bed and current extruder.
104 | Only one of either P or H may be used.
105 |
106 | Pnnn Tool number.
107 | Hnnn Heater number. 0="heater_bed", 1="extruder", 2="extruder1", etc.
108 | Snnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
109 |
110 | gcode:
111 | {% set newparameters = "" %} # Parameters to be passed to subroutine in new format.
112 |
113 |
114 | {% if params.P is defined %}
115 | {% set newparameters = newparameters ~ " TOOL=" ~ params.P %} # Set Tool to new parameters.
116 | {% endif %}
117 |
118 | {% if params.H is defined %}
119 | {% set newparameters = newparameters ~ " HEATER=" ~ params.H %} # Set Tool to new parameters.
120 | {% endif %}
121 |
122 | {% if params.S is defined %}
123 | {% set newparameters = newparameters ~ " TOLERANCE=" ~ params.S %} # Set Tool to new parameters.
124 | {% endif %}
125 |
126 | TEMPERATURE_WAIT_WITH_TOLERANCE{newparameters}
127 |
128 |
129 | [gcode_macro TOOL_DROPOFF]
130 | gcode:
131 | KTCC_TOOL_DROPOFF_ALL
132 |
133 | [gcode_macro SAVE_ACCELERATION]
134 | variable_max_accel: 0
135 | gcode:
136 | SET_GCODE_VARIABLE MACRO=SAVE_ACCELERATION VARIABLE=max_accel VALUE={printer.toolhead.max_accel}
137 |
138 | [gcode_macro RESTORE_ACCELERATION]
139 | gcode:
140 | {% if printer['gcode_macro SAVE_ACCELERATION'].max_accel|int == 0 %}
141 | { action_respond_info("RESTORE_ACCELERATION: No acceleration saved.") }
142 | {% else %}
143 | M204 S{printer['gcode_macro SAVE_ACCELERATION'].max_accel}
144 | {% endif %}
145 |
--------------------------------------------------------------------------------
/config/readme.md:
--------------------------------------------------------------------------------
1 | # Configuration reference
2 | This document is a reference for options available in the Klipper config file when adding the Tools module.
3 |
4 | ## Configuration examples
5 | Can be found in the different subdirectories.
6 | Feel free to add some for reference or send them my way and I will format, comment and add them.
7 | -
8 |
9 | ## Configuration order
10 |
11 | ToolGroups must come before tools that use them.
12 | A Tool that is used as physical_parent must be configured before other virtual tools that use it as a parent.
13 |
14 | ## Configuration requirements
15 |
16 | * `[save_variables]` must be used as described in the Klipper documentation.
17 | * `[input_shaper]` needs to be used for input shaper to work.
18 |
19 | ### [toollock]
20 |
21 | Configures the Locking mechanism and other common configuration for the Tools module.
22 |
23 | ```
24 | #purge_on_toolchange: True
25 | # Here we can disable all purging. When disabled it overrides all other purge options.
26 | # This can be turned off by a macro for automatic probing hot tools without probing them.
27 | # For example when doing TAMV or ZTATP. The default is True.
28 | #global_offset: 0,0,0
29 | # Optional offset that can be accesed in macros and added to all tools. Can be usefull for diailing in the first layer.
30 | #init_printer_to_last_tool: True
31 | # Initialise as it was turned off, unlock tool if none was loaded or lock if one was
32 | # loaded. Defaults to True
33 | tool_lock_gcode:
34 | # A list of G-Code commands to execute when the tool is locked
35 | # in place by the TOOL_LOCK command. This parameter must
36 | # be provided. This can also call a macro.
37 | tool_unlock_gcode:
38 | # A list of G-Code commands to execute when the tool is unlocked
39 | # in place by the TOOL_UNLOCK command. This parameter must
40 | # be provided. This can also call a macro.
41 | ```
42 |
43 | ### [toolgroup]
44 |
45 | Can be used for grouping settings common to multiple tools.
46 | At least one (the 0) must be specified and can be empty.
47 |
48 | ```
49 | [toolgroup 0]
50 | #is_virtual: True
51 | # If True then must have a physical_parent declared and shares extruder, hotend and
52 | # fan with the physical_parent
53 | #physical_parent: 0
54 | # Tool used as a Physical parent for all toos of this group. Only used if the tool i virtual.
55 | #lazy_home_when_parking: 0
56 | # If the printer is able to home with the tool mounted.
57 | # When set to 1, will home unhomed XY axes if needed and will not move any axis
58 | # if already homed and parked. 2 Will also home Z if not homed.
59 | #meltzonelength:0
60 | #idle_to_standby_time: 30
61 | #idle_to_powerdown_time: 600
62 | #pickup_gcode
63 | #dropoff_gcode
64 | ```
65 |
66 | ### [tool]
67 |
68 | A tool can be a physical tool on a toolchanger, being picked up and dropped of, or it can be
69 | virtual on a tool. A virtual tool can be a ERCF, a roatating wheel, etc.
70 |
71 | A virtual tool is a second layer of toolchanging. For example if using a physical e3d Revo
72 | with a Bondtech LGX Lite and two fans connected to a 9 port ERCF filament changer.
73 | Then the [Tool 0] to [Tool 9] would have 0 as parent and all be virtual. When changing
74 | from T0 to T2, then only the ERCF script would run. But if changing from T11 to T2,
75 | then first a toolchange and then a ERCF filament change would occur.
76 |
77 | A tool does not have to have a heater, extruder or fan. It can be a simple pen.
78 |
79 | The only mandatory setting is "tool_group".
80 |
81 | A virtual tool can inherit all and any configuration from the parent tool except for
82 | "is_virtual" and "physical_parent". Both can be defined in a group, so basicly only
83 | the group needs to be specified for a group of tools
84 |
85 | ```
86 | [tool 0]
87 | tool_group:
88 | # The Toolgroup number for this tool
89 | # Must be used and configured before thr tool using it.
90 | #is_virtual: False
91 | # Defines this tool as physical or virtual.
92 | #physical_parent:
93 | # Nr of the physical parent of this tool. Defaults not having one.
94 | #extruder:
95 | # Name of extruder connected to this tool. For example "extruder"
96 | # or "extruder1" without the quotation marks. Defaults to having no extruder.
97 | #fan:
98 | # Name of general fan configuration used as a partcooling fan.
99 | # For example "partfan_t0". Defaults to having no extruder.
100 | #zone:
101 | # Coordinates to when the toolhead is near the tool, used for fas aproach.
102 | # For example "550,5". This would be X550 Y5 in the printer coordinates.
103 | park:
104 | # Coordinates to when the tool is parked, aproach slowly from zone coordinates.
105 | # For example "598,5". This would be X598 Y5 in the printer coordinates.
106 | #offset:
107 | # Offset of the tip of the tool to the coordinates of the head in X,Y,Z
108 | # For example "11.278,3.766,3.528". Defaults to "0,0,0"
109 | #idle_to_standby_time: 0.1
110 | # Time in seconds from the tool being parked to setting temperature to standby
111 | # if the temperature current temperature is above the standby temperature.
112 | # Use 0.1 to change imediatley to standby temperature. Defaults to 0.1
113 | # If you use 0, then it disables the standby temperature.
114 | #idle_to_powerdown_time: 600
115 | # Time in seconds from being parked to turning off the heater, setting temperature to 0.
116 | # Use something like 86400 to wait 24h if you want to disable. Defaults to 600 (10 minutes).
117 | #lazy_home_when_parking: 0
118 | # If the printer is able to home with the tool mounted.
119 | # When set to 1, will home unhomed XY axes if needed and will not move any axis
120 | # if already homed and parked. 2 Will also home Z if not homed.
121 | #meltzonelength: 0
122 | # Length of the meltzone for retracting and inserting filament on toolchange. 18mm for e3d Revo.
123 | #shaper_freq_x: 0
124 | #shaper_freq_y: 0
125 | # Shaper frequency for this tool. For example "116.4". Defaults to "0".. See Klipper documentation for more details.
126 | # shaper_type_x: "mzv"
127 | # shaper_type_y: "mzv"
128 | # Shaper type for this tool. Defaults to "mzv". See Klipper documentation for more details.
129 | #shaper_damping_ratio_x: 0
130 | #shaper_damping_ratio_x: 0
131 | # Damping ratios of vibrations of X and Y axes used by input shaper.
132 | # Defaults to "0.1". See Klipper documentation for more details.
133 | #pickup_gcode:
134 | # A list of G-Code commands to execute when the tool is locked
135 | # in place by the TOOL_LOCK command. This can also call a macro.
136 | #dropoff_gcode:
137 | # A list of G-Code commands to execute when the tool is unlocked
138 | # in place by the TOOL_UNLOCK command. This can also call a macro.
139 | ```
140 |
141 | Not used yet:
142 | ```
143 | #HeatMultiplyerAtFullFanSpeed = 1
144 | # Multiplier to be aplied to hotend temperature when fan is at maximum.
145 | # Will be multiplied with fan speed. Ex. 1.1 at 205*C and fan speed of 40% will set temperature to 213*C
146 | ```
147 |
--------------------------------------------------------------------------------
/doc/command_ref.md:
--------------------------------------------------------------------------------
1 | # KTCC - Command Reference
2 |
3 | ##    Basic Toolchanger functionality
4 |
5 | | Command | Description | Parameters |
6 | | ------- | ----------- | ---------- |
7 | | `TOOL_LOCK` | Lock the tool to the toolhead. | |
8 | | `TOOL_UNLOCK` | Unlock the toolhead from tool. | |
9 | | `Tn` | Activates heater, pick up and readyy the tool. If tool is mapped to another one then that tool will be selected instead. | `RESTORE_AXIS=[XYZ]` Restore specified axis position to the latest saved. |
10 | | `TOOL_DROPOFF_ALL` | Unloads and parks the current tool without picking up another tool, leaving the toolhead free and unlocked. Actual active extruder eill still be last used one as Klipper needs an active extruder. | |
11 | | `SET_TOOL_TEMPERATURE` | Set tool temperature. If `TOOL` parameter is omited then current tool is set. | `TOOL=[0..n]` Optional if other than current loaded tool
`ACTV_TMP=...` Set Active temperature, optional
`STDB_TMP =...` Standby temperature, optional
`CHNG_STATE=[0\|1\|2]` Change Heater State, optional:
(0 = Off) \| (1 = Standby) \| (2 = Active)
`SHTDWN_TIMEOUT=...` Time in seconds to wait with the heater in standby before changing it to off, optional.
`STDB_TIMEOUT=...` Time in seconds to linger at Active temp. after setting the heater to standby when the standby temperature is lower than current tool temperature, optional.
`SHTDWN_TIMEOUT` is used for example so a tool used only on first few layers shuts down after 30 minutes of inactivity and won't stay at 175*C standby for the rest of a 72h print.
`STDB_TIMEOUT=` Time to linger at Active temp. after setting the heater to standby. Could be used for a tool with long heatup times and is only put in standby short periods of thme throughout a print and should stay at active temperature longer time. |
12 | | `SET_AND_SAVE_PARTFAN_SPEED` | Set the partcooling fan speed current or specified tool. Fan speed is carried over between toolchanges. | `S=[0-255 \| 0-1]` Fan speed with either a maximum of 255 or 1.
`P=[0-n]` Tool number if not current tool to set fan to. |
13 | | `TEMPERATURE_WAIT_WITH_TOLERANCE` | Waits for all temperatures, or a specified tool or heater's temperature. This command can be used without any additional parameters and then waits for bed and current extruder. Only one of either TOOL or HEATER may be used. Only waits if target temperature is >40*C | `TOOL=[0-n]` Tool number to wait for, optional.
`HEATER=[0-n]` Heater number. 0="heater_bed", 1="extruder", 2="extruder1", 3="extruder2", etc. Only works if named as default, this way, optional.
`TOLERANCE=[0-50]` Tolerance in degC. Defaults to 1*C. Wait will wait until heater is in range of set temperature +/- tolerance. |
14 |
15 |
16 | ##    Offset commands
17 | | Command | Description | Parameters   |
18 | | ------- | ----------- | ---------- |
19 | | `SET_GLOBAL_OFFSET` | Set a global offset that can be applied to all tools. Can use absolute offset or adjust relative to current offset. | `X=...` Set the new offset for the axis.
`Y=...` As above.
`Z=...` As above.
----------
`X_ADJUST=...` Adjust the offset position incramentally.
`Y_ADJUST=...` As above.
`Z_ADJUST=...` As above.
|
20 | | `SET_TOOL_OFFSET` | Set the offset of an individual tool. Can use absolute offset or adjust relative to current offset. | `TOOL=[0-n]` Tool number, optional. If not provided, the current tool is used.
----------
`X=...` Set the new offset for the axis.
`Y=...` As above.
`Z=...` As above.
----------
`X_ADJUST=...` Adjust the offset position incramentally.
`Y_ADJUST=...` As above.
`Z_ADJUST=...` As above.
|
21 | | `KTCC_SET_GCODE_OFFSET_FOR_CURRENT_TOOL` | Sets the Klipper G-Code offset to the one for the current tool. | `MOVE=[0\|1]` Wheteher to move the toolhead to the new offset. ( 0 = Do not move, default ) ( 1 = Move )
|
22 |
23 |
24 | ##    Position saving and restoring commands
25 | | Command | Description | Parameters   |
26 | | ------- | ----------- | ---------- |
27 | | `SAVE_POSITION` | Save the specified G-Code position for later restore. Without parameters it will set to not restoring axis. | `X=...` Set the restore position and set this axis to be restored.
`Y=...` As above.
`Z=...` As above. |
28 | | `SAVE_CURRENT_POSITION` | Save the current G-Code position for later restore. Without parameters it will save previousley saved axis. | `RESTORE_POSITION_TYPE=[XYZ] or [0\|1\|2]` Axis to save or tyoe ( 0 = No restore ), ( 1 = Restore XY ), ( 2 = Restore XYZ ) |
29 | | `RESTORE_POSITION` | Restore a previously saved G-Code position. With no parameters it will Restore to previousley saved type. | `RESTORE_POSITION_TYPE=[XYZ] or [0\|1\|2]` Axis to save or tyoe ( 0 = No restore ), ( 1 = Restore XY ), ( 2 = Restore XYZ ) |
30 |
31 |
32 | ##    Tool remapping commands
33 | | Command | Description | Parameters |
34 | | ------- | ----------- | ---------- |
35 | | `KTCC_DISPLAY_TOOL_MAP` | Dump the current mapping of tools to other KTCC tools. | |
36 | | `KTCC_REMAP_TOOL` | Remap a tool to another one. | `RESET=[0\|1]` If 1 the stored tooö remap will be reset.
`TOOL=[0-n]` The toolnumber to remap.
`SET=[0-n]` The toolnumber to remap to. |
37 |
38 |
39 | ##    Advanced commands, rarely used
40 | | Command | Description | Parameters |
41 | | ------- | ----------- | ---------- |
42 | | `KTCC_SAVE_CURRENT_TOOL` | Set the current loaded tool manually to the specified. When loading a tool manually | `T=[-2-n]` Tool to set as current. ( -2 = Unknown tool ), ( -1 = Toollock unlocked without tool ) |
43 | | `KTCC_SET_PURGE_ON_TOOLCHANGE` | Sets a global variable that can disable all purging (can be used in macros) when loading/unloading tools. For example for automated tool alignement such as TAMV/ZTATP. | `VALUE=[0\|1]` If enabled or disabled. |
44 | | `KTCC_ENDSTOP_QUERY` | Wait for a ENDSTOP untill it is in the specified state indefinitly or for maximum atempts if specified. Checking state once a second. | `ENDSTOP=...` Name of the endstop to wait for.
`TRIGGERED=[0\|1]` If should be waiting for it to be triggered (1) or open (0).
`ATEMPTS=...` Number of atempts to make, indefinitly if not specified. |
45 | | `KTCC_SET_ALL_TOOL_HEATERS_OFF` | Turns off all heaters configured for tools and saves changes made to be resumed later by KTCC_RESUME_ALL_TOOL_HEATERS. This does not affect heated beds or other heaters not defined as aan extruder in tools. | |
46 | | `KTCC_RESUME_ALL_TOOL_HEATERS` | Resumes all heaters previously turned off by KTCC_SET_ALL_TOOL_HEATERS_OFF. | `MSG=...` The message to be sent |
47 |
48 |
49 | ##    Status, Logging and Persisted state
50 | | Command | Description | Parameters |
51 | | ------- | ----------- | ---------- |
52 | | `KTCC_DUMP_STATS` | Dump the KTCC statistics to console. | |
53 | | `KTCC_RESET_STATS` | Reset all the KTCC statistics. | `SUERE=[yes\|no]` If "yes" the stored statistics will be reset. |
54 | | `KTCC_INIT_PRINT_STATS` | Run at start of a print to initialize and reset the KTCC print statistics | |
55 | | `KTCC_DUMP_PRINT_STATS` | Run at end of a print to dump statistics since last print reset to console. | |
56 | | `KTCC_SET_LOG_LEVEL` | Set the log level for the KTCC | `LEVEL=[0-3]` How much to log to console: ( 0 = Only the Always messages ) ( 1 = Info messages and above ) ( 2 = Debug messages and above ) ( 3 = Trace messages and above )
`LOGFILE=[0-3]` How much to log to file. Levels as above. |
57 | | `KTCC_LOG_TRACE` | Send a message to log at this logging level | `MSG=...` The message to be sent |
58 | | `KTCC_LOG_DEBUG` | Send a message to log at this logging level | `MSG=...` The message to be sent |
59 | | `KTCC_LOG_INFO` | Send a message to log at this logging level | `MSG=...` The message to be sent |
60 | | `KTCC_LOG_ALWAYS` | Send a message to log at this logging level | `MSG=...` The message to be sent |
61 |
62 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Tools for klipper (KTCC - Klipper Tool Changer Code)
4 |
5 |
6 |
7 | Universal Toolchanger driver for Klipper
8 |
9 |
10 | This are python modules, macros and example config for the
11 | [Klipper 3D printer firmware](https://github.com/Klipper3d/klipper) to be able to work as a toolchanger.
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | Klipper Tool Changer code v.2 is now released for preview:
28 | https://github.com/TypQxQ/KTC
29 |
30 | At it's simplest you need to specify extruder, fan, offset for each extruder tool.
31 | Then add your macros for pickup, dropoff, toollock and toolunlock.
32 |
33 | It doesn't matter if you lock the tool by a servo, stepper or moving the toolhead in a special way. Just as long as it can be written in GCODE.
34 | Pickups are also custom Gcode. You can uses the parameters stored for each tool to aproach he ZONE fast, slow in
35 | to PARKING place and lock. Or it have a robotic arm place the tool. It's all posible. :D
36 |
37 | [This](https://www.youtube.com/watch?v=cbRXn7R7JZM&t=52s) is a more complex example of it running on a toolchanger with an aditional ERCF under one tool. T0-8 uses first tool with virtual tools for the ERCF, calling the toolchanges recursively.
38 |
39 | Inspiration comes mainly from how RRF enables toolchanging and from the HappyHare project.
40 | I welcome any and all input and contributions. Don't be afraid to make a pull request :D
41 |
42 | Thank you!
43 |
44 | ## Readme Table of Contents
45 | **[Major feature](#---major-features)**
46 | **[Installation](#---installation)**
47 | \- [1-Install with Moonraker Autoupdate Support](#1-install-with-moonraker-autoupdate-support)
48 | \- [2-Manual Install](#2-manual-install)
49 | **[Configuration requirements](#---configuration-requirements)**
50 | **[G-Code commands](#---g-code-commands)**
51 | **[Values accesible from Macro for each object](#---values-accesible-from-macro-for-each-object)**
52 | **[Example configuration](#---example-configuration)**
53 |
54 | #### Other Docs:
55 |
56 | **[Command Reference](./doc/command_ref.md)**
57 | **[Required and Optional Macros](./klipper_macros/readme.md)**
58 | **[Configuration Reference](./config/readme.md)**
59 |
60 |
61 |
62 | ##    Major features:
63 |
64 | - Support any type of toolchanger and any type of tool
65 | - Tools don't need to be extruders/hotends, can be anything.
66 | - Each Tool is treated as an object and has it's own configuration having configurable coordinates for parking, tool offset, extruder, part cooling fan, etc.
67 | - Tools don't need to be extruders/hotends, can be anything.
68 | - Virtual tools - One tool can have multiple tools. Your T0-T8 can be on same extruder, fan and heater but having an MMU while T9 is another extruder and T10-T12 is another tool with 3 markers that can switched by a servo and finally T13 is a pick and place tool.
69 | - Multiple tools can be grouped in ToolGroup. -Most configuration can be inherited from the group and overwritten when needed by the tool config section.
70 | - Partcooling Fan speed is carried over on toolchange if the tool has a fan. M106/M107 defaults to fan of current_tool but can also specify another tool.
71 | - Extensive extruder temperature control:
72 |
73 | - A tool heater can be set as Active, Standby or Off mode
74 | - Diffrent Active and Standby temperatures for any tool. Switches to Active when selected and to Standby when Parked.
75 | - Configurable delay from Standby to off when parked. If tool isn't used for 30 minutes it cools down until used again.
76 | - Wait to reach temperature with configurable tolerance.
77 | - Position prior to toolchange can optionaly be saved and restored after toolchange. Configurable axis.
78 |
79 | - Current Tool persists at powerdown. Default but optional.
80 | - Tool remaping. Remap a tool to another, no need to reslice.
81 | - Sophisticated logging options (console and ktcc.log file)
82 | - Moonraker update-manager support
83 | - Persitance of state and statistics across restarts.
84 | - Vast customization options!
85 |
86 |
87 |
88 |
89 | ##    Installation
90 |
91 | ### 1\. Install with Moonraker Autoupdate Support
92 | This plugin assumes that you installed Klipper into your home directory (usually `/home/pi`).
93 |
94 | 1) Clone this repo into your home directory where Klipper is installed:
95 | ```
96 | cd ~
97 | git clone https://github.com/TypQxQ/Klipper_ToolChanger.git
98 | ```
99 |
100 | 2) Edit `moonraker.conf` by adding the following entry:
101 | ```
102 | [update_manager client klipper_toolchanger]
103 | type: git_repo
104 | path: ~/Klipper_ToolChanger
105 | origin: https://github.com/TypQxQ/Klipper_ToolChanger.git
106 | install_script: install.sh
107 | is_system_service: False
108 | ```
109 |
110 | 3) Run the `install.sh` script
111 | ```
112 | ~/Klipper_ToolChanger/install.sh
113 | ```
114 |
115 | Klipper_ToolChanger will show up in the update the next time you restart moonraker, or you can restart mooraker right away with: `sudo systemctl restart moonraker`.
116 | If you encouter errors after an automatic Klipper update you can safetly run the `install.sh` scipt again to repair the links to the extension.
117 |
118 | ### 2\. Manual Install
119 | Copy the python (`*.py`) files into the `\klipper\klipper\extras` directory. Assuming Klipper is installed in your home directory:
120 | ```
121 | cp ./*.py ~/klipper/klippy/extras/
122 | ```
123 | Then restart Klipper to pick up the extensions.
124 |
125 | ##    Configuration requirements
126 | * `[input_shaper]` needs to be used for input shaper to wordk.
127 |
128 | ##    G-Code commands:
129 | Reffer to the [Command Reference](./doc/command_ref.md).
130 |
131 | ##    Values accesible from Macro for each object
132 | - **Toollock**
133 | - `global_offset` - Global offset.
134 | - `tool_current` - -2: Unknown tool locked, -1: No tool locked, 0: and up are toolnames.
135 | - `saved_fan_speed` - Speed saved at each fanspeedchange to be recovered at Toolchange.
136 | - `purge_on_toolchange` - For use in macros to enable/disable purge/wipe code globaly.
137 | - `restore_axis_on_toolchange` - The axis to restore position:
138 | - : No restore
139 | - XY: Restore XY
140 | - XYZ: Restore XYZ
141 | - Etc
142 | - `saved_position` - The position saved when the latest T# command had a RESTORE_POSITION parameter to other than 0
143 | - **Tool** - The tool calling this macro is referenced as `myself` in macros. When running for example `T3` to pickup the physical tool, in `pickup_gcode:` of one can write `{myself.name}` which would return `3`.
144 | - `name` - id. 0, 1, 2, etc.
145 | - `is_virtual` - If this tool has another layer of toolchange possible.
146 | - `physical_parent_id` - Parent physical tool that holds tool coordinates. Can be same as this.
147 | - `extruder` - extruder name as configured.
148 | - `fan` - fan name.
149 | - `lazy_home_when_parking` - When set to 1, will home unhomed XY axes if needed and will not move any axis if already homed and parked. 2 Will also home Z if not homed.
150 | - `meltzonelength` - Meltzonelength to unload/load filament at toolpak. See e3d documentation.
151 | - `zone` - Fast aproach coordinates when parking
152 | - `park` - Parking spot, slow aproach.
153 | - `offset` - Tool offset.
154 | - `heater_state` - 0 = off, 1 = standby temperature, 2 = active temperature. Placeholder.
155 | - `heater_active_temp` - Temperature to set when in active mode.
156 | - `heater_standby_temp` - Temperature to set when in standby mode.
157 | - `idle_to_standby_time` - Time in seconds from being parked to setting temperature to standby the temperature above. Use 0.1 to change imediatley to standby temperature.
158 | - `idle_to_powerdown_time` - Time in seconds from being parked to setting temperature to 0. Use something like 86400 to wait 24h if you want to disable. Requred on Physical tool.
159 | - **ToolGroup**
160 | - `is_virtual` - As above
161 | - `physical_parent_id` - As above
162 | - `lazy_home_when_parking` - As above
163 |
164 | ##    Example configuration
165 | My corrent configuration is for v.2 where work progresses fast.
166 |
167 | ##    Updates 21/09/2023
168 | Added individual axis to position saving and restoring commands. Commited by viesturz.
169 |
170 | ##    Updates 09/03/2023
171 | Added Tool Remap. Point one or more tools to another one. Including fan and temperature. This is persistent at reboot.
172 | * `KTCC_DISPLAY_TOOL_MAP` - Display the current mapping of tools to other KTCC tools.
173 | * `KTCC_REMAP_TOOL` - The command to remap a tool or reset the remaping.
174 | * `KTCC_CHECK_TOOL_REMAP` - Display all tool remaps.
175 |
176 | ##    Updates 08/03/2023
177 | Added per print statistics and a wrapper around G28 to disable saving statistics while homing.
178 | The latter led to MCU Timer to close error when loading a tool at homing.
179 | * `KTCC_INIT_PRINT_STATS` - Run at start of a print to reset the KTCC print statistics.
180 | * `KTCC_DUMP_PRINT_STATS` - Run at end of a print to list statistics since last print reset.
181 |
182 | ##    Updates 22/02/2023
183 | This is not a simple upgrade, it has some configuration updates.
184 | A namechange to KTCC (Klipper Tool Changer Code) is also in the works).
185 |
186 | - **News:**
187 | - Virtual Tools
188 | - Logfile
189 | - Statistics
190 |
191 | - **Changes to Configuration:**
192 | - LogLevel under ToolLock is deprecated.
193 | - Must include new section ```[ktcclog]``` before all other Toollock, tool, and the others..
194 | - New ```virtual_toolload_gcode:`` parameter to tools.
195 | - New ```virtual_toolunload_gcode:`` parameter to tools.
196 |
197 | - **Changes to commands:**
198 | - T_1 => KTCC_TOOL_DROPOFF_ALL
199 | - T# => KTCC_T# (ex. T0 => KTCC_T0)
200 |
201 | - **New commands:**
202 | - KTCC_SET_GCODE_OFFSET_FOR_CURRENT_TOOL
203 | - KTCC_LOG_TRACE
204 | - KTCC_LOG_DEBUG
205 | - KTCC_LOG_INFO
206 | - KTCC_LOG_ALWAYS
207 | - KTCC_SET_LOG_LEVEL
208 | - KTCC_DUMP_STATS
209 | - KTCC_RESET_STATS
210 |
--------------------------------------------------------------------------------
/config/example_complex/tools.cfg:
--------------------------------------------------------------------------------
1 | # Config order: ToolGroups must come before tools that use them. Tool that are used as physical_parent must be configured before other virtual tools that use that as parent.
2 |
3 |
4 | # Enables saving of variables between powerdown of machine. Must be configured before [toollock].
5 | [save_variables]
6 | filename: ~/variables.cfg
7 |
8 | [ktcclog] # Log_level & logfile_level can be set to one of (0 = essential, 1 = info, 2 = debug, 3 = trace)
9 | log_level: 2
10 | logfile_level: 3
11 |
12 | [toollock]
13 | purge_on_toolchange = True # Here we can disable all purging. When disabled it overrides all other purge options. Defaults to true. This can be turned off by a macro for automatic probing hot tools without probing them. For example when doing TAMV or ZTATP.
14 | global_offset = 0,0,0
15 | #init_printer_to_last_tool = True #Initialise as it was turned off, unlock tool if none was loaded or lock if one was loaded. Defaults to True
16 | tool_lock_gcode:
17 | SAVE_GCODE_STATE NAME=tool_unlock_state # Save gcode state
18 | MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=0 # Set assumed possition as rotated to min
19 | MANUAL_STEPPER STEPPER=tool_lock Move=1 SPEED=30 STOP_ON_ENDSTOP=-1 SYNC=1 # Move until no longer endstop is triggered, max 1degree. If Endstop is not untriggered then raise an error. Wait for the movement before continuing.
20 | SET_TMC_CURRENT STEPPER=tool_lock CURRENT=1.0 # Raise current of stepper temporarily
21 | MANUAL_STEPPER STEPPER=tool_lock Move=150 SPEED=50 STOP_ON_ENDSTOP=1 SYNC=1 # Move to max and stop on endstop. If Endstop is not triggered then raise an error. Wait for the movement before continuing.
22 | M400
23 | MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=0 # Set manual extruder position as 0
24 | SET_TMC_CURRENT STEPPER=tool_lock CURRENT=0.7 # Decrease current to standard current.
25 | RESTORE_GCODE_STATE NAME=tool_unlock_state MOVE=0 # Restore gcode state
26 | M117 "Unknown tool Loaded" # Tool Loaded Message that stays on display.
27 |
28 | tool_unlock_gcode:
29 | SAVE_GCODE_STATE NAME=tool_lock_state # Save gcode state
30 | MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=180 # Set assumed possition as rotated to max
31 | MANUAL_STEPPER STEPPER=tool_lock Move=179 SPEED=30 STOP_ON_ENDSTOP=-1 SYNC=1 # Move until no longer endstop is triggered, max 1degree. If Endstop is not untriggered then raise an error. Wait for the movement before continuing.
32 | MANUAL_STEPPER STEPPER=tool_lock Move=0 SPEED=100 STOP_ON_ENDSTOP=1 SYNC=1 # Move to min and stop on endstop. If Endstop is not triggered then raise an error. Wait for the movement before continuing.
33 | M400
34 | MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=0 # Set manual extruder position as 0
35 | MANUAL_STEPPER STEPPER=tool_lock ENABLE=0 # Turn off the stepper while unlocked so it can rest without triggering the endswitch
36 | RESTORE_GCODE_STATE NAME=tool_lock_state MOVE=0 # Restore gcode state
37 | M117 Tool Unloaded # Tool UnLoaded Message that stays on display.
38 |
39 | [toolgroup 0]
40 | is_virtual: True # If True then must have a physical_parent declared and shares extruder, hotend and fan with the physical_parent
41 | physical_parent: 0 # Tool used as a Physical parent for all toos of this group. Only used if the tool i virtual.
42 | #idle_to_standby_time: 30
43 | #idle_to_powerdown_time: 600
44 | virtual_toolload_gcode:
45 | # Because the virtual tools match the number on ERCF I just call that.
46 | SUB_VIRTUALTOOL_LOAD T={myself.name}
47 | virtual_toolunload_gcode:
48 | SUB_VIRTUALTOOL_UNLOAD T={myself.name}
49 |
50 |
51 | # Used to group several tools with similar settings.
52 | [toolgroup 1]
53 | is_virtual: False # If True then must have a physical_parent declared and shares extruder, hotend and fan with the physical_parent
54 | pickup_gcode:
55 | SUB_TOOL_PICKUP_START T={myself.name}
56 | SUB_TOOL_PICKUP_END T={myself.name}
57 | dropoff_gcode:
58 | SUB_TOOL_DROPOFF_START T={myself.name}
59 | SUB_TOOL_DROPOFF_END T={myself.name}
60 |
61 | ##### Selectable tool. Must be configured after [toolgroup n].
62 | [tool 0]
63 | tool_group: 0 # Must be used and configured before this tool
64 | ##### Following can be inherited from Physical parent if not specified for this tool. Needed only by physical tools.
65 | extruder: extruder
66 | fan: partfan_t0
67 | zone: 550,5
68 | park: 598,5
69 | offset: 11.406,3.778,3.537
70 | #####
71 | ##### Following can be inherited from ToolGroup if not specified for this tool or inherited from a Physical parent.
72 | #physical_parent: # Defaults to None.
73 | #is_virtual: False # Defaults to False
74 | meltzonelength: 14 #18 # Defaults to 0
75 | #####
76 | ##### Options below have no effect on Virtual tools.
77 | idle_to_standby_time: 0.1 # Time in seconds from being parked to setting temperature to standby the temperature above. Use 0.1 to change imediatley to standby temperature. Defaults to 30
78 | #idle_to_powerdown_time: 600 # Time in seconds from being parked to setting temperature to 0. Use something like 86400 to wait 24h if you want to disable. Defaults to 600
79 | lazy_home_when_parking: 1 # (default: 0 - disabled) - When set to 1, will home unhomed XY axes if needed and will not move any axis if already homed and parked. 2 Will also home Z if not homed.
80 | shaper_freq_x: 137.2
81 | shaper_freq_y: 116.4
82 | shaper_type_x: 2hump_ei
83 | shaper_type_y: 2hump_ei
84 |
85 | #pickup_gcode= The code that is run when picking up the physical tool. Variable {myself} refers to the tool calling this code.
86 | pickup_gcode:
87 | SUB_TOOL_PICKUP_START T={myself.name}
88 | SUB_TOOL_PICKUP_END T={myself.name}
89 | dropoff_gcode:
90 | RESPOND MSG="dropoff_gcode. in t0"
91 | SUB_TOOL_DROPOFF_START T={myself.name}
92 | SUB_TOOL_DROPOFF_END T={myself.name}
93 |
94 | [tool 1]
95 | tool_group: 0
96 |
97 | [tool 2]
98 | tool_group: 0
99 | [tool 3]
100 | tool_group: 0
101 | [tool 4]
102 | tool_group: 0
103 | [tool 5]
104 | tool_group: 0
105 | [tool 6]
106 | tool_group: 0
107 | [tool 7]
108 | tool_group: 0
109 | [tool 8]
110 | tool_group: 0
111 |
112 | # End of Tool 0 virtual tools.
113 |
114 | [tool 9]
115 | tool_group: 1
116 | extruder: extruder1
117 | fan: partfan_t9
118 | zone: 550,100
119 | park: 598,100
120 | offset: -1.046,-0.220,-1.510
121 | meltzonelength: 14 #18
122 | idle_to_standby_time: 0.1
123 | shaper_freq_x: 126.8
124 | shaper_freq_y: 128.6
125 | shaper_type_x: 3hump_ei
126 | shaper_type_y: 3hump_ei
127 |
128 | [tool 10]
129 | tool_group: 1
130 | extruder: extruder2
131 | fan: partfan_t10
132 | zone: 550,200
133 | park: 598,200
134 | offset: 12.069,4.472,3.180
135 | meltzonelength: 14 #18
136 | idle_to_standby_time: 0.1
137 | shaper_freq_x: 119.8
138 | shaper_freq_y: 126.6
139 | shaper_type_x: mzv
140 | shaper_type_y: 2hump_ei
141 |
142 | [tool 49]
143 | tool_group: 1
144 | zone: 560,515
145 | park: 598,515
146 | offset: 0,0,0
147 | # Just to reset the input shaper.
148 | #shaper_freq_x: 0
149 | #shaper_freq_y: 0
150 | #shaper_type_x: mzv
151 | #shaper_type_y: mzv
152 |
153 | [gcode_macro SUB_TOOL_PICKUP_START]
154 | description: Internal subroutine. Do not use!
155 | # Tnnn: Tool to pickup
156 | gcode:
157 | {%set myself = printer['tool '~params.T]%}
158 |
159 | M568 P{myself.name} A2 # Put tool heater in Active mode
160 |
161 | SAVE_ACCELERATION # Save current acceleration value.
162 | M204 S8000 # Set high acceleration for toolchanging
163 |
164 | SAVE_GCODE_STATE NAME=TOOL_PICKUP # Save GCODE state. Will be restored at the end of SUB_TOOL_PICKUP_END
165 | SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=0 # Don't use the X-max endstop as EmergencyStop.
166 | G90
167 |
168 | ############## Move in to zone ##############
169 | {% if printer.toolhead.position.x < 500 %} # If Printer inside safezone:
170 | G0 X500 Y{myself.zone[1]} F40000 # Fast move XY inside the safezone.
171 | {% else %} # Else, outside of safezone:
172 | G0 X500 F40000 # Fast move X inside the safezone, so we don't crash into other tools.
173 | G0 Y{myself.zone[1]} F40000 # Fast move Y in front of parking spot.
174 | {% endif %} # /
175 |
176 | ############## Move in to parking spot ##############
177 | G0 X{myself.park[0]|int - 15} F40000 # Fast Move near the pickup position for tool.
178 | G0 X{myself.park[0]} F3000 # Slow Move to the pickup position for tool.
179 |
180 | ############## Lock Tool ##############
181 | M400 # Wait for all moves to finish.
182 | TOOL_LOCK # Lock the tool.
183 | SET_GCODE_OFFSET Z={myself.offset[2]} MOVE=1 # Set and move the Z offset. Avoid crashing into bed when moving out later.
184 |
185 | ############## Wait for heater ##############
186 | {% if myself.extruder|default("none")|lower !="none" %} # If the tool has an extruder:
187 | M116 P{myself.name} # Wait for tool to reach target temperature.
188 | {% endif %} # /
189 |
190 | ############## Move out to zone ##############
191 | G0 X{myself.zone[0]} F6000 # Slow Move to the zone position for tool.
192 |
193 | [gcode_macro SUB_TOOL_PICKUP_END]
194 | description: Internal subroutine. Do not use!
195 | # Tnnn: Tool to pickup
196 | gcode:
197 | {%set myself = printer['tool '~params.T]%}
198 | {%set ktcc = printer['ktcc_toolchanger']%}
199 | ############## Move out to Safe position ##############
200 | G0 X500 F40000 # Fast Move to the safe position for tools.
201 |
202 | ############## Check Tool Lock ##############
203 | QUERY_ENDSTOPS # Check the endstops and save the state to be retrieved in the macro below.
204 | TOOL_LOCK_CHECK # MAcro to check so the tool is mounted by slightly advancing the lock again until hit endstop, only if endstop not already hit. Do not wait for it to finish.
205 |
206 | ############## Finnish up ##############
207 | M400 # Wait for current moves to finish.
208 | SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=1 # Use the X max as EmergencyStop.
209 | RESTORE_GCODE_STATE NAME=TOOL_PICKUP MOVE=0 # Restore GCODE state. Was saved at thebegining of SUB_TOOL_PICKUP_START. Move fast to last location.
210 | # Set the toolhead offsets. Z is set and moved before any moves in SUB_TOOL_PICKUP_START. Needs to be after any RESTORE_GCODE_STATE!
211 | SET_GCODE_OFFSET X={myself.offset[0]|float + ktc.global_offset[0]|float } Y={myself.offset[1]|float + ktc.global_offset[1]|float } Z={myself.offset[2]|float + ktc.global_offset[2]|float } MOVE=0
212 |
213 | ############## Return to saved position ##############
214 | G1 F40000
215 | RESTORE_POSITION
216 |
217 | SAVE_GCODE_STATE NAME=TOOL_PICKUP2 # Save state for priming nozzle
218 | # RESPOND MSG="First if:{myself.extruder|default("none")|lower}"
219 |
220 | ############## Prime the filament, asume it was retracted as per e3d Revo documentation ##############
221 | {% if myself.extruder|default("none")|lower !="none" %} # If the tool has an extruder:
222 | # RESPOND MSG="First if1:{myself.extruder|default("none")|lower}"
223 | # RESPOND MSG="Second if:{printer[myself.extruder].can_extrude|default("false")|lower}"
224 | # RESPOND MSG="Second if1:{printer.toollock.purge_on_toolchange}"
225 | # If can extrude and global purge is active:
226 | {% if printer[myself.extruder].can_extrude|default("false")|lower == 'true' and printer.toollock.purge_on_toolchange %}
227 | # RESPOND MSG="Second if2:{printer[myself.extruder].can_extrude|default("false")|lower}"
228 | # RESPOND MSG="Second if3:{printer.toollock.purge_on_toolchange}"
229 | M83 # Relative extrusion
230 | G1 E{myself.meltzonelength|float - 2} F1300 # DeRetract filament from meltzone
231 | G1 E2 F400 # DeRetract filament from meltzone
232 | {% endif %}
233 | {% endif %}
234 | RESTORE_GCODE_STATE NAME=TOOL_PICKUP2 # Restore state after priming nozzle
235 | G1 F30000
236 | RESTORE_ACCELERATION # Restore saved acceleration value.
237 |
238 |
239 |
240 | [gcode_macro SUB_TOOL_DROPOFF_START]
241 | description: Internal subroutine. Do not use!
242 | # Tnnn: Tool to pickup
243 | gcode:
244 | {%set myself = printer['tool '~params.T]%}
245 |
246 | SAVE_ACCELERATION # Save current acceleration value.
247 | M204 S8000 # Set high acceleration for toolchanging
248 |
249 | {% if myself.name|int != printer.toollock.tool_current|int %}
250 | { action_raise_error("SUB_TOOL_DROPOFF_START: Wrong tool. Asked to dropoff T" ~ myself.name ~ " while current is T" ~ printer.toollock.tool_current ~ ".") }
251 | {% endif %}
252 |
253 | ############## Retract the filament as per e3d Revo documentation ##############
254 | {% if myself.extruder|default("none")|lower !="none" %} # If the tool has an extruder:
255 | M568 P{myself.name} A1 # Put tool heater in standby
256 |
257 | {% if printer[myself.extruder].can_extrude|default("false")|lower == 'true' and printer.toollock.purge_on_toolchange %}
258 | M83 # Relative extrusion
259 | G1 E-4 F2700 # retract filament from meltzone
260 | G1 E2 F800 # Extrude slightly to form a tip
261 | G1 E-{myself.meltzonelength|float - 2} F800 # Retract filament from meltzone
262 | {% endif %}
263 | {% endif %}
264 |
265 | SET_GCODE_OFFSET X=0 Y=0 # Set XY offset to 0 so we park the tool right.
266 | SAVE_GCODE_STATE NAME=TOOL_DROPOFF_002 # Save GCode state.
267 | G90 # Absolute positions
268 |
269 | SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=0 # Don't use the X max as EmergencyStop.
270 |
271 | # Fast Move to the general pickup position for tools.
272 | {% if printer.toolhead.position.x|float < 500 %}
273 | G0 X500 Y{myself.zone[1]} F40000 # Move near pickup and lift z so we don't crash the bed later.
274 | {% else %}
275 | G0 X500 F40000 # Move X and lift z so we don't crash the bed or into other tools.
276 | G0 Y{myself.zone[1]} F40000 # Move Y after X and Z
277 | {% endif %}
278 | M400 # Wait for current moves to finish
279 |
280 | G0 X{myself.zone[0]} F40000 # Fast Move near the dropoff position for tool.
281 | G0 X{myself.park[0]} F3000 # Slow Move to the dropoff position for tool.
282 |
283 |
284 | [gcode_macro SUB_TOOL_DROPOFF_END]
285 | description: Internal subroutine. Do not use!
286 | # Tnnn: Tool to pickup
287 | gcode:
288 | {%set myself = printer['tool '~params.T]%}
289 |
290 | M400 # Wait for current moves to finish
291 | TOOL_UNLOCK # Unlock the tool
292 |
293 | G0 X{myself.park[0]|float - 15} F6000 # Slow Move to the pickup position for tool.
294 | G0 X500 F40000 # Fast Move to the general pickup position for tools.
295 | M400
296 |
297 | SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=1 # Use the X max as EmergencyStop.
298 | RESTORE_GCODE_STATE NAME=TOOL_DROPOFF_002 MOVE=0 # Restore Gcode state
299 | RESTORE_ACCELERATION # Restore saved acceleration value.
300 |
301 | [gcode_macro SUB_VIRTUALTOOL_LOAD]
302 | description: Internal subroutine. Do not use!
303 | # Tnnn: Tool to load
304 | gcode:
305 | {%set myself = printer['tool '~params.T]%}
306 |
307 | SET_TOOL_TEMPERATURE TOOL={myself.name} CHNG_STATE=2 # Put tool heater in Active mode
308 |
309 | SAVE_ACCELERATION # Save current acceleration value.
310 | M204 S8000 # Set high acceleration for toolchanging
311 |
312 | SAVE_GCODE_STATE NAME=VIRTUALTOOL_LOAD # Save GCODE state. Will be restored at the end of SUB_TOOL_PICKUP_END
313 | SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=0 # Don't use the X-max endstop as EmergencyStop.
314 | SET_GCODE_OFFSET X=0 Y=0 # Set XY offset to 0 so we park the tool right.
315 | G90 # Absolute positions
316 |
317 | ############## Move in to zone ##############
318 | {% if printer.toolhead.position.x < 500 %} # If Printer inside safezone:
319 | G0 X500 Y{myself.zone[1]} F40000 # Fast move XY inside the safezone.
320 | {% else %} # Else, outside of safezone:
321 | G0 X500 F40000 # Fast move X inside the safezone, so we don't crash into other tools.
322 | G0 Y{myself.zone[1]} F40000 # Fast move Y in front of parking spot.
323 | {% endif %} # /
324 | G0 X{myself.zone[0]} F40000 # Fast Move to the zone position for tool.
325 |
326 | ############## Wait for heater ##############
327 | TEMPERATURE_WAIT_WITH_TOLERANCE TOOL={myself.name} # Wait for tool to reach target temperature.
328 |
329 | ############## Load ERCF Tool ##############
330 | M400 # Wait for all moves to finish.
331 | G4 P5000 # Wait 5s so any fiament inside the hotend will get molten before tip forming.
332 | ERCF_CHANGE_TOOL TOOL={myself.name} STANDALONE=1 # Load the ERCF tool.
333 |
334 | ############## Clear the filament by purging ##############
335 | M83 # Relative extrusion
336 | G1 E50 F300 # Purge filament for new.
337 | G1 E25 F300 # Purge filament for new.
338 | G1 E-1 F2400 # Equalize pressure.
339 |
340 | ############## Wipe the nozzle ##############
341 | SUB_TOOL_WIPE T={myself.name} # Wipe the tool at the toolpost.
342 | G0 X{myself.zone[0]} F3000 # Fast Move to the zone position for tool.
343 |
344 | ############## Move in to parking spot ##############
345 | G0 X{myself.park[0]} F3000 # Slow Move to the pickup position for tool.
346 |
347 | ############## Move out to zone ##############
348 | G0 X{myself.zone[0]} F6000 # Slow Move to the zone position for tool.
349 |
350 | ############## Move out to Safe position ##############
351 | G0 X500 F40000 # Fast Move to the safe position for tools.
352 |
353 | ############## Finnish up ##############
354 | M400 # Wait for current moves to finish.
355 | SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=1 # Use the X max as EmergencyStop.
356 | RESTORE_GCODE_STATE NAME=VIRTUALTOOL_LOAD MOVE=0 # Restore GCODE state. Was saved at the begining of SUB_VIRTUALTOOL_LOAD_START. No move.
357 |
358 | ############## Return to saved position ##############
359 | G1 F40000
360 | RESTORE_POSITION # This checks if the position is to be restored or not.
361 | RESTORE_ACCELERATION # Restore saved acceleration value.
362 |
363 | [gcode_macro SUB_VIRTUALTOOL_UNLOAD]
364 | description: Internal subroutine. Do not use!
365 | # Tnnn: Tool to unload
366 | gcode:
367 | {%set myself = printer['tool '~params.T]%}
368 |
369 | SAVE_ACCELERATION # Save current acceleration value.
370 | M204 S8000 # Set high acceleration for toolchanging
371 |
372 | SAVE_GCODE_STATE NAME=VIRTUALTOOL_UNLOAD # Save GCode state.
373 | SET_GCODE_OFFSET X=0 Y=0 # Set XY offset to 0 so we park the tool right.
374 | G90 # Absolute positions
375 |
376 | SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=0 # Don't use the X max as EmergencyStop.
377 |
378 | ############## Move in to zone ##############
379 | {% if printer.toolhead.position.x|int < 500 %}
380 | G0 X500 Y{myself.zone[1]} F40000 # Move near pickup and lift z so we don't crash the bed later.
381 | {% else %}
382 | G0 X500 F40000 # Move X and lift z so we don't crash the bed or into other tools.
383 | G0 Y{myself.zone[1]} F40000 # Move Y after X and Z
384 | {% endif %}
385 | M400 # Wait for current moves to finish
386 |
387 | G0 X{myself.zone[0]} F40000 # Fast Move near the dropoff position for tool.
388 |
389 | ############## Wait for heater ##############
390 | M116 P{myself.name} # Wait for tool to reach target temperature.
391 |
392 | ############## Ejecting filament from ERCF ##############
393 | G4 P5000 # Wait 5s so any fiament inside the hotend will get molten before tip forming.
394 | ERCF_EJECT
395 |
396 | ############## Wipe the nozzle ##############
397 | SUB_TOOL_WIPE T={myself.name} # Wipe the tool at the toolpost.
398 |
399 | ############## Move in to parking spot ##############
400 | G0 X{myself.park[0]} F3000 # Slow Move to the dropoff position for tool to remove any excess filament on tool.
401 |
402 | M400 # Wait for current moves to finish
403 |
404 | G0 X{myself.park[0]|int - 15} F6000 # Slow Move to the pickup position for tool.
405 | G0 X500 F40000 # Fast Move to the general pickup position for tools.
406 | M400
407 |
408 | SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=1 # Use the X max as EmergencyStop.
409 | RESTORE_GCODE_STATE NAME=VIRTUALTOOL_UNLOAD MOVE=0 # Restore Gcode state
410 | RESTORE_ACCELERATION # Restore saved acceleration value.
411 |
412 | [gcode_macro SUB_TOOL_WIPE]
413 | description: Internal subroutine. Do not use!
414 | # Tnnn: Tool
415 | gcode:
416 | {%set myself = printer['tool '~params.T]%}
417 | ############## Wipe the nozzle ##############
418 | G0 X{myself.park[0]|int - 10} F3000 # Fast Move near the pickup position for tool.
419 | G0 X{myself.zone[0]} F3000 # Fast Move to the zone position for tool.
420 | G0 X{myself.park[0]|int - 10} F3000 # Fast Move near the pickup position for tool.
421 | G0 X{myself.zone[0]} F3000 # Fast Move to the zone position for tool.
422 | G0 X{myself.park[0]|int - 10} F3000 # Fast Move near the pickup position for tool.
423 | G0 X{myself.zone[0]} F3000 # Fast Move to the zone position for tool.
424 | G0 X{myself.park[0]|int - 10} F3000 # Fast Move near the pickup position for tool.
425 | G0 X{myself.zone[0]} F3000 # Fast Move to the zone position for tool.
426 | SET_GCODE_OFFSET Z=0 # Set Z offset to 0 after too is parked.
427 |
--------------------------------------------------------------------------------
/toollock.py:
--------------------------------------------------------------------------------
1 | # KTCC - Klipper Tool Changer Code
2 | # Toollock and general Tool support
3 | #
4 | # Copyright (C) 2023 Andrei Ignat
5 | #
6 | # This file may be distributed under the terms of the GNU GPLv3 license.
7 | #
8 |
9 | # To try to keep terms apart:
10 | # Mount: Tool is selected and loaded for use, be it a physical or a virtual on physical.
11 | # Unmopunt: Tool is unselected and unloaded, be it a physical or a virtual on physical.
12 | # Pickup: Tool is physically picked up and attached to the toolchanger head.
13 | # Droppoff: Tool is physically parked and dropped of the toolchanger head.
14 | # ToolLock: Toollock is engaged.
15 | # ToolUnLock: Toollock is disengaged.
16 |
17 | class ToolLock:
18 | TOOL_UNKNOWN = -2
19 | TOOL_UNLOCKED = -1
20 | BOOT_DELAY = 1.5 # Delay before running bootup tasks
21 | VARS_KTCC_TOOL_MAP = "ktcc_state_tool_remap"
22 |
23 | def __init__(self, config):
24 | self.printer = config.get_printer()
25 | self.reactor = self.printer.get_reactor()
26 | self.gcode = self.printer.lookup_object('gcode')
27 | gcode_macro = self.printer.load_object(config, 'gcode_macro')
28 |
29 | self.global_offset = config.get('global_offset', "0,0,0")
30 | if isinstance(self.global_offset, str):
31 | offset_list = self.global_offset.split(',')
32 | if len(offset_list) == 3 and all(x.replace('.', '').isdigit() for x in offset_list):
33 | self.global_offset = [float(x) for x in offset_list]
34 | else:
35 | raise ValueError("global_offset is not a string containing 3 float numbers separated by ,")
36 | else:
37 | raise TypeError("global_offset is not a string")
38 |
39 | self.saved_fan_speed = 0 # Saved partcooling fan speed when deselecting a tool with a fan.
40 | self.tool_current = "-2" # -2 Unknown tool locked, -1 No tool locked, 0 and up are tools.
41 | self.init_printer_to_last_tool = config.getboolean(
42 | 'init_printer_to_last_tool', True)
43 | self.purge_on_toolchange = config.getboolean(
44 | 'purge_on_toolchange', True)
45 | self.saved_position = None
46 | self.restore_axis_on_toolchange = '' # string of axis to restore: XYZ
47 | self.log = self.printer.load_object(config, 'ktcclog')
48 |
49 | self.tool_map = {}
50 | self.last_endstop_query = {}
51 | self.changes_made_by_set_all_tool_heaters_off={}
52 |
53 | # G-Code macros
54 | self.tool_lock_gcode_template = gcode_macro.load_template(config, 'tool_lock_gcode', '')
55 | self.tool_unlock_gcode_template = gcode_macro.load_template(config, 'tool_unlock_gcode', '')
56 |
57 | # Register commands
58 | handlers = [
59 | 'SAVE_CURRENT_TOOL', 'TOOL_LOCK', 'TOOL_UNLOCK',
60 | 'KTCC_TOOL_DROPOFF_ALL', 'SET_AND_SAVE_FAN_SPEED', 'TEMPERATURE_WAIT_WITH_TOLERANCE',
61 | 'SET_TOOL_TEMPERATURE', 'SET_GLOBAL_OFFSET', 'SET_TOOL_OFFSET',
62 | 'SET_PURGE_ON_TOOLCHANGE', 'SAVE_POSITION', 'SAVE_CURRENT_POSITION',
63 | 'RESTORE_POSITION', 'KTCC_SET_GCODE_OFFSET_FOR_CURRENT_TOOL',
64 | 'KTCC_DISPLAY_TOOL_MAP', 'KTCC_REMAP_TOOL', 'KTCC_ENDSTOP_QUERY',
65 | 'KTCC_SET_ALL_TOOL_HEATERS_OFF', 'KTCC_RESUME_ALL_TOOL_HEATERS']
66 | for cmd in handlers:
67 | func = getattr(self, 'cmd_' + cmd)
68 | desc = getattr(self, 'cmd_' + cmd + '_help', None)
69 | self.gcode.register_command(cmd, func, False, desc)
70 |
71 | self.printer.register_event_handler("klippy:ready", self.handle_ready)
72 |
73 | def handle_ready(self):
74 | # Load persistent Tool remaping.
75 | self.tool_map = self.printer.lookup_object('save_variables').allVariables.get(self.VARS_KTCC_TOOL_MAP, {})
76 | waketime = self.reactor.monotonic() + self.BOOT_DELAY
77 | self.reactor.register_callback(self._bootup_tasks, waketime)
78 |
79 | def _bootup_tasks(self, eventtime):
80 | try:
81 | if len(self.tool_map) > 0:
82 | self.log.always(self._tool_map_to_human_string())
83 | self.Initialize_Tool_Lock()
84 | except Exception as e:
85 | self.log.always('Warning: Error booting up KTCC: %s' % str(e))
86 |
87 | def Initialize_Tool_Lock(self):
88 | if not self.init_printer_to_last_tool:
89 | return None
90 |
91 | # self.log.always("Initialize_Tool_Lock running.")
92 | save_variables = self.printer.lookup_object('save_variables')
93 | try:
94 | self.tool_current = save_variables.allVariables["tool_current"]
95 | except:
96 | self.tool_current = "-1"
97 | save_variables.cmd_SAVE_VARIABLE(self.gcode.create_gcode_command(
98 | "SAVE_VARIABLE", "SAVE_VARIABLE", {"VARIABLE": "tool_current", 'VALUE': self.tool_current }))
99 |
100 | if str(self.tool_current) == "-1":
101 | self.cmd_TOOL_UNLOCK()
102 | self.log.always("ToolLock initialized unlocked")
103 |
104 | else:
105 | t = self.tool_current
106 | self.ToolLock(True)
107 | self.SaveCurrentTool(str(t))
108 | self.log.always("ToolLock initialized with T%s." % self.tool_current)
109 |
110 | cmd_TOOL_LOCK_help = "Lock the ToolLock."
111 | def cmd_TOOL_LOCK(self, gcmd = None):
112 | self.ToolLock()
113 |
114 | def ToolLock(self, ignore_locked = False):
115 | self.log.trace("TOOL_LOCK running. ")
116 | if not ignore_locked and int(self.tool_current) != -1:
117 | self.log.always("TOOL_LOCK is already locked with tool " + self.tool_current + ".")
118 | else:
119 | self.tool_lock_gcode_template.run_gcode_from_command()
120 | self.SaveCurrentTool("-2")
121 | self.log.trace("Tool Locked")
122 | self.log.increase_statistics('total_toollocks')
123 |
124 |
125 | cmd_KTCC_TOOL_DROPOFF_ALL_help = "Deselect all tools"
126 | def cmd_KTCC_TOOL_DROPOFF_ALL(self, gcmd = None):
127 | self.log.trace("KTCC_TOOL_DROPOFF_ALL running. ")# + gcmd.get_raw_command_parameters())
128 | if self.tool_current == "-2":
129 | raise self.printer.command_error("cmd_KTCC_TOOL_DROPOFF_ALL: Unknown tool already mounted Can't park unknown tool.")
130 | if self.tool_current != "-1":
131 | self.printer.lookup_object('tool ' + str(self.tool_current)).Dropoff( force_virtual_unload = True )
132 |
133 |
134 | try:
135 | # Need to check all tools at least once but reload them after each time.
136 | all_checked_once = False
137 | while not all_checked_once:
138 | all_tools = dict(self.printer.lookup_objects('tool'))
139 | all_checked_once =True # If no breaks in next For loop then we can exit the While loop.
140 | for tool_name, tool in all_tools.items():
141 | # If there is a virtual tool loaded:
142 | if tool.get_status()["virtual_loaded"] > self.TOOL_UNLOCKED:
143 | # Pickup and then unload and drop the tool.
144 | self.log.trace("cmd_KTCC_TOOL_DROPOFF_ALL: Picking up and dropping forced: %s." % str(tool.get_status()["virtual_loaded"]))
145 | self.printer.lookup_object("tool " + str(tool.get_status()["virtual_loaded"])).select_tool_actual()
146 | self.printer.lookup_object("tool " + str(tool.get_status()["virtual_loaded"])).Dropoff( force_virtual_unload = True )
147 | all_checked_once =False # Do not exit while loop.
148 | break # Break for loop to start again.
149 |
150 | except Exception as e:
151 | raise Exception('cmd_KTCC_TOOL_DROPOFF_ALL: Error: %s' % str(e))
152 |
153 | cmd_TOOL_UNLOCK_help = "Unlock the ToolLock."
154 | def cmd_TOOL_UNLOCK(self, gcmd = None):
155 | self.log.trace("TOOL_UNLOCK running. ")
156 | self.tool_unlock_gcode_template.run_gcode_from_command()
157 | self.SaveCurrentTool(-1)
158 | self.log.trace("ToolLock Unlocked.")
159 | self.log.increase_statistics('total_toolunlocks')
160 |
161 |
162 | def PrinterIsHomedForToolchange(self, lazy_home_when_parking =0):
163 | curtime = self.printer.get_reactor().monotonic()
164 | toolhead = self.printer.lookup_object('toolhead')
165 | homed = toolhead.get_status(curtime)['homed_axes'].lower()
166 | if all(axis in homed for axis in ['x','y','z']):
167 | return True
168 | elif lazy_home_when_parking == 0 and not all(axis in homed for axis in ['x','y','z']):
169 | return False
170 | elif lazy_home_when_parking == 1 and 'z' not in homed:
171 | return False
172 |
173 | axes_to_home = ""
174 | for axis in ['x', 'y', 'z']:
175 | if axis not in homed:
176 | axes_to_home += axis
177 | self.gcode.run_script_from_command("G28 " + axes_to_home.upper())
178 | return True
179 |
180 | def SaveCurrentTool(self, t):
181 | self.tool_current = str(t)
182 | save_variables = self.printer.lookup_object('save_variables')
183 | save_variables.cmd_SAVE_VARIABLE(self.gcode.create_gcode_command(
184 | "SAVE_VARIABLE", "SAVE_VARIABLE", {"VARIABLE": "tool_current", 'VALUE': t}))
185 |
186 | cmd_SAVE_CURRENT_TOOL_help = "Save the current tool to file to load at printer startup."
187 | def cmd_SAVE_CURRENT_TOOL(self, gcmd):
188 | t = gcmd.get_int('T', None, minval=-2)
189 | if t is not None:
190 | self.SaveCurrentTool(t)
191 |
192 | cmd_SET_AND_SAVE_FAN_SPEED_help = "Save the fan speed to be recovered at ToolChange."
193 | def cmd_SET_AND_SAVE_FAN_SPEED(self, gcmd):
194 | fanspeed = gcmd.get_float('S', 1, minval=0, maxval=255)
195 | tool_id = gcmd.get_int('P', int(self.tool_current), minval=0)
196 |
197 | # The minval above doesn't seem to work.
198 | if tool_id < 0:
199 | self.log.always("cmd_SET_AND_SAVE_FAN_SPEED: Invalid tool:"+str(tool_id))
200 | return None
201 |
202 | # self.log.trace("ToolLock.cmd_SET_AND_SAVE_FAN_SPEED: Change fan speed for T%s to %f." % (str(tool_id), fanspeed))
203 |
204 | # If value is >1 asume it is given in 0-255 and convert to percentage.
205 | if fanspeed > 1:
206 | fanspeed=float(fanspeed / 255.0)
207 |
208 | self.SetAndSaveFanSpeed(tool_id, fanspeed)
209 |
210 | #
211 | # Todo:
212 | # Implement Fan Scale. Inspired by https://github.com/jschuh/klipper-macros/blob/main/fans.cfg
213 | # Can change fan scale for diffrent materials or tools from slicer. Maybe max and min too?
214 | #
215 | def SetAndSaveFanSpeed(self, tool_id, fanspeed):
216 | # Check if the requested tool has been remaped to another one.
217 | tool_is_remaped = self.tool_is_remaped(int(tool_id))
218 | if tool_is_remaped > -1:
219 | tool_id = tool_is_remaped
220 |
221 |
222 | tool = self.printer.lookup_object("tool " + str(tool_id))
223 |
224 | if tool.fan is None:
225 | self.log.debug("ToolLock.SetAndSaveFanSpeed: Tool %s has no fan." % str(tool_id))
226 | else:
227 | self.SaveFanSpeed(fanspeed)
228 | self.gcode.run_script_from_command(
229 | "SET_FAN_SPEED FAN=%s SPEED=%f" %
230 | (tool.fan,
231 | fanspeed))
232 |
233 | cmd_TEMPERATURE_WAIT_WITH_TOLERANCE_help = "Waits for current tool temperature, or a specified (TOOL) tool or (HEATER) heater's temperature within (TOLERANCE) tolerance."
234 | # Waits for all temperatures, or a specified tool or heater's temperature.
235 | # This command can be used without any additional parameters.
236 | # Without parameters it waits for bed and current extruder.
237 | # Only one of either P or H may be used.
238 | #
239 | # TOOL=nnn Tool number.
240 | # HEATER=nnn Heater number. 0="heater_bed", 1="extruder", 2="extruder1", etc.
241 | # TOLERANCE=nnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
242 | def cmd_TEMPERATURE_WAIT_WITH_TOLERANCE(self, gcmd):
243 | curtime = self.printer.get_reactor().monotonic()
244 | heater_name = None
245 | tool_id = gcmd.get_int('TOOL', None, minval=0)
246 | heater_id = gcmd.get_int('HEATER', None, minval=0)
247 | tolerance = gcmd.get_int('TOLERANCE', 1, minval=0, maxval=50)
248 |
249 | if tool_id is not None and heater_id is not None:
250 | self.log.always("cmd_TEMPERATURE_WAIT_WITH_TOLERANCE: Can't use both P and H parameter at the same time.")
251 | return None
252 | elif tool_id is None and heater_id is None:
253 | tool_id = self.tool_current
254 | if int(self.tool_current) >= 0:
255 | heater_name = self.printer.lookup_object("tool " + self.tool_current).get_status()["extruder"]
256 | #wait for bed
257 | self._Temperature_wait_with_tolerance(curtime, "heater_bed", tolerance)
258 |
259 | else: # Only heater or tool is specified
260 | if tool_id is not None:
261 | # Check if the requested tool has been remaped to another one.
262 | tool_is_remaped = self.tool_is_remaped(int(tool_id))
263 | if tool_is_remaped > -1:
264 | tool_id = tool_is_remaped
265 |
266 | heater_name = self.printer.lookup_object( # Set the heater_name to the extruder of the tool.
267 | "tool " + str(tool_id)).get_status(curtime)["extruder"]
268 | elif heater_id == 0: # Else If 0, then heater_bed.
269 | heater_name = "heater_bed" # Set heater_name to "heater_bed".
270 |
271 | elif heater_id == 1: # Else If h is 1 then use for first extruder.
272 | heater_name = "extruder" # Set heater_name to first extruder which has no number.
273 | else: # Else is another heater number.
274 | heater_name = "extruder" + str(heater_id - 1) # Because bed is heater_number 0 extruders will be numbered one less than H parameter.
275 | if heater_name is not None:
276 | self._Temperature_wait_with_tolerance(curtime, heater_name, tolerance)
277 |
278 |
279 | def _Temperature_wait_with_tolerance(self, curtime, heater_name, tolerance):
280 | target_temp = int(self.printer.lookup_object( # Get the heaters target temperature.
281 | heater_name).get_status(curtime)["target"]
282 | )
283 |
284 | if target_temp > 40: # Only wait if set temperature is over 40*C
285 | self.log.always("Wait for heater " + heater_name + " to reach " + str(target_temp) + " with a tolerance of " + str(tolerance) + ".")
286 | self.gcode.run_script_from_command(
287 | "TEMPERATURE_WAIT SENSOR=" + heater_name +
288 | " MINIMUM=" + str(target_temp - tolerance) +
289 | " MAXIMUM=" + str(target_temp + tolerance) )
290 | self.log.always("Wait for heater " + heater_name + " complete.")
291 |
292 | def _get_tool_id_from_gcmd(self, gcmd):
293 | tool_id = gcmd.get_int('TOOL', None, minval=0)
294 |
295 | if tool_id is None:
296 | tool_id = self.tool_current
297 | if not int(tool_id) > self.TOOL_UNLOCKED:
298 | self.log.always("_get_tool_id_from_gcmd: Tool " + str(tool_id) + " is not valid.")
299 | return None
300 | else:
301 | # Check if the requested tool has been remaped to another one.
302 | tool_is_remaped = self.tool_is_remaped(int(tool_id))
303 | if tool_is_remaped > self.TOOL_UNLOCKED:
304 | tool_id = tool_is_remaped
305 | return tool_id
306 |
307 |
308 | cmd_SET_TOOL_TEMPERATURE_help = "Waits for all temperatures, or a specified (TOOL) tool or (HEATER) heater's temperature within (TOLERANCE) tolerance."
309 | # Set tool temperature.
310 | # TOOL= Tool number, optional. If this parameter is not provided, the current tool is used.
311 | # STDB_TMP= Standby temperature(s), optional
312 | # ACTV_TMP= Active temperature(s), optional
313 | # CHNG_STATE = Change Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature(s).
314 | # STDB_TIMEOUT = Time in seconds to wait between changing heater state to standby and setting heater target temperature to standby temperature when standby temperature is lower than tool temperature.
315 | # Use for example 0.1 to change immediately to standby temperature.
316 | # SHTDWN_TIMEOUT = Time in seconds to wait from docking tool to shutting off the heater, optional.
317 | # Use for example 86400 to wait 24h if you want to disable shutdown timer.
318 | def cmd_SET_TOOL_TEMPERATURE(self, gcmd):
319 | tool_id = self._get_tool_id_from_gcmd(gcmd)
320 | if tool_id is None: return
321 |
322 | stdb_tmp = gcmd.get_float('STDB_TMP', None, minval=0)
323 | actv_tmp = gcmd.get_float('ACTV_TMP', None, minval=0)
324 | chng_state = gcmd.get_int('CHNG_STATE', None, minval=0, maxval=2)
325 | stdb_timeout = gcmd.get_float('STDB_TIMEOUT', None, minval=0)
326 | shtdwn_timeout = gcmd.get_float('SHTDWN_TIMEOUT', None, minval=0)
327 |
328 |
329 | if self.printer.lookup_object("tool " + str(tool_id)).get_status()["extruder"] is None:
330 | self.log.trace("cmd_SET_TOOL_TEMPERATURE: T%s has no extruder! Nothing to do." % str(tool_id))
331 | return None
332 |
333 | tool = self.printer.lookup_object("tool " + str(tool_id))
334 | set_heater_cmd = {}
335 |
336 | if stdb_tmp is not None:
337 | set_heater_cmd["heater_standby_temp"] = int(stdb_tmp)
338 | if actv_tmp is not None:
339 | set_heater_cmd["heater_active_temp"] = int(actv_tmp)
340 | if stdb_timeout is not None:
341 | set_heater_cmd["idle_to_standby_time"] = stdb_timeout
342 | if shtdwn_timeout is not None:
343 | set_heater_cmd["idle_to_powerdown_time"] = shtdwn_timeout
344 | if chng_state is not None:
345 | set_heater_cmd["heater_state"] = chng_state
346 | # tool.set_heater(heater_state= chng_state)
347 | if len(set_heater_cmd) > 0:
348 | tool.set_heater(**set_heater_cmd)
349 | else:
350 | # Print out the current set of temperature settings for the tool if no changes are provided.
351 | msg = "T%s Current Temperature Settings" % str(tool_id)
352 | msg += "\n Active temperature %s - %d*C - Active to Standby timer: %d seconds" % ( "*" if tool.heater_state == 2 else " ", tool.heater_active_temp, tool.idle_to_standby_time)
353 | msg += "\n Standby temperature %s - %d*C - Standby to Off timer: %d seconds" % ( "*" if tool.heater_state == 1 else " ", tool.heater_standby_temp, tool.idle_to_powerdown_time)
354 | if tool.heater_state != 3:
355 | if tool.timer_idle_to_standby.get_status()["next_wake"] == True:
356 | msg += "\n Will go to standby temperature in in %s seconds." % tool.timer_idle_to_standby.get_status()["next_wake"]
357 | if tool.timer_idle_to_powerdown.get_status()["counting_down"] == True:
358 | msg += "\n Will power down in %s seconds." % tool.timer_idle_to_powerdown.get_status()["next_wake"]
359 | gcmd.respond_info(msg)
360 |
361 | cmd_KTCC_SET_ALL_TOOL_HEATERS_OFF_help = "Turns off all heaters and saves changes made to be resumed by KTCC_RESUME_ALL_TOOL_HEATERS."
362 | def cmd_KTCC_SET_ALL_TOOL_HEATERS_OFF(self, gcmd):
363 | self.set_all_tool_heaters_off()
364 |
365 | def set_all_tool_heaters_off(self):
366 | all_tools = dict(self.printer.lookup_objects('tool'))
367 | self.changes_made_by_set_all_tool_heaters_off = {}
368 |
369 | try:
370 | for tool_name, tool in all_tools.items():
371 | if tool.get_status()["extruder"] is None:
372 | # self.log.trace("set_all_tool_heaters_off: T%s has no extruder! Nothing to do." % str(tool_name))
373 | continue
374 | if tool.get_status()["heater_state"] == 0:
375 | # self.log.trace("set_all_tool_heaters_off: T%s already off! Nothing to do." % str(tool_name))
376 | continue
377 | self.log.trace("set_all_tool_heaters_off: T%s saved with heater_state: %str." % ( str(tool_name), str(tool.get_status()["heater_state"])))
378 | self.changes_made_by_set_all_tool_heaters_off[tool_name] = tool.get_status()["heater_state"]
379 | tool.set_heater(heater_state = 0)
380 | except Exception as e:
381 | raise Exception('set_all_tool_heaters_off: Error: %s' % str(e))
382 |
383 | cmd_KTCC_RESUME_ALL_TOOL_HEATERS_help = "Resumes all heaters previously turned off by KTCC_SET_ALL_TOOL_HEATERS_OFF."
384 | def cmd_KTCC_RESUME_ALL_TOOL_HEATERS(self, gcmd):
385 | self.resume_all_tool_heaters()
386 |
387 | def resume_all_tool_heaters(self):
388 | try:
389 | # Loop it 2 times, first for all heaters standby and then the active.
390 |
391 | for tool_name, v in self.changes_made_by_set_all_tool_heaters_off.items():
392 | if v == 1:
393 | self.printer.lookup_object(str(tool_name)).set_heater(heater_state = v)
394 |
395 | for tool_name, v in self.changes_made_by_set_all_tool_heaters_off.items():
396 | if v == 2:
397 | self.printer.lookup_object(str(tool_name)).set_heater(heater_state = v)
398 |
399 | except Exception as e:
400 | raise Exception('set_all_tool_heaters_off: Error: %s' % str(e))
401 |
402 |
403 | cmd_SET_TOOL_OFFSET_help = "Set an individual tool offset"
404 | def cmd_SET_TOOL_OFFSET(self, gcmd):
405 | tool_id = self._get_tool_id_from_gcmd(gcmd)
406 | if tool_id is None: return
407 |
408 | x_pos = gcmd.get_float('X', None)
409 | x_adjust = gcmd.get_float('X_ADJUST', None)
410 | y_pos = gcmd.get_float('Y', None)
411 | y_adjust = gcmd.get_float('Y_ADJUST', None)
412 | z_pos = gcmd.get_float('Z', None)
413 | z_adjust = gcmd.get_float('Z_ADJUST', None)
414 |
415 | tool = self.printer.lookup_object("tool " + str(tool_id))
416 | set_offset_cmd = {}
417 |
418 | if x_pos is not None:
419 | set_offset_cmd["x_pos"] = x_pos
420 | elif x_adjust is not None:
421 | set_offset_cmd["x_adjust"] = x_adjust
422 | if y_pos is not None:
423 | set_offset_cmd["y_pos"] = y_pos
424 | elif y_adjust is not None:
425 | set_offset_cmd["y_adjust"] = y_adjust
426 | if z_pos is not None:
427 | set_offset_cmd["z_pos"] = z_pos
428 | elif z_adjust is not None:
429 | set_offset_cmd["z_adjust"] = z_adjust
430 | if len(set_offset_cmd) > 0:
431 | tool.set_offset(**set_offset_cmd)
432 |
433 | cmd_SET_GLOBAL_OFFSET_help = "Set the global tool offset"
434 | def cmd_SET_GLOBAL_OFFSET(self, gcmd):
435 | x_pos = gcmd.get_float('X', None)
436 | x_adjust = gcmd.get_float('X_ADJUST', None)
437 | y_pos = gcmd.get_float('Y', None)
438 | y_adjust = gcmd.get_float('Y_ADJUST', None)
439 | z_pos = gcmd.get_float('Z', None)
440 | z_adjust = gcmd.get_float('Z_ADJUST', None)
441 |
442 | if x_pos is not None:
443 | self.global_offset[0] = float(x_pos)
444 | elif x_adjust is not None:
445 | self.global_offset[0] = float(self.global_offset[0]) + float(x_adjust)
446 | if y_pos is not None:
447 | self.global_offset[1] = float(y_pos)
448 | elif y_adjust is not None:
449 | self.global_offset[1] = float(self.global_offset[1]) + float(y_adjust)
450 | if z_pos is not None:
451 | self.global_offset[2] = float(z_pos)
452 | elif z_adjust is not None:
453 | self.global_offset[2] = float(self.global_offset[2]) + float(z_adjust)
454 |
455 | self.log.trace("Global offset now set to: %f, %f, %f." % (float(self.global_offset[0]), float(self.global_offset[1]), float(self.global_offset[2])))
456 |
457 | cmd_SET_PURGE_ON_TOOLCHANGE_help = "Set the global variable if the tool should be purged or primed with filament at toolchange."
458 | def cmd_SET_PURGE_ON_TOOLCHANGE(self, gcmd = None):
459 | param = gcmd.get('VALUE', 'FALSE')
460 |
461 | if param.upper() == 'FALSE' or param == '0':
462 | self.purge_on_toolchange = False
463 | else:
464 | self.purge_on_toolchange = True
465 |
466 | def SaveFanSpeed(self, fanspeed):
467 | self.saved_fan_speed = float(fanspeed)
468 |
469 | cmd_SAVE_POSITION_help = "Save the specified G-Code position."
470 | # Sets the Restore type and saves specified position.
471 | # With no parameters it will set Restore type to 0, no restore.
472 | # Othervise will restore what is saved.
473 | def cmd_SAVE_POSITION(self, gcmd):
474 | param_X = gcmd.get_float('X', None)
475 | param_Y = gcmd.get_float('Y', None)
476 | param_Z = gcmd.get_float('Z', None)
477 | self.SavePosition(param_X, param_Y, param_Z)
478 |
479 | def SavePosition(self, param_X = None, param_Y = None, param_Z = None):
480 | self.saved_position = [param_X, param_Y, param_Z]
481 | restore_axis = ''
482 | if param_X is not None:
483 | restore_axis += 'X'
484 | if param_Y is not None:
485 | restore_axis += 'Y'
486 | if param_Z is not None:
487 | restore_axis += 'Z'
488 | self.restore_axis_on_toolchange = restore_axis
489 |
490 | cmd_SAVE_CURRENT_POSITION_help = "Save the current G-Code position."
491 | # Saves current position.
492 | # RESTORE_POSITION_TYPE= Type of restore, optional. If not specified, restore_axis_on_toolchange will not be changed.
493 | # 0: No restore
494 | # 1: Restore XY
495 | # 2: Restore XYZ
496 | # XYZ: Restore specified axis
497 |
498 | def cmd_SAVE_CURRENT_POSITION(self, gcmd):
499 | # Save optional RESTORE_POSITION_TYPE parameter to restore_axis_on_toolchange variable.
500 | restore_axis = parse_restore_type(gcmd, 'RESTORE_POSITION_TYPE')
501 | self.SaveCurrentPosition(restore_axis)
502 |
503 | def SaveCurrentPosition(self, restore_axis = None):
504 | if restore_axis is not None:
505 | self.restore_axis_on_toolchange = restore_axis
506 | gcode_move = self.printer.lookup_object('gcode_move')
507 | self.saved_position = gcode_move._get_gcode_position()
508 |
509 | cmd_RESTORE_POSITION_help = "Restore a previously saved G-Code position if it was specified in the toolchange T# command."
510 | # Restores the previously saved possition according to
511 | # With no parameters it will Restore to previousley saved type.
512 | # RESTORE_POSITION_TYPE= Type of restore, optional. If not specified, previousley saved restore_axis_on_toolchange will be used.
513 | # 0: No restore
514 | # 1: Restore XY
515 | # 2: Restore XYZ
516 | # XYZ: Restore specified axis
517 | def cmd_RESTORE_POSITION(self, gcmd):
518 | self.restore_axis_on_toolchange = parse_restore_type(gcmd, 'RESTORE_POSITION_TYPE', default=self.restore_axis_on_toolchange)
519 | self.log.trace("cmd_RESTORE_POSITION running: " + str(self.restore_axis_on_toolchange))
520 | speed = gcmd.get_int('F', None)
521 |
522 | if not self.restore_axis_on_toolchange:
523 | return # No axis to restore
524 | if self.saved_position is None:
525 | raise gcmd.error("No previously saved g-code position.")
526 |
527 | try:
528 | p = self.saved_position
529 | cmd = 'G1'
530 | for t in self.restore_axis_on_toolchange:
531 | cmd += ' %s%.3f' % (t, p[XYZ_TO_INDEX[t]])
532 | if speed:
533 | cmd += " F%i" % (speed,)
534 | # Restore position
535 | self.log.trace("cmd_RESTORE_POSITION running: " + cmd)
536 | self.gcode.run_script_from_command(cmd)
537 | except:
538 | raise gcmd.error("Could not restore position.")
539 |
540 | def get_status(self, eventtime= None):
541 | status = {
542 | "global_offset": self.global_offset,
543 | "tool_current": self.tool_current,
544 | "saved_fan_speed": self.saved_fan_speed,
545 | "purge_on_toolchange": self.purge_on_toolchange,
546 | "restore_axis_on_toolchange": self.restore_axis_on_toolchange,
547 | "saved_position": self.saved_position,
548 | "last_endstop_query": self.last_endstop_query
549 | }
550 | return status
551 |
552 | cmd_KTCC_SET_GCODE_OFFSET_FOR_CURRENT_TOOL_help = "Set G-Code offset to the one of current tool."
553 | # Sets the G-Code offset to the one of the current tool.
554 | # With no parameters it will not move the toolhead.
555 | # MOVE= If should move the toolhead, optional. If not specified, it will not move.
556 | # 0: No move
557 | # 1: Move
558 | def cmd_KTCC_SET_GCODE_OFFSET_FOR_CURRENT_TOOL(self, gcmd):
559 | current_tool_id = int(self.get_status()['tool_current']) # int(self.toollock.get_tool_current())
560 |
561 | self.log.trace("Setting offsets to those of T" + str(current_tool_id) + ".")
562 |
563 | if current_tool_id <= self.TOOL_UNLOCKED:
564 | msg = "KTCC_SET_GCODE_OFFSET_FOR_CURRENT_TOOL: Unknown tool mounted. Can't set offsets."
565 | self.log.always(msg)
566 | # raise self.printer.command_error(msg)
567 | else:
568 | # If optional MOVE parameter is passed as 0 or 1
569 | param_Move = gcmd.get_int('MOVE', 0, minval=0, maxval=1)
570 | current_tool = self.printer.lookup_object('tool ' + str(current_tool_id))
571 | self.log.trace("SET_GCODE_OFFSET X=%s Y=%s Z=%s MOVE=%s" % (str(current_tool.offset[0]), str(current_tool.offset[1]), str(current_tool.offset[2]), str(param_Move)))
572 | self.gcode.run_script_from_command("SET_GCODE_OFFSET X=%s Y=%s Z=%s MOVE=%s" % (str(current_tool.offset[0]), str(current_tool.offset[1]), str(current_tool.offset[2]), str(param_Move)))
573 |
574 |
575 | ###########################################
576 | # TOOL REMAPING #
577 | ###########################################
578 |
579 | def _set_tool_to_tool(self, from_tool, to_tool):
580 | #Check first if to_tool is a valid tool.
581 | tools = self.printer.lookup_objects('tool')
582 | if not [item for item in tools if item[0] == ("tool " + str(to_tool))]:
583 | self.log.always("Tool %s not a valid tool" % str(to_tool))
584 | return False
585 |
586 | # Set the new tool.
587 | self.tool_map[from_tool] = to_tool
588 | self.gcode.run_script_from_command("SAVE_VARIABLE VARIABLE=%s VALUE='%s'" % (self.VARS_KTCC_TOOL_MAP, self.tool_map))
589 |
590 | def _tool_map_to_human_string(self):
591 | msg = "Number of tools remaped: " + str(len(self.tool_map))
592 |
593 | for from_tool, to_tool in self.tool_map.items():
594 | msg += "\nTool %s-> Tool %s" % ( str(from_tool), str(to_tool))
595 |
596 | return msg
597 |
598 | def tool_is_remaped(self, tool_to_check):
599 | if tool_to_check in self.tool_map:
600 | return self.tool_map[tool_to_check]
601 | else:
602 | return -1
603 |
604 | def _remap_tool(self, tool, gate, available):
605 | self._set_tool_to_tool(tool, gate)
606 | # self._set_tool_status(gate, available)
607 |
608 | def _reset_tool_mapping(self):
609 | self.log.debug("Resetting Tool map")
610 | self.tool_map = {}
611 | self.gcode.run_script_from_command("SAVE_VARIABLE VARIABLE=%s VALUE='%s'" % (self.VARS_KTCC_TOOL_MAP, self.tool_map))
612 |
613 | ### GCODE COMMANDS FOR TOOL REMAP LOGIC ##################################
614 |
615 | cmd_KTCC_DISPLAY_TOOL_MAP_help = "Display the current mapping of tools to other KTCC tools." # Used with endless spool" in the future
616 | def cmd_KTCC_DISPLAY_TOOL_MAP(self, gcmd):
617 | summary = gcmd.get_int('SUMMARY', 0, minval=0, maxval=1)
618 | self.log.always(self._tool_map_to_human_string())
619 |
620 | cmd_KTCC_REMAP_TOOL_help = "Remap a tool to another one."
621 | def cmd_KTCC_REMAP_TOOL(self, gcmd):
622 | reset = gcmd.get_int('RESET', 0, minval=0, maxval=1)
623 | if reset == 1:
624 | self._reset_tool_mapping()
625 | else:
626 | from_tool = gcmd.get_int('TOOL', -1, minval=0)
627 | to_tool = gcmd.get_int('SET', minval=0)
628 | available = 1 #gcmd.get_int('AVAILABLE', -1, minval=0, maxval=1) #For future endless spool mode.
629 | # if available == -1:
630 | # available = self.tool_status[to_tool]
631 | if from_tool != -1:
632 | self._remap_tool(from_tool, to_tool, available)
633 | # else:
634 | # self._set_tool_status(to_tool, available)
635 | self.log.info(self._tool_map_to_human_string())
636 |
637 | ### GCODE COMMANDS FOR witing on endstop (Jubilee sytle toollock) ##################################
638 |
639 | cmd_KTCC_ENDSTOP_QUERY_help = "Wait for a ENDSTOP= untill it is TRIGGERED=0/[1] or ATEMPTS=#"
640 | def cmd_KTCC_ENDSTOP_QUERY(self, gcmd):
641 | endstop_name = gcmd.get('ENDSTOP') #'manual_stepper tool_lock'
642 | should_be_triggered = bool(gcmd.get_int('TRIGGERED', 1, minval=0, maxval=1))
643 | atempts = gcmd.get_int('ATEMPTS', -1, minval=1)
644 | self.query_endstop(endstop_name, should_be_triggered, atempts)
645 |
646 | def query_endstop(self, endstop_name, should_be_triggered=True, atempts=-1):
647 | # Get endstops
648 | endstop = None
649 | query_endstops = self.printer.lookup_object('query_endstops')
650 | for es, name in query_endstops.endstops:
651 | if name == endstop_name:
652 | endstop = es
653 | break
654 | if endstop is None:
655 | raise Exception("Unknown endstop '%s'" % (endstop_name))
656 |
657 | toolhead = self.printer.lookup_object("toolhead")
658 | eventtime = self.reactor.monotonic()
659 |
660 | dwell = 0.1
661 | if atempts == -1:
662 | dwell = 1.0
663 |
664 | i=0
665 | while not self.printer.is_shutdown():
666 | i += 1
667 | last_move_time = toolhead.get_last_move_time()
668 | is_triggered = bool(endstop.query_endstop(last_move_time))
669 | self.log.trace("Check #%d of %s endstop: %s" % (i, endstop_name, ("Triggered" if is_triggered else "Not Triggered")))
670 | if is_triggered == should_be_triggered:
671 | break
672 | # If not running continuesly then check for atempts.
673 | if atempts > 0 and atempts <= i:
674 | break
675 | eventtime = self.reactor.pause(eventtime + dwell)
676 | # if i > 1 or atempts == 1:
677 | # self.log.debug("Endstop %s is %s Triggered after #%d checks." % (endstop_name, ("" if is_triggered else "Not"), i))
678 |
679 | self.last_endstop_query[endstop_name] = is_triggered
680 |
681 | # parses legacy type into string of axis names.
682 | # Raises gcode error on fail
683 | def parse_restore_type(gcmd, arg_name, default = None):
684 | type = gcmd.get(arg_name, None)
685 | if type is None:
686 | return default
687 | elif type == '0':
688 | return ''
689 | elif type == '1':
690 | return 'XY'
691 | elif type == '2':
692 | return 'XYZ'
693 | # Validate this is XYZ
694 | for c in type:
695 | if c not in XYZ_TO_INDEX:
696 | raise gcmd.error("Invalid RESTORE_POSITION_TYPE")
697 | return type
698 |
699 | XYZ_TO_INDEX = {'x': 0, 'X':0, 'y':1, 'Y': 1, 'z': 2, 'Z':2}
700 | INDEX_TO_XYZ = ['X','Y','Z']
701 |
702 |
703 | def load_config(config):
704 | return ToolLock(config)
705 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/ktcclog.py:
--------------------------------------------------------------------------------
1 | # KTCC - Klipper Tool Changer Code
2 | # Log and statistics module
3 | #
4 | # Copyright (C) 2023 Andrei Ignat
5 | #
6 | # Based on and inspired by ERCF-Software-V3 Copyright (C) 2021 moggieuk#6538 (discord)
7 | #
8 | # This file may be distributed under the terms of the GNU GPLv3 license.
9 | #
10 |
11 | # To try to keep terms apart:
12 | # Mount: Tool is selected and loaded for use, be it a physical or a virtual on physical.
13 | # Unmopunt: Tool is unselected and unloaded, be it a physical or a virtual on physical.
14 | # Pickup: Tool is physically picked up and attached to the toolchanger head.
15 | # Droppoff: Tool is physically parked and dropped of the toolchanger head.
16 | # ToolLock: Toollock is engaged.
17 | # ToolUnLock: Toollock is disengaged.
18 |
19 | import logging, logging.handlers, threading, queue, time
20 | import math, os.path, copy
21 |
22 | # Forward all messages through a queue (polled by background thread)
23 | class KtccQueueHandler(logging.Handler):
24 | def __init__(self, queue):
25 | logging.Handler.__init__(self)
26 | self.queue = queue
27 |
28 | def emit(self, record):
29 | try:
30 | self.format(record)
31 | record.msg = record.message
32 | record.args = None
33 | record.exc_info = None
34 | self.queue.put_nowait(record)
35 | except Exception:
36 | self.handleError(record)
37 |
38 | # Poll log queue on background thread and log each message to logfile
39 | class KtccQueueListener(logging.handlers.TimedRotatingFileHandler):
40 | def __init__(self, filename):
41 | logging.handlers.TimedRotatingFileHandler.__init__(
42 | self, filename, when='midnight', backupCount=5)
43 | self.bg_queue = queue.Queue()
44 | self.bg_thread = threading.Thread(target=self._bg_thread)
45 | self.bg_thread.start()
46 |
47 | def _bg_thread(self):
48 | while True:
49 | record = self.bg_queue.get(True)
50 | if record is None:
51 | break
52 | self.handle(record)
53 |
54 | def stop(self):
55 | self.bg_queue.put_nowait(None)
56 | self.bg_thread.join()
57 |
58 | # Class to improve formatting of multi-line KTCC messages
59 | class KtccMultiLineFormatter(logging.Formatter):
60 | def format(self, record):
61 | indent = ' ' * 9
62 | lines = super(KtccMultiLineFormatter, self).format(record)
63 | return lines.replace('\n', '\n' + indent)
64 |
65 | class KtccLog:
66 | TOOL_UNKNOWN = -2
67 | TOOL_UNLOCKED = -1
68 | EMPTY_TOOL_STATS = {'toolmounts_completed': 0, 'toolunmounts_completed': 0, 'toolmounts_started': 0, 'toolunmounts_started': 0, 'time_selected': 0, 'time_heater_active': 0, 'time_heater_standby': 0, 'tracked_start_time_selected':0, 'tracked_start_time_active':0, 'tracked_start_time_standby':0, 'total_time_spent_unmounting':0, 'total_time_spent_mounting':0}
69 | KTCC_TOOL_STATISTICS_PREFIX = "ktcc_statistics_tool"
70 |
71 | def __init__(self, config):
72 | self.config = config
73 | self.gcode = config.get_printer().lookup_object('gcode')
74 | self.printer = config.get_printer()
75 | self.reactor = self.printer.get_reactor()
76 |
77 | self.printer.register_event_handler('klippy:connect', self.handle_connect)
78 | self.printer.register_event_handler("klippy:disconnect", self.handle_disconnect)
79 | self.printer.register_event_handler("klippy:ready", self.handle_ready)
80 |
81 | # Logging
82 | self.log_level = config.getint('log_level', 1, minval=0, maxval=3)
83 | self.logfile_level = config.getint('logfile_level', 3, minval=-1, maxval=4)
84 | self.log_statistics = config.getint('log_statistics', 0, minval=0, maxval=1)
85 | self.log_visual = config.getint('log_visual', 1, minval=0, maxval=2)
86 |
87 | # Logging
88 | self.queue_listener = None
89 | self.ktcc_logger = None
90 |
91 | # Save to file
92 | self.changes_to_save = False
93 | self.save_delay = 10
94 | self.save_active = True
95 |
96 | # Register commands
97 | handlers = [
98 | 'KTCC_LOG_TRACE', 'KTCC_LOG_DEBUG', 'KTCC_LOG_INFO', 'KTCC_LOG_ALWAYS',
99 | 'KTCC_SET_LOG_LEVEL', 'KTCC_DUMP_STATS', 'KTCC_RESET_STATS',
100 | 'KTCC_INIT_PRINT_STATS', 'KTCC_DUMP_PRINT_STATS']
101 | for cmd in handlers:
102 | func = getattr(self, 'cmd_' + cmd)
103 | desc = getattr(self, 'cmd_' + cmd + '_help', None)
104 | self.gcode.register_command(cmd, func, False, desc)
105 |
106 | def handle_ready(self):
107 | self.always('KlipperToolChangerCode Ready')
108 |
109 | # Wraping G28 and wait for temperature so we don't try sending gcode commands to save state while the gcode is blocked.
110 | # Need to do it outermost so that any G28 macros are used too.
111 | # When inside a G28 the parser won't run any SAVE_VARIABLE resulting in Klipper
112 | try:
113 | self.toolhead = self.printer.lookup_object('toolhead')
114 |
115 | self.prev_G28 = self.gcode.register_command("G28", None)
116 | self.gcode.register_command("G28", self.cmd_KTCC_G28, desc = self.cmd_KTCC_G28_help)
117 | except Exception as e:
118 | logging.exception('KTCC Warning: Error trying to wrap G28 macro: %s' % str(e))
119 |
120 | cmd_KTCC_G28_help = "Homing axes."
121 | def cmd_KTCC_G28(self, gcmd):
122 | # self.trace("Starting G28")
123 | self.save_active = False # Don't try to use SAVE_VARIABLE commands.
124 | self.prev_G28(gcmd)
125 | self.save_active = True # Resume to use SAVE_VARIABLE commands.
126 | # self.trace("Ending G28")
127 |
128 | def _save_changes_timer_event(self, eventtime):
129 | try:
130 | if self.save_active and self.changes_to_save:
131 | self.changes_to_save = False
132 | self.trace("Saving state in logs.")
133 |
134 | self._persist_swap_statistics()
135 | self._persist_tool_statistics()
136 | except Exception as e:
137 | self.debug("_save_changes_timer_event:Exception: %s" % (str(e)))
138 | logging.exception("_save_changes_timer_event:Exception: %s" % (str(e)))
139 | nextwake = eventtime + self.save_delay
140 | return nextwake
141 |
142 | def handle_connect(self):
143 | # Load saved variables
144 | self.variables = self.printer.lookup_object('save_variables').allVariables
145 |
146 | # Setup background file based logging before logging any messages
147 | if self.logfile_level >= 0:
148 | logfile_path = self.printer.start_args['log_file']
149 | dirname = os.path.dirname(logfile_path)
150 | if dirname == None:
151 | ktcc_log = '/tmp/ktcc.log'
152 | else:
153 | ktcc_log = dirname + '/ktcc.log'
154 | self.debug("ktcc_log=%s" % ktcc_log)
155 | self.queue_listener = KtccQueueListener(ktcc_log)
156 | self.queue_listener.setFormatter(KtccMultiLineFormatter('%(asctime)s %(message)s', datefmt='%I:%M:%S'))
157 | queue_handler = KtccQueueHandler(self.queue_listener.bg_queue)
158 | self.ktcc_logger = logging.getLogger('ktcc')
159 | self.ktcc_logger.setLevel(logging.INFO)
160 | self.ktcc_logger.addHandler(queue_handler)
161 |
162 | # Load saved values
163 | self._load_persisted_state()
164 |
165 | # Init persihabele statistics
166 | self._reset_print_statistics()
167 |
168 | # Set up timer to save values when needed
169 | self.timer_save = self.reactor.register_timer(
170 | self._save_changes_timer_event, self.reactor.monotonic() + (self.save_delay))
171 |
172 | def handle_disconnect(self):
173 | self.always('KTCC Shutdown')
174 | self.reactor.update_timer(self.timer_save, self.reactor.NEVER)
175 | if self.queue_listener != None:
176 | self.queue_listener.stop()
177 |
178 | def _load_persisted_state(self):
179 | swap_stats = self.variables.get("ktcc_statistics_swaps", {})
180 | try:
181 | if swap_stats is None or swap_stats == {}:
182 | raise Exception("Couldn't find any saved statistics.")
183 | # self.trace("Loading statistics for KTCC: %s" % str(swap_stats))
184 | # self.total_mounts = swap_stats['total_mounts'] or 0
185 | self.total_time_spent_mounting = swap_stats['total_time_spent_mounting'] or 0
186 | self.total_time_spent_unmounting = swap_stats['total_time_spent_unmounting'] or 0
187 | self.total_toollocks = swap_stats['total_toollocks'] or 0
188 | self.total_toolunlocks = swap_stats['total_toolunlocks'] or 0
189 | self.total_toolmounts = swap_stats['total_toolmounts'] or 0
190 | self.total_toolunmounts = swap_stats['total_toolunmounts'] or 0
191 | except Exception:
192 | # Initializing statistics
193 | self._reset_statistics()
194 |
195 | self.tool_statistics = {}
196 | for tool in self.printer.lookup_objects('tool'):
197 | try:
198 | toolname=str(tool[0])
199 | toolname=toolname[toolname.rindex(' ')+1:]
200 | self.tool_statistics[toolname] = self.variables.get("%s%s" % (self.KTCC_TOOL_STATISTICS_PREFIX, toolname), self.EMPTY_TOOL_STATS.copy())
201 | self.tool_statistics[toolname]["tracked_start_time_selected"] = 0
202 | self.tool_statistics[toolname]["tracked_start_time_active"] = 0
203 | self.tool_statistics[toolname]["tracked_start_time_standby"] = 0
204 | self.tool_statistics[toolname]["tracked_unmount_start_time"] = 0
205 | self.tool_statistics[toolname]["tracked_mount_start_time"] = 0
206 |
207 | except Exception as err:
208 | self.debug("Unexpected error in toolstast: %s" % err)
209 |
210 | def _reset_print_statistics(self):
211 | # Init persihabele statistics
212 | self.print_time_spent_mounting = self.total_time_spent_mounting
213 | self.print_time_spent_unmounting = self.total_time_spent_unmounting
214 | self.print_toollocks = self.total_toollocks
215 | self.print_toolunlocks = self.total_toolunlocks
216 | self.print_toolmounts = self.total_toolmounts
217 | self.print_toolunmounts = self.total_toolunmounts
218 | self.print_tool_statistics = copy.deepcopy(self.tool_statistics)
219 |
220 | ####################################
221 | # LOGGING FUNCTIONS #
222 | ####################################
223 | def get_status(self, eventtime):
224 | return {'encoder_pos': "?"}
225 |
226 | def always(self, message):
227 | if self.ktcc_logger:
228 | self.ktcc_logger.info(message)
229 | self.gcode.respond_info(message)
230 |
231 | def info(self, message):
232 | if self.ktcc_logger and self.logfile_level > 0:
233 | self.ktcc_logger.info(message)
234 | if self.log_level > 0:
235 | self.gcode.respond_info(message)
236 |
237 | def debug(self, message):
238 | message = "- DEBUG: %s" % message
239 | if self.ktcc_logger and self.logfile_level > 1:
240 | self.ktcc_logger.info(message)
241 | if self.log_level > 1:
242 | self.gcode.respond_info(message)
243 |
244 | def trace(self, message):
245 | message = "- - TRACE: %s" % message
246 | if self.ktcc_logger and self.logfile_level > 2:
247 | self.ktcc_logger.info(message)
248 | if self.log_level > 2:
249 | self.gcode.respond_info(message)
250 |
251 | # Fun visual display of KTCC state
252 | def _display_visual_state(self):
253 | if self.log_visual > 0 and not self.calibrating:
254 | self.always(self._state_to_human_string())
255 |
256 | def _log_level_to_human_string(self, level):
257 | log = "OFF"
258 | if level > 2: log = "TRACE"
259 | elif level > 1: log = "DEBUG"
260 | elif level > 0: log = "INFO"
261 | elif level > -1: log = "ESSENTIAL MESSAGES"
262 | return log
263 |
264 | def _visual_log_level_to_human_string(self, level):
265 | log = "OFF"
266 | if level > 1: log = "SHORT"
267 | elif level > 0: log = "LONG"
268 | return log
269 |
270 |
271 |
272 | ####################################
273 | # STATISTICS FUNCTIONS #
274 | ####################################
275 | def _reset_statistics(self):
276 | self.debug("Reseting KTCC statistics.")
277 | # self.total_mounts = 0
278 | self.total_time_spent_mounting = 0
279 | self.total_time_spent_unmounting = 0
280 | self.tracked_mount_start_time = 0
281 | # self.tracked_unmount_start_time = 0
282 | self.pause_start_time = 0
283 | self.total_toollocks = 0
284 | self.total_toolunlocks = 0
285 | self.total_toolmounts = 0
286 | self.total_toolunmounts = 0
287 |
288 | self.tool_statistics = {}
289 | for tool in self.printer.lookup_objects('tool'):
290 | try:
291 | toolname=str(tool[0])
292 | toolname=toolname[toolname.rindex(' ')+1:]
293 | self.tool_statistics[toolname] = self.EMPTY_TOOL_STATS.copy()
294 | self.tool_statistics[toolname]["tracked_start_time_selected"] = 0
295 | self.tool_statistics[toolname]["tracked_start_time_active"] = 0
296 | self.tool_statistics[toolname]["tracked_start_time_standby"] = 0
297 | self.tool_statistics[toolname]["tracked_unmount_start_time"] = 0
298 | self.tool_statistics[toolname]["tracked_mount_start_time"] = 0
299 |
300 | except Exception as err:
301 | self.debug("Unexpected error in toolstast: %s" % err)
302 |
303 |
304 | def track_mount_start(self, tool_id):
305 | self.trace("track_mount_start: Running for Tool: %s." % (tool_id))
306 | self._set_tool_statistics(tool_id, 'tracked_mount_start_time', time.time())
307 |
308 |
309 | def track_mount_end(self, tool_id):
310 | self.trace("track_mount_end: Running for Tool: %s." % (tool_id))
311 | start_time = self.tool_statistics[str(tool_id)]['tracked_mount_start_time']
312 | if start_time is not None and start_time != 0:
313 | # self.trace("track_mount_end: start_time is not None for Tool: %s." % (tool_id))
314 | time_spent = time.time() - start_time
315 | self.increase_tool_statistics(tool_id, 'total_time_spent_mounting', time_spent)
316 | self.total_time_spent_mounting += time_spent
317 | self._set_tool_statistics(tool_id, 'tracked_mount_start_time', 0)
318 | self.changes_to_save = True
319 |
320 | def track_unmount_start(self, tool_id):
321 | self.trace("track_unmount_start: Running for Tool: %s." % (tool_id))
322 | self._set_tool_statistics(tool_id, 'tracked_unmount_start_time', time.time())
323 | self.increase_tool_statistics(tool_id, 'toolunmounts_started')
324 |
325 | def track_unmount_end(self, tool_id):
326 | self.trace("track_unmount_end: Running for Tool: %s." % (tool_id))
327 | start_time = self.tool_statistics[str(tool_id)]['tracked_unmount_start_time']
328 | if start_time is not None and start_time != 0:
329 | # self.trace("track_unmount_end: start_time is not None for Tool: %s." % (tool_id))
330 | time_spent = time.time() - start_time
331 | self.increase_tool_statistics(tool_id, 'total_time_spent_unmounting', time_spent)
332 | self.total_time_spent_unmounting += time_spent
333 | self._set_tool_statistics(tool_id, 'tracked_unmount_start_time', 0)
334 | self.increase_tool_statistics(tool_id, 'toolunmounts_completed')
335 | self.increase_statistics('total_toolunmounts')
336 | self.changes_to_save = True
337 |
338 |
339 | def increase_statistics(self, key, count=1):
340 | try:
341 | self.trace("increase_statistics: Running. Provided to record tool stats while key: %s and count: %s" % (str(key), str(count)))
342 | if key == 'total_toolmounts':
343 | self.total_toolmounts += int(count)
344 | elif key == 'total_toolunmounts':
345 | self.total_toolunmounts += int(count)
346 | elif key == 'total_toollocks':
347 | self.total_toollocks += int(count)
348 | elif key == 'total_toolunlocks':
349 | self.total_toolunlocks += int(count)
350 | self.changes_to_save = True
351 | except Exception as e:
352 | self.debug("Exception whilst tracking tool stats: %s" % str(e))
353 | self.debug("increase_statistics: Error while increasing stats while key: %s and count: %s" % (str(key), str(count)))
354 |
355 | def track_selected_tool_start(self, tool_id):
356 | self.trace("track_selected_tool_start: Running for Tool: %s." % (tool_id))
357 | self._set_tool_statistics(tool_id, 'tracked_start_time_selected', time.time())
358 | self.increase_statistics('total_toolmounts')
359 | self.increase_tool_statistics(tool_id, 'toolmounts_completed')
360 |
361 | def track_selected_tool_end(self, tool_id):
362 | self.trace("track_selected_tool_end: Running for Tool: %s." % (tool_id))
363 | self._set_tool_statistics_time_diff(tool_id, 'time_selected', 'tracked_start_time_selected')
364 | self.changes_to_save = True
365 |
366 | def track_active_heater_start(self, tool_id):
367 | self.trace("track_active_heater_start: Running for Tool: %s." % (tool_id))
368 | self._set_tool_statistics(tool_id, 'tracked_start_time_active', time.time())
369 |
370 | def track_active_heater_end(self, tool_id):
371 | self.trace("track_active_heater_end: Running for Tool: %s." % (tool_id))
372 | self._set_tool_statistics_time_diff(tool_id, 'time_heater_active', 'tracked_start_time_active')
373 | self.changes_to_save = True
374 |
375 | def track_standby_heater_start(self, tool_id):
376 | self.trace("track_standby_heater_start: Running for Tool: %s." % (tool_id))
377 | self._set_tool_statistics(tool_id, 'tracked_start_time_standby', time.time())
378 |
379 | def track_standby_heater_end(self, tool_id):
380 | self.trace("track_standby_heater_end: Running for Tool: %s." % (tool_id))
381 | self._set_tool_statistics_time_diff(tool_id, 'time_heater_standby', 'tracked_start_time_standby')
382 | self.changes_to_save = True
383 |
384 | def _seconds_to_human_string(self, seconds):
385 | result = ""
386 | hours = int(math.floor(seconds / 3600.))
387 | if hours >= 1:
388 | result += "%d hours " % hours
389 | minutes = int(math.floor(seconds / 60.) % 60)
390 | if hours >= 1 or minutes >= 1:
391 | result += "%d minutes " % minutes
392 | result += "%d seconds" % int((math.floor(seconds) % 60))
393 | return result
394 |
395 | def _swap_statistics_to_human_string(self):
396 | msg = "KTCC Statistics:"
397 | # msg += "\n%d swaps completed" % self.total_mounts
398 | msg += "\n%s spent mounting tools" % self._seconds_to_human_string(self.total_time_spent_mounting)
399 | msg += "\n%s spent unmounting tools" % self._seconds_to_human_string(self.total_time_spent_unmounting)
400 | msg += "\n%d tool locks completed" % self.total_toollocks
401 | msg += "\n%d tool unlocks completed" % self.total_toolunlocks
402 | msg += "\n%d tool mounts completed" % self.total_toolmounts
403 | msg += "\n%d tool unmounts completed" % self.total_toolunmounts
404 | return msg
405 |
406 | def _swap_print_statistics_to_human_string(self):
407 | msg = "KTCC Statistics for this print:"
408 | # msg += "\n%d swaps completed" % self.total_mounts
409 | msg += "\n%s spent mounting tools" % self._seconds_to_human_string(self.total_time_spent_mounting-self.print_time_spent_mounting)
410 | msg += "\n%s spent unmounting tools" % self._seconds_to_human_string(self.total_time_spent_unmounting-self.print_time_spent_unmounting)
411 | msg += "\n%d tool locks completed" % (self.total_toollocks-self.print_toollocks)
412 | msg += "\n%d tool unlocks completed" % (self.total_toolunlocks-self.print_toolunlocks)
413 | msg += "\n%d tool mounts completed" % (self.total_toolmounts-self.print_toolmounts)
414 | msg += "\n%d tool unmounts completed" % (self.total_toolunmounts-self.print_toolunmounts)
415 | return msg
416 |
417 | def _division(self, dividend, divisor):
418 | try:
419 | return dividend/divisor
420 | except ZeroDivisionError:
421 | return 0
422 |
423 | def _dump_statistics(self, report=False):
424 | if self.log_statistics or report:
425 | msg = "ToolChanger Statistics:\n"
426 | msg += self._swap_statistics_to_human_string()
427 | msg += "\n------------\n"
428 |
429 | msg += "Tool Statistics:\n"
430 |
431 | # First convert to int so we get right order.
432 | res = {int(k):v for k,v in self.tool_statistics.items()}
433 | for tid in res:
434 | tool_id= str(tid)
435 | msg += "Tool#%s:\n" % (tool_id)
436 | msg += "Completed %d out of %d mounts in %s. Average of %s per toolmount.\n" % (self.tool_statistics[tool_id]['toolmounts_completed'], self.tool_statistics[tool_id]['toolmounts_started'], self._seconds_to_human_string(self.tool_statistics[tool_id]['total_time_spent_mounting']), self._seconds_to_human_string(self._division(self.tool_statistics[tool_id]['total_time_spent_mounting'], self.tool_statistics[tool_id]['toolmounts_completed'])))
437 | msg += "Completed %d out of %d unmounts in %s. Average of %s per toolunmount.\n" % (self.tool_statistics[tool_id]['toolunmounts_completed'], self.tool_statistics[tool_id]['toolunmounts_started'], self._seconds_to_human_string(self.tool_statistics[tool_id]['total_time_spent_unmounting']), self._seconds_to_human_string(self._division(self.tool_statistics[tool_id]['total_time_spent_unmounting'], self.tool_statistics[tool_id]['toolunmounts_completed'])))
438 | msg += "%s spent selected." % self._seconds_to_human_string(self.tool_statistics[tool_id]['time_selected'])
439 | tool = self.printer.lookup_object("tool " + str(tool_id))
440 | if tool.is_virtual != True or tool.name==tool.physical_parent_id:
441 | if tool.extruder is not None:
442 | msg += " %s with active heater and %s with standby heater." % (self._seconds_to_human_string(self.tool_statistics[tool_id]['time_heater_active']), self._seconds_to_human_string(self.tool_statistics[tool_id]['time_heater_standby']))
443 | msg += "\n------------\n"
444 |
445 |
446 | self.always(msg)
447 |
448 | def _dump_print_statistics(self, report=False):
449 | if self.log_statistics or report:
450 | msg = "ToolChanger Statistics for this print:\n"
451 | msg += self._swap_print_statistics_to_human_string()
452 | msg += "\n------------\n"
453 |
454 | msg += "Tool Statistics for this print:\n"
455 |
456 | # First convert to int so we get right order.
457 | res = {int(k):v for k,v in self.tool_statistics.items()}
458 | for tid in res:
459 | tool_id= str(tid)
460 | ts = self.tool_statistics[tool_id]
461 | pts = self.print_tool_statistics[tool_id]
462 | msg += "Tool#%s:\n" % (tool_id)
463 | msg += "Completed %d out of %d mounts in %s. Average of %s per toolmount.\n" % ((ts['toolmounts_completed']-pts['toolmounts_completed']), (ts['toolmounts_started']-pts['toolmounts_started']), self._seconds_to_human_string(ts['total_time_spent_mounting']-pts['total_time_spent_mounting']), self._seconds_to_human_string(self._division((ts['total_time_spent_mounting']-pts['total_time_spent_mounting']), (ts['toolmounts_completed']-ts['toolmounts_completed']))))
464 | msg += "Completed %d out of %d unmounts in %s. Average of %s per toolunmount.\n" % (ts['toolunmounts_completed']-pts['toolunmounts_completed'], ts['toolunmounts_started']-pts['toolunmounts_started'], self._seconds_to_human_string(ts['total_time_spent_unmounting']-pts['total_time_spent_unmounting']), self._seconds_to_human_string(self._division(ts['total_time_spent_unmounting']-pts['total_time_spent_unmounting'], ts['toolunmounts_completed']-pts['toolunmounts_completed'])))
465 | msg += "%s spent selected. %s with active heater and %s with standby heater.\n" % (self._seconds_to_human_string(ts['time_selected']-pts['time_selected']), self._seconds_to_human_string(ts['time_heater_active']-pts['time_heater_active']), self._seconds_to_human_string(ts['time_heater_standby']-pts['time_heater_standby']))
466 | msg += "------------\n"
467 | self.always(msg)
468 |
469 |
470 |
471 | def _persist_swap_statistics(self):
472 | swap_stats = {
473 | # 'total_mounts': self.total_mounts,
474 | 'total_time_spent_mounting': round(self.total_time_spent_mounting, 1),
475 | 'total_time_spent_unmounting': round(self.total_time_spent_unmounting, 1),
476 | 'total_toolunlocks': self.total_toolunlocks,
477 | 'total_toollocks': self.total_toollocks,
478 | 'total_toolmounts': self.total_toolmounts,
479 | 'total_toolunmounts': self.total_toolunmounts
480 | }
481 | self.toolhead.wait_moves()
482 | self.gcode.run_script_from_command("SAVE_VARIABLE VARIABLE=%s VALUE=\"%s\"" % ("ktcc_statistics_swaps", swap_stats))
483 |
484 | def _persist_tool_statistics(self):
485 | for tool in self.tool_statistics:
486 | try:
487 | self.toolhead.wait_moves()
488 | self.gcode.run_script_from_command("SAVE_VARIABLE VARIABLE=%s%s VALUE=\"%s\"" % (self.KTCC_TOOL_STATISTICS_PREFIX, tool, self.tool_statistics[tool]))
489 | except Exception as err:
490 | self.debug("Unexpected error in _persist_tool_statistics: %s" % err)
491 |
492 | def increase_tool_statistics(self, tool_id, key, count=1):
493 | try:
494 | self.trace("increase_tool_statistics: Running for Tool: %s. Provided to record tool stats while key: %s and count: %s" % (tool_id, str(key), str(count)))
495 | # if self.tool_statistics.get(str(tool_id)) is not None:
496 | if str(tool_id) in self.tool_statistics:
497 | if self.tool_statistics[str(tool_id)][key] is None:
498 | self.tool_statistics[str(tool_id)][key]=0
499 | # self.trace("increase_tool_statistics: Before running for Tool: %s. Key: %s is: %s" % (tool_id, str(key), str(self.tool_statistics[str(tool_id)][key])))
500 | if isinstance(count, float):
501 | self.tool_statistics[str(tool_id)][key] = round(self.tool_statistics[str(tool_id)][key] + count, 3)
502 | else:
503 | self.tool_statistics[str(tool_id)][key] += count
504 | # self.trace("increase_tool_statistics: After running for Tool: %s. Key: %s is: %s" % (tool_id, str(key), str(self.tool_statistics[str(tool_id)][key])))
505 | else:
506 | self.debug("increase_tool_statistics: Unknown tool provided to record tool stats: %s" % tool_id)
507 | # self.debug(str(self.tool_statistics))
508 | except Exception as e:
509 | self.debug("Exception whilst tracking tool stats: %s" % str(e))
510 | self.debug("increase_tool_statistics: Error while tool: %s provided to record tool stats while key: %s and count: %s" % (tool_id, str(key), str(count)))
511 | # self.trace("increase_tool_statistics: Tool: %s provided to record tool stats while key: %s and count: %s" % (tool_id, str(key), str(count)))
512 |
513 | def _set_tool_statistics(self, tool_id, key, value):
514 | self.trace("_set_tool_statistics:Running for Tool: %s provided to record tool stats while key: %s and value: %s" % (tool_id, str(key), str(value)))
515 | try:
516 | if str(tool_id) in self.tool_statistics:
517 | self.tool_statistics[str(tool_id)][key] = value
518 | else:
519 | self.debug("_set_tool_statistics: Unknown tool: %s provided to record tool stats while key: %s and value: %s" % (tool_id, str(key), str(value)))
520 | except Exception as e:
521 | self.debug("Exception whilst tracking tool stats: %s" % str(e))
522 | self.debug("_set_tool_statistics: Error while tool: %s provided to record tool stats while key: %s and value: %s" % (tool_id, str(key), str(value)))
523 | # self.trace("_set_tool_statistics: Tool: %s provided to record tool stats while key: %s and value: %s" % (tool_id, str(key), str(value)))
524 |
525 | def _set_tool_statistics_time_diff(self, tool_id, final_time_key, start_time_key):
526 | try:
527 | if str(tool_id) in self.tool_statistics:
528 | tool_stat= self.tool_statistics[str(tool_id)]
529 | if tool_stat[start_time_key] is not None and tool_stat[start_time_key] != 0:
530 | # self.trace("_set_tool_statistics_time_diff: Tool: %s value before running: final_time_key: %s=%s, start_time_key: %s=%s." % (tool_id, final_time_key, str(tool_stat[final_time_key]), start_time_key, str(tool_stat[start_time_key])))
531 | if tool_stat[final_time_key] is not None and tool_stat[final_time_key] != 0:
532 | tool_stat[final_time_key] += time.time() - tool_stat[start_time_key]
533 | else:
534 | tool_stat[final_time_key] = time.time() - tool_stat[start_time_key]
535 | tool_stat[start_time_key] = 0
536 | else:
537 | self.debug("_set_tool_statistics_time_diff: Unknown tool: %s provided to record tool stats while final_time_key: %s and start_time_key: %s" % (tool_id, str(final_time_key), str(start_time_key)))
538 | except Exception as e:
539 | self.debug("Exception whilst tracking tool stats: %s" % str(e))
540 | self.debug("_set_tool_statistics_time_diff: Error while tool: %s provided to record tool stats while final_time_key: %s and start_time_key: %s" % (tool_id, str(final_time_key), str(start_time_key)))
541 | # self.trace("_set_tool_statistics_time_diff: Tool: %s value after running: final_time_key: %s=%s, start_time_key: %s=%s." % (tool_id, final_time_key, str(tool_stat[final_time_key]), start_time_key, str(tool_stat[start_time_key])))
542 |
543 | ### LOGGING AND STATISTICS FUNCTIONS GCODE FUNCTIONS
544 |
545 | cmd_KTCC_RESET_STATS_help = "Reset the KTCC statistics"
546 | def cmd_KTCC_RESET_STATS(self, gcmd):
547 | param = gcmd.get('SURE', "no")
548 | if param.lower() == "yes":
549 | self._reset_statistics()
550 | self._reset_print_statistics()
551 | self.changes_to_save = True
552 | self._dump_statistics(True)
553 | self.always("Statistics RESET.")
554 | else:
555 | message = "Are you sure you want to reset KTCC statistics?\n"
556 | message += "If so, run with parameter SURE=YES:\n"
557 | message += "KTCC_RESET_STATS SURE=YES"
558 | self.gcode.respond_info(message)
559 |
560 | cmd_KTCC_DUMP_STATS_help = "Dump the KTCC statistics"
561 | def cmd_KTCC_DUMP_STATS(self, gcmd):
562 | self._dump_statistics(True)
563 |
564 | cmd_KTCC_INIT_PRINT_STATS_help = "Run at start of a print to initialize the KTCC print statistics"
565 | def cmd_KTCC_INIT_PRINT_STATS(self, gcmd):
566 | self._reset_print_statistics()
567 |
568 | cmd_KTCC_DUMP_PRINT_STATS_help = "Run at end of a print to list statistics since last print reset."
569 | def cmd_KTCC_DUMP_PRINT_STATS(self, gcmd):
570 | self._dump_print_statistics(True)
571 |
572 | cmd_KTCC_SET_LOG_LEVEL_help = "Set the log level for the KTCC"
573 | def cmd_KTCC_SET_LOG_LEVEL(self, gcmd):
574 | self.log_level = gcmd.get_int('LEVEL', self.log_level, minval=0, maxval=4)
575 | self.logfile_level = gcmd.get_int('LOGFILE', self.logfile_level, minval=0, maxval=4)
576 | self.log_visual = gcmd.get_int('VISUAL', self.log_visual, minval=0, maxval=2)
577 | self.log_statistics = gcmd.get_int('STATISTICS', self.log_statistics, minval=0, maxval=1)
578 |
579 | cmd_KTCC_LOG_ALWAYS_help = "Log allways MSG"
580 | def cmd_KTCC_LOG_ALWAYS(self, gcmd):
581 | msg = gcmd.get('MSG')
582 | self.always(msg)
583 |
584 | cmd_KTCC_LOG_INFO_help = "Log info MSG"
585 | def cmd_KTCC_LOG_INFO(self, gcmd):
586 | msg = gcmd.get('MSG')
587 | self.info(msg)
588 |
589 | cmd_KTCC_LOG_DEBUG_help = "Log debug MSG"
590 | def cmd_KTCC_LOG_DEBUG(self, gcmd):
591 | msg = gcmd.get('MSG')
592 | self.debug(msg)
593 |
594 | cmd_KTCC_LOG_TRACE_help = "Log trace MSG"
595 | def cmd_KTCC_LOG_TRACE(self, gcmd):
596 | msg = gcmd.get('MSG')
597 | self.trace(msg)
598 |
599 | # def _get_print_status(self):
600 | # try:
601 | # # If using virtual sdcard this is the most reliable method
602 | # source = "print_stats"
603 | # print_status = self.printer.lookup_object("print_stats").get_status(self.printer.get_reactor().monotonic())['state']
604 | # except:
605 | # # Otherwise we fallback to idle_timeout
606 | # source = "idle_timeout"
607 | # if self.printer.lookup_object("pause_resume").is_paused:
608 | # print_status = "paused"
609 | # else:
610 | # idle_timeout = self.printer.lookup_object("idle_timeout").get_status(self.printer.get_reactor().monotonic())
611 | # if idle_timeout["printing_time"] < 1.0:
612 | # print_status = "standby"
613 | # else:
614 | # print_status = idle_timeout['state'].lower()
615 | # finally:
616 | # self.trace("Determined print status as: %s from %s" % (print_status, source))
617 | # return print_status
618 |
619 |
620 | # cmd_KTCC_STATUS_help = "Complete dump of current KTCC state and important configuration"
621 | # def cmd_KTCC_STATUS(self, gcmd):
622 | # config = gcmd.get_int('SHOWCONFIG', 0, minval=0, maxval=1)
623 | # msg = "KTCC with %d gates" % (len(self.selector_offsets))
624 | # msg += " is %s" % ("DISABLED" if not self.is_enabled else "PAUSED/LOCKED" if self.is_paused else "OPERATIONAL")
625 | # msg += " with the servo in a %s position" % ("UP" if self.servo_state == self.SERVO_UP_STATE else "DOWN" if self.servo_state == self.SERVO_DOWN_STATE else "unknown")
626 | # msg += ", Encoder reads %.2fmm" % self._counter.get_distance()
627 | # msg += "\nSelector is %shomed" % ("" if self.is_homed else "NOT ")
628 | # msg += ". Tool %s is selected " % self._selected_tool_string()
629 | # msg += " on gate %s" % self._selected_gate_string()
630 | # msg += ". Toolhead position saved pending resume" if self.saved_toolhead_position else ""
631 | # msg += "\nFilament position: %s" % self._state_to_human_string()
632 |
633 | # if config:
634 | # msg += "\n\nConfiguration:\nFilament homes"
635 | # if self._must_home_to_extruder():
636 | # if self.homing_method == self.EXTRUDER_COLLISION:
637 | # msg += " to EXTRUDER using COLLISION DETECTION (current %d%%)" % self.extruder_homing_current
638 | # else:
639 | # msg += " to EXTRUDER using STALLGUARD"
640 | # if self._has_toolhead_sensor():
641 | # msg += " and then"
642 | # msg += " to TOOLHEAD SENSOR" if self._has_toolhead_sensor() else ""
643 | # msg += " after a %.1fmm calibration reference length" % self._get_calibration_ref()
644 | # if self.sync_load_length > 0 or self.sync_unload_length > 0:
645 | # msg += "\nGear and Extruder steppers are synchronized during "
646 | # load = False
647 | # if self._has_toolhead_sensor() and self.sync_load_length > 0:
648 | # msg += "load (up to %.1fmm)" % (self.toolhead_homing_max)
649 | # load = True
650 | # elif self.sync_load_length > 0:
651 | # msg += "load (%.1fmm)" % (self.sync_load_length)
652 | # load = True
653 | # if self.sync_unload_length > 0:
654 | # msg += " and " if load else ""
655 | # msg += "unload (%.1fmm)" % (self.sync_unload_length)
656 | # else:
657 | # msg += "\nGear and Extruder steppers are not synchronized"
658 | # msg += ". Tip forming current is %d%%" % self.extruder_form_tip_current
659 | # msg += "\nSelector homing is %s - blocked gate detection and recovery %s possible" % (("sensorless", "may be") if self.sensorless_selector else ("microswitch", "is not"))
660 | # msg += "\nClog detection is %s" % ("ENABLED" if self.enable_clog_detection else "DISABLED")
661 | # msg += " and EndlessSpool is %s" % ("ENABLED" if self.enable_endless_spool else "DISABLED")
662 | # p = self.persistence_level
663 | # msg += ", %s state is persisted across restarts" % ("All" if p == 4 else "Gate status & TTG map & EndlessSpool groups" if p == 3 else "TTG map & EndlessSpool groups" if p == 2 else "EndlessSpool groups" if p == 1 else "No")
664 | # msg += "\nLogging levels: Console %d(%s)" % (self.log_level, self._log_level_to_human_string(self.log_level))
665 | # msg += ", Logfile %d(%s)" % (self.logfile_level, self._log_level_to_human_string(self.logfile_level))
666 | # msg += ", Visual %d(%s)" % (self.log_visual, self._visual_log_level_to_human_string(self.log_visual))
667 | # msg += ", Statistics %d(%s)" % (self.log_statistics, "ON" if self.log_statistics else "OFF")
668 | # msg += "\n\nTool/gate mapping%s" % (" and EndlessSpool groups:" if self.enable_endless_spool else ":")
669 | # msg += "\n%s" % self._tool_to_gate_map_to_human_string()
670 | # msg += "\n\n%s" % self._swap_statistics_to_human_string()
671 | # self._log_always(msg)
672 |
673 | def load_config(config):
674 | return KtccLog(config)
675 |
676 |
--------------------------------------------------------------------------------