├── doc
├── 085afe.png
├── 0fefa9.png
├── 1589F0.png
├── c5f015.png
├── f03c15.png
├── f98b00.png
├── fe3263.png
├── discord+ktc.png
├── TODO.md
├── state_ref.md
├── command_ref.md
└── configuration.md
├── .github
└── FUNDING.yml
├── macros
├── optional_rrf_compability
│ ├── G10.cfg
│ ├── M116.cfg
│ └── M568.cfg
└── base
│ ├── M107.cfg
│ ├── M104.cfg
│ ├── M106.cfg
│ └── M109.cfg
├── .vscode
└── settings.json
├── config
├── PrusaSlicer_Custom_Gcode.md
└── example_config
│ ├── TOOL_MACROS.cfg
│ ├── simple
│ └── simple_example.cfg
│ └── complete
│ └── complete_example.cfg
├── .gitignore
├── extensions
├── ktc_persisting.py
├── ktc_toolchanger.py
├── ktc_tool.py
├── ktc_heater.py
└── ktc_base.py
├── README.md
├── install.sh
├── Dev_doc.md
└── LICENSE
/doc/085afe.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/KTC/HEAD/doc/085afe.png
--------------------------------------------------------------------------------
/doc/0fefa9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/KTC/HEAD/doc/0fefa9.png
--------------------------------------------------------------------------------
/doc/1589F0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/KTC/HEAD/doc/1589F0.png
--------------------------------------------------------------------------------
/doc/c5f015.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/KTC/HEAD/doc/c5f015.png
--------------------------------------------------------------------------------
/doc/f03c15.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/KTC/HEAD/doc/f03c15.png
--------------------------------------------------------------------------------
/doc/f98b00.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/KTC/HEAD/doc/f98b00.png
--------------------------------------------------------------------------------
/doc/fe3263.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/KTC/HEAD/doc/fe3263.png
--------------------------------------------------------------------------------
/doc/discord+ktc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TypQxQ/KTC/HEAD/doc/discord+ktc.png
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: TypQxQ
4 |
--------------------------------------------------------------------------------
/macros/optional_rrf_compability/G10.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro G10]
2 | description: See M568. Passtrough to M568.
3 | gcode:
4 | M568 {rawparams}
--------------------------------------------------------------------------------
/macros/optional_rrf_compability/M116.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M116]
2 | description: [T | P | H] [S] [W]
3 | Alias for M109.
4 | gcode:
5 | M109 {rawparams}
--------------------------------------------------------------------------------
/macros/base/M107.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M107]
2 | description: [T | P]
3 | Turn off fan.
4 | T= Tool number (optional, defaults to the currently selected tool).
5 | P= Tool Number (Same as T. Use one or the other, not both).
6 | gcode:
7 | {% set newparameters = "" %} # Parameters to be passed on to subroutines.
8 |
9 | {% if params.P is defined %}
10 | {% set newparameters = " P"~params.P %}
11 | {% elif params.T is defined %}
12 | {% set newparameters = " P"~params.T %}
13 | {% endif %}
14 |
15 | M106{newparameters} S0
16 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "pylint.args": [
3 | "--disable=E0611",
4 | "--disable=C0410 ",
5 | "--disable=W0719",
6 | "--disable=C0209",
7 | "--disable=C0115",
8 | "--disable=C0116",
9 | "--disable=W0718",
10 | "--disable=C0114",
11 | "--disable=C0112",
12 | "--disable=W0201"
13 | ],
14 | "python.analysis.typeCheckingMode": "standard",
15 | // "python.analysis.extraPaths": [
16 | // "../klipper/klippy/"
17 | // ]
18 | "python.analysis.diagnosticSeverityOverrides": {
19 | "reportArgumentType": "none"
20 | },
21 | }
--------------------------------------------------------------------------------
/doc/TODO.md:
--------------------------------------------------------------------------------
1 | ##    Planed To do:
2 | - Mainsail integration
3 | - KlipperScreen integration
4 | - Add selectable automatic calculation of active times based on previous times. Ex:
5 | - Mean Layer time Standby mode. - Save time at every layerchange and at toolchange set to mean time of last 3 layers *2 or at last layer *1.5 with a Maximum and a minimum time. Needs to be analyzed further.
6 | - Save the time it was in Standby last time and apply a fuzzfactor. Put tool in standby and heatup with presumption that next time will be aproximatley after the same time as last. +/- Fuzzfactor.
7 |
--------------------------------------------------------------------------------
/macros/base/M104.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M104]
2 | rename_existing: M104.1
3 | description: [T | P] [S]
4 | Set tool temperature.
5 | T= Tool number (optional, defaults to the currently selected tool).
6 | P= Tool number (Same as T. Use one or the other, not both).
7 | S= Active temperature(s), optional. If this parameter is not provided, the temperature is set to 0.
8 | gcode:
9 | {% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
10 |
11 | # P= Tool number and optional T.
12 | {% if params.P is defined %}
13 | {% set newparameters = newparameters ~ " P="~params.P %}
14 | {% elif params.T is defined %}
15 | {% set newparameters = newparameters ~ " P="~params.T %}
16 | {% endif %}
17 |
18 | # S= Active temperature
19 | {% if params.S is defined %}
20 | {% set newparameters = newparameters ~ " ACTV_TMP="~params.S %}
21 | {% endif %}
22 |
23 | {action_respond_info("M104: Running: KTC_TOOL_SET_TEMPERATURE"~newparameters)}
24 | KTC_TOOL_SET_TEMPERATURE{newparameters}
25 |
--------------------------------------------------------------------------------
/macros/base/M106.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M106]
2 | variable_fan_speed: 0
3 | description: [T | P] [S]
4 | Set fan speed. A KTC tool must be configured for this to work.
5 | S= Fan speed 0-1 or 2-255 (optional, defult 1, full speed).
6 | T= Tool (optional, defaults to the currently selected tool).
7 | P= Tool (Same as T. Use one or the other, not both).
8 | The P parameter specifies tool instead of fan number as in RRF.
9 | If no S value is given, the fan speed is set to 1 (full speed).
10 | If no T or P value is given, the currently active tool is used.
11 | gcode:
12 | {% set newparameters = "" %} # Parameters to be passed on to subroutines in new format.
13 |
14 | # S= Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
15 | {% if params.S is defined %}
16 | {% set newparameters = newparameters ~ " S="~params.S %}
17 | {% endif %}
18 |
19 | # P= Tool number and optional T.
20 | {% if params.P is defined %}
21 | {% set newparameters = newparameters ~ " P="~params.P %}
22 | {% elif params.T is defined %}
23 | {% set newparameters = newparameters ~ " P="~params.T %}
24 | {% endif %}
25 |
26 | KTC_SET_AND_SAVE_PARTFAN_SPEED{newparameters}
27 |
--------------------------------------------------------------------------------
/config/PrusaSlicer_Custom_Gcode.md:
--------------------------------------------------------------------------------
1 | Here are the custom G-codes I use in PrusaSlicer on my ToolChanger as an example.
2 | This haven't been updated so use with caution
3 |
4 | Start G-code:
5 | - I don't heat the tools before actually using them so I don't degrade filament.
6 | - Using e3d Revo the heatup times for the tools are verry fast.
7 | ```
8 | KTCC_INIT_PRINT_STATS
9 |
10 | ; Heat the bed first
11 | M140 S[first_layer_bed_temperature]
12 | ; Wait for bed to reach temperature with 2 degrees tolerance
13 | M116 H0 W2
14 | M568 P[initial_extruder] R{if not is_nil(idle_temperature[initial_extruder])} R{idle_temperature[initial_extruder]}{else} R100{endif} S{first_layer_temperature[initial_extruder]} A1
15 |
16 | G28
17 |
18 | G0 Z3 F5000 ; Ensure nozzle is at 3mm over the bed
19 | T[initial_extruder] ; Mount extruder first used (even if only one extruder used). Waits for temperature inside the script.
20 | ```
21 |
22 | End G-code
23 | ```
24 | ; Custom gcode to run at end of print
25 | M104 S0 ; turn off temperature
26 | G10 P0 S0 R0 A0 ; turn off extruder 0
27 | G10 P1 S0 R0 A0 ; turn off extruder 1
28 | G10 P2 S0 R0 A0 ; turn off extruder 2
29 | M140 S0 ; turn off bed
30 | T_1 ; dropoff current tool
31 | G91 ; relative moves
32 | G0 Z20 ; move bed down another 30mm
33 | G90 ; absolute moves
34 | G0 X1 Y1 F30000 ; Move toolhead out of the way
35 | SAVE_POSITION ; Reset saved position.
36 | KTCC_DUMP_PRINT_STATS ; Print statistics to console.
37 | ```
38 |
39 | ToolChange G-code
40 | - Sets the temperature before activating the tool in case this is the first time the tool is selected.
41 | - On first layer it sets the temperature for the next tool to first layer temperature.
42 | ```
43 | {if layer_num < 1}M568 P[next_extruder] {if not is_nil(idle_temperature[initial_extruder])} R{idle_temperature[initial_extruder]}{else} R100{endif} S{first_layer_temperature[next_extruder]} A2 ;First layer temperature
44 | {else}M568 P[next_extruder] {if not is_nil(idle_temperature[initial_extruder])} R{idle_temperature[initial_extruder]}{else} R100{endif} S{first_layer_temperature[next_extruder]} A2 ;Other layer temperature
45 | {endif}
46 | G91 ; relative moves
47 | G0 Z1 ; move bed down 1mm to add a Z-hop style on toolchange.
48 | G90 ; absolute moves
49 | T{next_extruder} ; Actual ToolChange
50 | ```
51 |
--------------------------------------------------------------------------------
/macros/base/M109.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M109]
2 | rename_existing: M109.1
3 | description: [T | P | H] [S] [W]
4 | Turn off fan.
5 | T= Tool number (optional, defaults to the currently selected tool).
6 | P= Tool Number (Same as T. Use one or the other, not both).
7 | H= Heater number, optional. Defaults to 0. If H is specified, P and T are ignored.
8 | S= Temperature in degC to wait for. Used together with P or T. The command will set the active temperature of the specified tool to this value and set the tool to active mode.
9 | W= Tolerance in degC, optional. Wait will wait until heater is between set temperature +/- tolerance.
10 | Waits for all temperatures, or a specified tool or heater's temperature.
11 | This command can be used without any additional parameters.
12 | Without parameters it waits for bed and current extruder.
13 | Defaults to 1*C for faster response. Newer hardware is not as sensitive.
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 ~ " T=" ~ params.P %}
25 | {% elif params.T is defined %}
26 | {% set newparameters = newparameters ~ " T=" ~ 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 | # {action_respond_info("M109: Running: KTC_TOOL_SET_TEMPERATURE"~newTempParameters)}
33 | KTC_TOOL_SET_TEMPERATURE{newTempParameters}
34 | {% endif %}
35 |
36 | # W= Tolerance
37 | {% if params.W is defined %}
38 | {% set newparameters = newparameters ~ " TOLERANCE=" ~ params.W %} # Set Tolerance to new parameters.
39 | # {% else %}
40 | # {% set newparameters = newparameters ~ " TOLERANCE=1" %} # Set Tolerance to default of 1.
41 | {% endif %}
42 |
43 | {action_respond_info("M109: Running: KTC_TEMPERATURE_WAIT_WITH_TOLERANCE"~newparameters)}
44 | KTC_TEMPERATURE_WAIT_WITH_TOLERANCE{newparameters}
45 |
--------------------------------------------------------------------------------
/macros/optional_rrf_compability/M568.cfg:
--------------------------------------------------------------------------------
1 | [gcode_macro M568]
2 | description: [T | P] [S] [R] [A] [N] [O]
3 | Set tool temperature.
4 | T= Tool number (optional, defaults to the currently selected tool).
5 | P= Tool number (Same as T. Use one or the other, not both).
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.
10 | Use for example 0.1 to change immediately to standby temperature.
11 | O = Time in seconds to wait from being set in standby to turning off the heater.
12 | This is for example useful if the tool is not to be used for a long time.
13 | Use for example 86400 to wait 24h if you want to disable shutdown timer.
14 |
15 |
16 | gcode:
17 | # RESPOND MSG="M568: Seting new temperature: {rawparams}"
18 | {% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
19 |
20 | # P= Tool number
21 | {% if params.P is defined %}
22 | {% set newparameters = newparameters ~ " T=" ~ params.P %}
23 | {% elif params.T is defined %}
24 | {% set newparameters = newparameters ~ " T=" ~ params.T %}
25 | {% endif %}
26 |
27 | # R= Standby temperature
28 | {% if params.R is defined %}
29 | {% set newparameters = newparameters ~ " STDB_TMP="~params.R %} # Set heater_standby_temp to new parameters.
30 | {% endif %}
31 |
32 | # S= Active temperature
33 | {% if params.S is defined %}
34 | {% set newparameters = newparameters ~ " ACTV_TMP="~params.S %} # Set heater_active_temp to new parameters.
35 | {% endif %}
36 |
37 | # N = Time in seconds to wait from docking tool to putting the heater in standy
38 | {% if params.N is defined %}
39 | {% set newparameters = newparameters ~ " STDB_TIMEOUT="~params.N %} # Set heater_active_to_standby_delay to new parameters.
40 | {% endif %}
41 |
42 | # M = Time in seconds to wait from docking tool to shuting off the heater
43 | {% if params.O is defined %}
44 | {% set newparameters = newparameters ~ " SHTDWN_TIMEOUT="~params.O %} # Set heater_active_to_powerdown_delay to new parameters.
45 | {% endif %}
46 |
47 | # A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature
48 | {% if params.A is defined %}
49 | {% set newparameters = newparameters ~ " CHNG_STATE="~params.A %} # Set heater_active_to_powerdown_delay to new parameters.
50 | {% endif %}
51 |
52 | {action_respond_info("M568: Running: KTC_TOOL_SET_TEMPERATURE"~newparameters)}
53 | KTC_TOOL_SET_TEMPERATURE{newparameters}
54 |
--------------------------------------------------------------------------------
/config/example_config/TOOL_MACROS.cfg:
--------------------------------------------------------------------------------
1 | ########################################################################
2 | # Tool change macros for Mainsail compability
3 | #######################################################################
4 | [gcode_macro T_1]
5 | gcode: KTC_DESELECT_ALL
6 | [gcode_macro T0]
7 | variable_active: 0
8 | gcode: _SET_ACTIVE_TOOL TOOL=0
9 | [gcode_macro T1]
10 | variable_active: 0
11 | gcode: _SET_ACTIVE_TOOL TOOL=1
12 | [gcode_macro T2]
13 | variable_active: 0
14 | gcode: _SET_ACTIVE_TOOL TOOL=2
15 | [gcode_macro T3]
16 | variable_active: 0
17 | gcode: _SET_ACTIVE_TOOL TOOL=3
18 | [gcode_macro T4]
19 | variable_active: 0
20 | gcode: _SET_ACTIVE_TOOL TOOL=4
21 | [gcode_macro T5]
22 | variable_active: 0
23 | gcode: _SET_ACTIVE_TOOL TOOL=5
24 | [gcode_macro T6]
25 | variable_active: 0
26 | gcode: _SET_ACTIVE_TOOL TOOL=6
27 | [gcode_macro T7]
28 | variable_active: 0
29 | gcode: _SET_ACTIVE_TOOL TOOL=7
30 | [gcode_macro T8]
31 | variable_active: 0
32 | gcode: _SET_ACTIVE_TOOL TOOL=8
33 | [gcode_macro T9]
34 | variable_active: 0
35 | gcode: _SET_ACTIVE_TOOL TOOL=9
36 | [gcode_macro T10]
37 | variable_active: 0
38 | gcode: _SET_ACTIVE_TOOL TOOL=10
39 | [gcode_macro T11]
40 | variable_active: 0
41 | gcode: _SET_ACTIVE_TOOL TOOL=11
42 | [gcode_macro T49]
43 | variable_active: 0
44 | gcode: _SET_ACTIVE_TOOL TOOL=49
45 |
46 | [gcode_macro T20]
47 | variable_active: 0
48 | gcode: _SET_ACTIVE_TOOL TOOL=20
49 |
50 | [gcode_macro TOOL_DROPOFF]
51 | gcode:
52 | KTC_DESELECT_ALL
53 | SUB_SET_ALL_TOOLS_DEACTIVE
54 |
55 |
56 | [gcode_macro _SET_ACTIVE_TOOL]
57 | description: Sets the active tool in mainsail (and all others inactive)
58 | gcode:
59 | SUB_SET_ALL_TOOLS_DEACTIVE
60 | {% set TOOL = params.TOOL|default(-1)|int %}
61 | SET_GCODE_VARIABLE MACRO=T{TOOL} VARIABLE=active VALUE=1
62 | KTC_T{TOOL}
63 |
64 | [gcode_macro SUB_SET_ALL_TOOLS_DEACTIVE]
65 | description: Sets the active tool in mainsail (and all others inactive)
66 | gcode:
67 | SET_GCODE_VARIABLE MACRO=T0 VARIABLE=active VALUE=0
68 | SET_GCODE_VARIABLE MACRO=T1 VARIABLE=active VALUE=0
69 | SET_GCODE_VARIABLE MACRO=T2 VARIABLE=active VALUE=0
70 | SET_GCODE_VARIABLE MACRO=T3 VARIABLE=active VALUE=0
71 | SET_GCODE_VARIABLE MACRO=T4 VARIABLE=active VALUE=0
72 | SET_GCODE_VARIABLE MACRO=T5 VARIABLE=active VALUE=0
73 | SET_GCODE_VARIABLE MACRO=T6 VARIABLE=active VALUE=0
74 | SET_GCODE_VARIABLE MACRO=T7 VARIABLE=active VALUE=0
75 | SET_GCODE_VARIABLE MACRO=T8 VARIABLE=active VALUE=0
76 | SET_GCODE_VARIABLE MACRO=T9 VARIABLE=active VALUE=0
77 | SET_GCODE_VARIABLE MACRO=T10 VARIABLE=active VALUE=0
78 | SET_GCODE_VARIABLE MACRO=T11 VARIABLE=active VALUE=0
79 | SET_GCODE_VARIABLE MACRO=T49 VARIABLE=active VALUE=0
80 |
81 |
82 | [gcode_macro TOOL_UNLOCK]
83 | gcode:
84 | KTC_TOOLCHANGER_DISENGAGE TOOLCHANGER=Jubilee
85 |
86 | [gcode_macro TOOL_LOCK]
87 | gcode:
88 | KTC_TOOLCHANGER_ENGAGE TOOLCHANGER=Jubilee
89 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | #.idea/
161 |
--------------------------------------------------------------------------------
/config/example_config/simple/simple_example.cfg:
--------------------------------------------------------------------------------
1 | # Example of a KTC configuration file for a 2 tool printer.
2 | # This assumes that the printer is configured with 2 extruders and 2 part cooling fans:
3 | # - [extruder0] and [fan_generic partfan_t0] for the first extruder and part cooling fan
4 | # - [extruder1] and [fan_generic partfan_t1] for the second extruder and part cooling fan
5 |
6 | [ktc_tool 0]
7 | tool_number: 0
8 | heater: extruder
9 | fans: partfan_t0
10 | params_park:198,50, 0
11 |
12 | [ktc_tool 1]
13 | tool_number: 1
14 | heater: extruder1
15 | fans: partfan_t1
16 | params_park:198,150, 0
17 |
18 | [ktc]
19 | # Tool change gcode that will be inherited by all tools not overriding it.
20 | tool_select_gcode:
21 | # myself will be replaced with the tool that is selected
22 | KTC_TOOL_SET_TEMPERATURE TOOL={myself.name} CHNG_STATE=2 # Put tool heater in Active mode so heating while moving
23 |
24 | SAVE_GCODE_STATE NAME=TOOL_PICKUP # Save GCODE state. Will be restored at the end of pickup code
25 | G90
26 |
27 | ############## Move in to parking spot ##############
28 | G0 X150 F40000 # Fast move X inside the safezone, so we don't crash into other tools.
29 | G0 Y{myself.zone[1]} F40000 # Fast move Y in front of parking spot.
30 | G0 X{myself.params_park[0]} F3000 # Slow Move to the pickup position for tool.
31 |
32 | ############## Atach Tool ##############
33 | # Asume attached
34 |
35 | ############## Tool Z Offset ##############
36 | SET_GCODE_OFFSET Z={myself.offset[2]} MOVE=1 # Set and move the Z offset. Avoid crashing into bed when moving out later.
37 |
38 | ############## Wait for heater ##############
39 | {% if myself.heater_names|length > 0 %} # If the tool has an extruder:
40 | ACTIVATE_EXTRUDER EXTRUDER={myself.heater_names[0]} # Activate the extruder
41 | KTC_TEMPERATURE_WAIT_WITH_TOLERANCE TOOL={myself.name} # Wait for tool to reach target temperature.
42 | {% endif %} # /
43 |
44 | ############## Move out ##############
45 | G0 X150 F6000 # Slow Move to the zone position for tool.
46 |
47 | ############## Finnish up ##############
48 | M400 # Wait for current moves to finish.
49 | 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.
50 | # Set the toolhead offsets. Needs to be after any RESTORE_GCODE_STATE!
51 | SET_GCODE_OFFSET X={myself.offset[0]} Y={myself.offset[1]} Z={myself.offset[2]} MOVE=0
52 |
53 | tool_deselect_gcode:
54 | # myself will be replaced with the tool that is deselected
55 |
56 | SET_GCODE_OFFSET X=0 Y=0 # Set XY offset to 0 so we park the tool right.
57 | SAVE_GCODE_STATE NAME=TOOL_DROPOFF # Save GCode state.
58 | G90 # Absolute positions
59 |
60 | ############## Move in to parking spot ##############
61 | G0 X150 F40000 # Move X and
62 | G0 Y{myself.zone[1]} F40000 # Fast move Y in front of parking spot.
63 | G0 X{myself.park[0]} F3000 # Slow Move to the dropoff position for tool.
64 |
65 | ############## Detach Tool ##############
66 | G0 Y{myself.zone[1]|float - 15} F40000 # Detach tool
67 |
68 | G0 X150 F40000 # Fast Move to the general pickup position for tools.
69 |
70 | RESTORE_GCODE_STATE NAME=TOOL_DROPOFF MOVE=0 # Restore Gcode state
71 | SET_GCODE_OFFSET Z=0 # Set Z offset to 0 after too is parked.
--------------------------------------------------------------------------------
/doc/state_ref.md:
--------------------------------------------------------------------------------
1 | # Macros used by KTC have this object states accesible
2 | ##     **KTC** - Is always accessible
3 | - `global_offset` - Global offset.
4 | - `active_tool` - Name of the active tool. Special names are: 'tool_unknown' and 'tool_none'.
5 | - `active_tool_n` - Tool Number if any of the active tool. Special numbers are: -2 for 'tool_unknown' and -1 for 'tool_none'.
6 | - `saved_fan_speed` - Speed saved at each fanspeedchange to be recovered at Toolchange.
7 | - `state` - State of KTC, one of STATE_TYPE.
8 | - `tools` - List of all tool names.
9 | - `toolchangers` - List of all toolchangers.
10 | - `params_available` - List of available custom parameters as specified in the configuration file.
11 | - `params_*` - parameter in the above list.
12 |
13 | ##     **Tool** - The tool calling this macro is referenced as `myself` in `tool_select_gcode:` and `tool_deselect_gcode:`. One can write `{myself.name}` which would return `3` for a tool named so.
14 | - `name` - Tool name. 0, 1, 2, etc.
15 | - `number` - Tool number.
16 | - `state` - State of the tool, one of STATE_TYPE.
17 | - `toolchanger` - Name of toolchanger this tool is on.
18 | - `heater_names` - List of heaters this tool has.
19 | - `heater_state` - Current state for the tools heaters. 0 = off, 1 = standby temperature, 2 = active temperature.
20 | - `fans` - List of fans this tool has.
21 | - `offset` - Tool offset as a list of [X,Y,Z]. Global offset is added if set.
22 | - `heater_active_temp` - Temperature to set when in active mode.
23 | - `heater_standby_temp` - Temperature to set when in standby mode.
24 | - `heater_active_to_standby_delay` - Time in seconds from setting temperature to standby that the temperature actualy changes. Use 0.1 to change imediatley to standby temperature.
25 | - `standby_to_powerdown_delay` - 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.
26 | - `params_available` - List of available custom parameters as specified in the configuration file.
27 | - `params_*` - parameter in the above list.
28 |
29 | ##     **Toolchanger** - The toolchanger calling this macro is referenced as `myself` in `init_gcode:`, `engage_gcode:` and `disengage_gcode:`. One can write `{myself.name}` which would return `Jubilee` for a toolchanger named so.
30 | - `name` - Tool name. 0, 1, 2, etc.
31 | - `selected_tool` - Name of the selected tool. Special names are: 'tool_unknown' and 'tool_none'.
32 | - `selected_tool_n` - Tool Number if any of the selected tool. Special numbers are: -2 for 'tool_unknown' and -1 for 'tool_none'.
33 | - `init_mode` - When this toolchanger is initialized: 'manual', 'on_start' or 'on_first_use'
34 | - `state` - State of the toolchanger, one of STATE_TYPE.
35 | - `tools` - List of all tool names attached to this toolchanger.
36 | - `params_available` - List of available custom parameters as specified in the configuration file.
37 | - `params_*` - parameter in the above list.
38 |
39 | ##     **STATE_TYPE** Constant valuse that the state of ktc, a tool or toolchanger can have.
40 | States can be set like: `KTC_SET_STATE TOOLCHANGER={myself.name} STATE=READY`
41 | - `ERROR` - Toolchanger or tool is in error state.
42 | - `NOT_CONFIGURED` - Toolchanger or tool is not configured.
43 | - `CONFIGURING` - Toolchanger or tool is configuring.
44 | - `CONFIGURED` - Toolchanger or tool is configured but not initialized.
45 | - `UNINITIALIZED` - Toolchanger or tool is uninitialized.
46 | - `INITIALIZING` - Toolchanger or tool is initializing.
47 | - `INITIALIZED` - Toolchanger or tool is initialized but not ready.
48 | - `READY` - Toolchanger or tool is ready to be used.
49 | - `CHANGING` - Toolchanger or tool is changing tool.
50 | - `ENGAGING` - Toolchanger is engaging.
51 | - `SELECTING` - Tool is selecting.
52 | - `DISENGAGING` - Toolchanger or tool is disengaging.
53 | - `DESELECTING` - Tool is deselecting.
54 | - `ENGAGED` - Tollchanger or tool is engaged.
55 | - `SELECTED` - Tool is selected.
56 | - `ACTIVE` - Tool is active as main engaged tool for ktc.
57 |
--------------------------------------------------------------------------------
/config/example_config/complete/complete_example.cfg:
--------------------------------------------------------------------------------
1 | # Under development
2 |
3 | # Example of a KTC configuration file for a 5 tool printer and 2 toolchangers.
4 | # This assumes that the printer is configured with 2 extruders and 2 part cooling fans:
5 | # - [extruder0] and [fan_generic partfan_t0] for the first extruder and part cooling fan
6 | # - [extruder1] and [fan_generic partfan_t1] for the second extruder and part cooling fan
7 | # - This asumes that the printer also has a ERCF MMU unit with 3 gates configured with HappyHare.
8 |
9 | # Object tree inheritance:
10 | # - KTC
11 | # Jubilee
12 | # Tool 0
13 | # ERCF
14 | # Tool 2
15 | # Tool 3
16 | # Tool 4
17 | # Tool 1
18 |
19 |
20 | [ktc_toolchanger Jubilee]
21 |
22 | [ktc_tool 0]
23 | tool_number: 0
24 | heater: extruder
25 | fans: partfan_t0
26 | params_park:198,50, 0
27 |
28 | [ktc_tool 1]
29 | tool_number: 1
30 | heater: extruder1
31 | fans: partfan_t1
32 | params_park:198,150, 0
33 |
34 | [ktc_toolchanger ERCF]
35 | parent_tool: 0
36 | tool_deselect_gcode:
37 | # This code will be inherited by ktc_tool 2, 3 and 4.
38 | MMU_EJECT
39 |
40 | [ktc_tool 2]
41 | tool_select_gcode:
42 | # This code will not be inherited.
43 | MMU_CHANGE_TOOL TOOL=0 STANDALONE=1
44 |
45 | [ktc_tool 3]
46 | tool_select_gcode:
47 | MMU_CHANGE_TOOL TOOL=1 STANDALONE=1
48 |
49 | [ktc_tool 4]
50 | tool_select_gcode:
51 | MMU_CHANGE_TOOL TOOL=2 STANDALONE=1
52 |
53 | [ktc]
54 | default_toolchanger = Jubilee
55 |
56 | # Tool change gcode that will be inherited by all tools not overriding it.
57 | tool_select_gcode:
58 | # myself will be replaced with the tool that is selected
59 | # This code will be inherited by Jubillee and on untill overriden by tool 2, 3 or 4.
60 | KTC_TOOL_SET_TEMPERATURE TOOL={myself.name} CHNG_STATE=2 # Put tool heater in Active mode so heating while moving
61 |
62 | SAVE_GCODE_STATE NAME=TOOL_PICKUP # Save GCODE state. Will be restored at the end of pickup code
63 | G90
64 |
65 | ############## Move in to parking spot ##############
66 | G0 X150 F40000 # Fast move X inside the safezone, so we don't crash into other tools.
67 | G0 Y{myself.zone[1]} F40000 # Fast move Y in front of parking spot.
68 | G0 X{myself.params_park[0]} F3000 # Slow Move to the pickup position for tool.
69 |
70 | ############## Atach Tool ##############
71 | # Asume attached
72 |
73 | ############## Tool Z Offset ##############
74 | SET_GCODE_OFFSET Z={myself.offset[2]} MOVE=1 # Set and move the Z offset. Avoid crashing into bed when moving out later.
75 |
76 | ############## Wait for heater ##############
77 | {% if myself.heater_names|length > 0 %} # If the tool has an extruder:
78 | ACTIVATE_EXTRUDER EXTRUDER={myself.heater_names[0]} # Activate the extruder
79 | KTC_TEMPERATURE_WAIT_WITH_TOLERANCE TOOL={myself.name} # Wait for tool to reach target temperature.
80 | {% endif %} # /
81 |
82 | ############## Move out ##############
83 | G0 X150 F6000 # Slow Move to the zone position for tool.
84 |
85 | ############## Finnish up ##############
86 | M400 # Wait for current moves to finish.
87 | 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.
88 | # Set the toolhead offsets. Needs to be after any RESTORE_GCODE_STATE!
89 | SET_GCODE_OFFSET X={myself.offset[0]} Y={myself.offset[1]} Z={myself.offset[2]} MOVE=0
90 |
91 | tool_deselect_gcode:
92 | # myself will be replaced with the tool that is deselected
93 | # This code will be inherited by Jubillee and on untill overriden by ERCF.
94 |
95 | SET_GCODE_OFFSET X=0 Y=0 # Set XY offset to 0 so we park the tool right.
96 | SAVE_GCODE_STATE NAME=TOOL_DROPOFF # Save GCode state.
97 | G90 # Absolute positions
98 |
99 | ############## Move in to parking spot ##############
100 | G0 X150 F40000 # Move X and
101 | G0 Y{myself.zone[1]} F40000 # Fast move Y in front of parking spot.
102 | G0 X{myself.park[0]} F3000 # Slow Move to the dropoff position for tool.
103 |
104 | ############## Detach Tool ##############
105 | G0 Y{myself.zone[1]|float - 15} F40000 # Detach tool
106 |
107 | G0 X150 F40000 # Fast Move to the general pickup position for tools.
108 |
109 | RESTORE_GCODE_STATE NAME=TOOL_DROPOFF MOVE=0 # Restore Gcode state
110 | SET_GCODE_OFFSET Z=0 # Set Z offset to 0 after too is parked.
--------------------------------------------------------------------------------
/extensions/ktc_persisting.py:
--------------------------------------------------------------------------------
1 | # KTC - Klipper Tool Changer code (v.2)
2 | # Persistent storage of variables for the KTC
3 | #
4 | # Copyright (C) 2024 Andrei Ignat
5 | #
6 | # This file may be distributed under the terms of the GNU GPLv3 license.
7 | #
8 |
9 | # This is based on the Klipper save_variables.py to be able to
10 | # save variables from KTC inddependent of other plugins.
11 | # Using the default save_variables.py will cause conflicts when
12 | # other plugins such as HappyHare tries to reference the file again.
13 | # This will use a different filename to avoid this incompatibility.
14 | #
15 | # This module will also only save the variables when needed and no more.
16 | # This is to avoid excessive writes to the SD card and overhaed on the system.
17 |
18 | import os.path, ast, configparser, typing
19 |
20 | # Only import these modules in Dev environment. Consult Dev_doc.md for more info.
21 | if typing.TYPE_CHECKING:
22 | from ...klipper.klippy import configfile
23 | from ...klipper.klippy import klippy, reactor
24 | from. import ktc_log
25 |
26 | # Constant values moved here to avoid circular imports
27 | KTC_SAVE_VARIABLES_FILENAME = "~/ktc_variables.cfg"
28 | KTC_SAVE_VARIABLES_DELAY = 10
29 |
30 | class KtcPersisting:
31 | def __init__(self, config: 'configfile.ConfigWrapper'):
32 | self.printer : 'klippy.Printer' = config.get_printer()
33 | self.reactor: 'reactor.Reactor' = self.printer.get_reactor()
34 | self.log = typing.cast('ktc_log.KtcLog', self.printer.load_object(
35 | config, "ktc_log"
36 | ))
37 |
38 | self.filename = os.path.expanduser(KTC_SAVE_VARIABLES_FILENAME)
39 |
40 | self.content = {}
41 | self.ready_to_save = False
42 |
43 | # Set up timer to only save values when needed
44 | # and no more than once every 10 seconds to allow for
45 | # multiple changes and avoid excessive writes
46 | self.timer_save = self.reactor.register_timer(
47 | self._save_changes_timer_event,
48 | self.reactor.monotonic() + (KTC_SAVE_VARIABLES_DELAY),
49 | )
50 |
51 | try:
52 | if not os.path.exists(self.filename):
53 | open(self.filename, "w", encoding="utf-8").close()
54 | self.load_content()
55 | except Exception as e:
56 | raise e.with_traceback(e.__traceback__)
57 |
58 | # Remove the timer when Klipper shuts down
59 | def disconnect(self):
60 | self.reactor.update_timer(self.timer_save, self.reactor.NEVER)
61 |
62 | def load_content(self):
63 | sections = {}
64 | varfile = configparser.ConfigParser()
65 | try:
66 | varfile.read(self.filename)
67 | # Load variables for each section
68 | for section in varfile.sections():
69 | sections[section] = {}
70 | for name, val in varfile.items(section):
71 | sections[section][name] = ast.literal_eval(val)
72 | except Exception as e:
73 | msg = "Unable to parse existing KTC variable file: %s" % (self.filename,)
74 | raise Exception(msg) from e
75 | self.content = sections
76 |
77 | def save_variable(self, varname: str, value: str, section: str = "Variables",
78 | force_save: bool = False):
79 | try:
80 | value = ast.literal_eval(value)
81 | except ValueError as e:
82 | raise Exception("Unable to parse '%s' as a literal: %s" % (value, e)) from e
83 |
84 | if section not in self.content:
85 | self.content[section] = {}
86 |
87 | self.content[section][varname] = value
88 | self.ready_to_save = True
89 |
90 | if force_save:
91 | self.force_save()
92 |
93 | def force_save(self):
94 | self.ready_to_save = True
95 | self._save_changes_timer_event(self.reactor.monotonic())
96 |
97 | def _save_changes_timer_event(self, eventtime):
98 | try:
99 | if self.ready_to_save:
100 | self.ready_to_save = False
101 |
102 | # Write file
103 | varfile = configparser.ConfigParser()
104 | for section, variables in sorted(self.content.items()):
105 | varfile.add_section(section)
106 | for name, val in sorted(variables.items()):
107 | varfile.set(section, name, repr(val))
108 |
109 | f = open(self.filename, "w", encoding="utf-8")
110 | varfile.write(f)
111 | f.close()
112 | except Exception as e:
113 | self.log.debug("_save_changes_timer_event:Exception: %s" % (str(e)))
114 | raise e.with_traceback(e.__traceback__)
115 | nextwake = eventtime + KTC_SAVE_VARIABLES_DELAY
116 | return nextwake
117 |
118 | def get_status(self, eventtime=None): # pylint: disable=unused-argument
119 | status = {
120 | "content": self.content,
121 | }
122 | return status
123 |
124 |
125 | def load_config(config):
126 | return KtcPersisting(config)
127 |
--------------------------------------------------------------------------------
/doc/command_ref.md:
--------------------------------------------------------------------------------
1 | # KTC - Command Reference
2 |
3 | ##     Basic Toolchanger functionality
4 | | Command | Description |
5 | | ------- | ----------- |
6 | | `KTC_TOOLCHANGER_ENGAGE [TOOLCHANGER=] [DISREGARD_ENGAGED=<0\|1>]` | Engage or lock the tool. |
7 | | `KTC_TOOLCHANGER_DISENGAGE [TOOLCHANGER=] [DISREGARD_DISENGAGED=<0\|1>]` | Disengage or unlock from the tool. |
8 | | `KTC_T` | Select the tool with number. |
9 | | `KTC_DESELECT_ALL` | Recursivley deselects all tools. |
10 | | `KTC_TOOL_SET_TEMPERATURE [TOOL= \| T=] [ACTV_TMP=] [STDB_TMP=] [CHNG_STATE=<0\|1\|2>\|] [STDB_TIMEOUT=] [SHTDWN_TIMEOUT=]` | Change temperature settings for active or specified tool. |
11 | | `KTC_SET_AND_SAVE_PARTFAN_SPEED [TOOL= \| T=] [S=]` | Set the part cooling fan speed for the active or specified tool. If no speed value is specified, the fan will run at full speed by default. |
12 | | `KTC_TEMPERATURE_WAIT_WITH_TOLERANCE [TOOL= \| T=] [TOLERANCE=<0-9>]` | Waits for the specified tool or heater's temperature to reach its target temperature with a set tolerance. The default tolerance is 1°C. If no tool or heater is specified, it waits for all temperatures to reach their target temperatures. |
13 |
14 |
15 | ##     Offset commands
16 | | Command | Description |
17 | | ------- | ----------- |
18 | | `KTC_GLOBAL_OFFSET_SAVE [ [[X=] [Y=] [Z=]] \| [[X_ADJUST=] [Y_ADJUST=] [Z_ADJUST=]] ]` | Set a global position offset that is applied to all tool offsets. Reports the current global offset if no parameter is provided. |
19 | | `KTC_TOOL_OFFSET_SAVE [TOOL= \| T=] [ [[X=] [Y=] [Z=]] \| [[X_ADJUST=] [Y_ADJUST=] [Z_ADJUST=]] ]` | Save the positional offset of an individual tool to file so it can be used later. Reports the tool offset without global offsets if no offset parameter is provided. |
20 |
21 |
22 | ##     Tool number mapping commands
23 | | Command | Description |
24 | | ------- | ----------- |
25 | | `KTC_TOOLS_DISPLAY` | Report the current mapping of tools to other KTC tools. |
26 | | `KTC_TOOL_MAP_NR TOOL= SET=` | Map a tool to a index. Index must not be already in use. |
27 |
28 |
29 | ##     Advanced commands, rarely used
30 | | Command | Description |
31 | | ------- | ----------- |
32 | | `KTC_SET_ACTIVE_TOOL TOOL= \| T=`| Set the KTC active tool manually to the specified. For overwriding when loading a tool manually. |
33 | | `KTC_SET_STATE [TOOL= \| T= \| TOOLCHANGER=] [STATE=]` | Sets the state of the specified tool, toolchanger or the KTC itself. Without state provided, it reports the currently active state for the specified tool, toolchanger or KTC itself if no attributes. To change state to KTC, only use the STATE attribute. For changing toolchanger state, use TOOLCHANGER attribute. |
34 | | `KTC_TOOLCHANGER_SET_SELECTED_TOOL TOOL= \| T= [TOOLCHANGER=]` | Manually sets the selected tool of a specified or the default toolchanger. |
35 | | `KTC_TOOLCHANGER_INITIALIZE [TOOLCHANGER=]` | Manually initialize the specified or default toolchanger. |
36 | | `KTC_HEATERS_PAUSE` | Turns off all heaters that are configured for tools and saves the changes. The heaters can be resumed later using the command KTC_HEATERS_RESUME. This command does not affect heated beds. |
37 | | `KTC_HEATERS_RESUME` | Resumes all heaters that were previously turned off by the `KTC_HEATERS_PAUSE` command. |
38 |
39 |
40 | ##     Status, Logging and Persisted state
41 | | Command | Description |
42 | | ------- | ----------- |
43 | | `KTC_STATS_REPORT` | Report the KTC statistics to console. |
44 | | `KTC_PRINT_STATS_REPORT` | Report KTC statistics since last print started. |
45 | | `KTC_RESET_STATS SURE=YES` | Reset all the KTC statistics. |
46 | | `KTC_RESET_PRINT_STATS` | Run at start of a print to initialize and reset the KTC print statistics | |
47 | | `KTC_SET_LOG_LEVEL [LEVEL=<0-3>] [LOGFILE=<0-3>]` | Set the log level for the KTC.
- `LEVEL` determines the amount of logging displayed on the console.
- `LOGFILE` determines the amount of logging saved to a file.
Log levels:
( 0 = Only the Always messages )
( 1 = Info messages and above )
( 2 = Debug messages and above )
( 3 = Trace messages and above ) |
48 | | `KTC_LOG_TRACE MSG=` | Send a message to log at this logging level |
49 | | `KTC_LOG_DEBUG MSG=` | Send a message to log at this logging level |
50 | | `KTC_LOG_INFO MSG=` | Send a message to log at this logging level |
51 | | `KTC_LOG_ALWAYS MSG=` | Send a message to log at this logging level |
52 |
53 |
54 | ##     Debuging
55 | | Command | Description |
56 | | ------- | ----------- |
57 | | `KTC_DEBUG_HEATERS` | Reports current status of heaters. |
58 | | `KTC_DEBUG_TOOLS` | Reports current status of tools. |
59 |
60 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
KTC - Klipper Toolchanger Code v.2
4 |
5 |
6 |
7 | Universal Toolchanger helper for Klipper
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 | This adds logic to [Klipper](https://github.com/Klipper3d/klipper) for layered, inherited ToolChanging functionality.
29 |
30 | This is a complete rewrite of KTCC v.1 to be more versatile and have infinite levels of toolchangers. Inspiration comes mainly from how RRF enables toolchanging and from the HappyHare project.
31 |
32 | I welcome any and all input and contributions. Don't be afraid to make a pull request :D
33 |
34 | Complex code example is still under construction.
35 |
36 | Thank you!
37 |
38 | ##     Major features:
39 |
40 | - Support any type of toolchanger and any type of tool.
41 | - Infinite levels of nested changers and tools with inheritance.
42 | - Handles Tool temperature transfers on tool select/deselect with multiple heaters and offsets.
43 | - Standby temperatures for parked tools.
44 | - Handles multiple fans per tool and speed transfer between tools.
45 | - Wait to reach temperature with configurable tolerance for tool.
46 | - Unlimited parameters for each object, accesible by macros.
47 | - Tool number maping. Remap a tool to another, no need to reslice.
48 | - Persitance of state and statistics across restarts.
49 |
50 |
51 |
52 |
53 | ##     Installation
54 |
55 | The code requires Klipper to run on Python v.3 and is not compatible with Python v.2.
56 |
57 | ### 1\. Automatic install with Moonraker autoupdate support
58 | Connect to your klipper machine using SSH and run this one line command:
59 | ```
60 | cd ~/ && git clone https://github.com/TypQxQ/KTC.git && bash ~/KTC/install.sh
61 | ```
62 |
63 | Configure away inside printer.cfg or a file referenced by it.
64 |
65 | ### 2\. Manual Install
66 | Copy or link the python (`*.py`) files into the `\klipper\klippy\extras` directory.
67 |
68 | Copy the macros inside the macros folder and reference them in printer.cfg.
69 |
70 | ##     Minimum Configuration:
71 | * At least one tool needs to be defined, ex:
72 |
73 | `[ktc_tool 0]`
74 |
75 | ##     Help and community:
76 | [The discution forums here on Github](https://github.com/TypQxQ/KTC/discussions)
77 |
78 | ##     Configuration Examples:
79 | Configuration example can be found here:
80 |
81 | * [Simple Configuration with one toolchanger](/config/example_config/simple/simple_example.cfg)
82 | * [Full Configuration with one Toolchanger](/config/example_config/complete/complete_example.cfg)
83 | * [Macros for T# toolchange](/config/example_config/TOOL_MACROS.cfg)
84 |
85 | And here are some configurations of working machines:
86 | * [Jubilee Toolchanger with Toolchanger and ERCF](https://github.com/TypQxQ/DuetBackup/tree/main/qTC-Klipper/config)
87 | * [Jubilee Toolchanger with Toolchanger and ERCF](https://github.com/ngolshan/Jubilee_KTC_Config)
88 |
89 | ##     References:
90 |
91 | **[Configuation Reference](./doc/configuration.md)**
92 | Explains all configurable options.
93 |
94 | **[Command Reference](./doc/command_ref.md)**
95 | Lists all the commands available at runtime from Klipper.
96 |
97 | **[Object state Reference](./doc/state_ref.md)**
98 | Lists all available object variables available to macros.
99 |
100 | ##     Related projects
101 | - [kTAMV - Klipper Tool Alignment (using) Machine Vision](https://github.com/TypQxQ/kTAMV) allows X and Y allignment betwween multiple tools on a 3D printer using a camera that points up towards the nozzle from inside Klipper.
102 |
103 | - [KnobProbe](https://github.com/TypQxQ/KnobProbe_Klipper) allows Z allignment between multiple tools.
104 |
105 | - [Query Endstop Continuesly in Klipper](https://github.com/TypQxQ/Query-Endstop-Continuesly-in-Klipper) Klipper module that adds a G-code command so Klipper will pause until specified endstop is in selected state, triggered or not triggered. Alternativley it can query a specified amount of times.
106 |
107 | - [Klipper Save-Restore Position](https://github.com/TypQxQ/Klipper-Save-Restore-Position) Adds behaviour as was in Klipper Toolchanger code v.1. Currently not finnished because I see no use for it. Tell me if you need it.
108 |
109 | - [KTCC v.1](https://github.com/TypQxQ/Klipper_ToolChanger)
110 |
111 | ##     Limitations
112 | - T commands need to be added by macros. Mainsail looks for `[gcode_macros T#]` inside the printer config. Adding a gcode_macro component for the tool at runtime will not work with current implementation of Mainsail and no button will show up. Therefore KTC_T should be manuly called by a corresponding T script as in the [Macros for T# toolchange example](/config/example_config/TOOL_MACROS.cfg).
113 |
114 | - Saving to configuration files does not work in Klipper when the section is not in printer.cfg. That is the reason of the persistent storage. This enables organized and distributable configuration files.
115 |
--------------------------------------------------------------------------------
/doc/configuration.md:
--------------------------------------------------------------------------------
1 | # KTC Configuration reference
2 |
3 | This document is a reference for options available in the Klipper Toolchanger Code
4 | config file.
5 |
6 | ##     Configuration file structure
7 |
8 | The configuration for KTC can be saved in one or multiple files that are referenced by printer.cfg
9 |
10 | Minimum amount of information is one `[ktc_tool name]` section that will initiate one tool with a name.
11 |
12 | ##     Structure
13 |
14 | One KTC object can be configured and will contain one default toolchanger.
15 | The default toolchanger can contain one or multiple tools. Each tool can have a toolchanger:
16 |
17 | - [ktc]
18 | - [ktc_toolchanger Default]
19 | - [ktc_tool 0]
20 | - [ktc_toolchanger SubChanger]
21 | - [ktc_tool 0-0]
22 | - [ktc_tool 0-1]
23 | - [ktc_tool 0-2]
24 | - [ktc_tool 0-3]
25 | - [ktc_tool 1]
26 | - [ktc_tool 2]
27 |
28 | ### Inheritance
29 |
30 | Inheritable options are propagated down the object tree until overridden.
31 |
32 | For the previous structure, the following code would set all tools to require_axis_homed except for those under the toolchanger named "SubChanger" whose tools have no required axis to home and ktc_tool 2 that requires all XYZ as in default.
33 | ```
34 | [ktc]
35 | requires_axis_homed = XY
36 |
37 | [ktc_toolchanger SubChanger]
38 | requires_axis_homed = None
39 |
40 | [ktc_tool 2]
41 | requires_axis_homed =
42 | ```
43 | ###     Initiating options
44 |
45 | Some options that are stored inside the persistance file can overriden from configuration. When klipper starts and finds such a option, it will save it to persistant state and raise an error prompting to delete or comment out the option in the config file. This is to have a clear source for the setting to be read from at startup and counter any ambiguity.
46 |
47 | ```
48 | #init_offset = 0.0, 0.0, 0.0
49 | # Used to initiate tool offset from configuration. Saved to state. Inheritable.
50 | # Option must be removed or commented out after being run once.
51 | # Use the 'KTC_TOOL_OFFSET_SAVE' to specify at runtime.
52 |
53 | #init_global_offset = 0.0, 0.0, 0.0
54 | # This only aplies to ktc object.
55 | # Option must be removed or commented out after being run once.
56 | # Use the 'KTC_GLOBAL_OFFSET_SAVE' to specify at runtime.
57 | ```
58 |
59 | ###     Inheritable options
60 |
61 | The following options can be set to either ktc, ktc_toolchanger or ktc_tool and will propagate down the object tree untill overridden by specifying it as empty `option=` or with a overriding value.
62 |
63 | When not specified they will be initialized with the default value as below.
64 |
65 | ```
66 | #engage_gcode = ""
67 | # Macro name or G-code to run when 'KTC_TOOLCHANGER_ENGAGE' runs for a ktc_toolchanger.
68 | # The toolchanger state is set to 'ENGAGING' at the begining and
69 | # the code here needs to change it to 'ENGAGED' or 'ERROR'.
70 |
71 | #disengage_gcode
72 | # Macro name or G-code to run when 'KTC_TOOLCHANGER_DISENGAGE' runs for a ktc_toolchanger.
73 | # The toolchanger state is set to 'DISENGAGING' at the begining and
74 | # the code here needs to change it to 'READY' or 'ERROR'.
75 |
76 | #init_gcode = ""
77 | # Macro name or G-code to run when 'KTC_TOOLCHANGER_INITIALIZE' runs for a ktc_toolchanger.
78 | # The toolchanger state is set to 'INITIALIZING' at the begining and
79 | # the code here needs to change it to 'INITIALIZED', 'READY' or 'ERROR'.
80 |
81 | #tool_select_gcode = ""
82 | # Macro name or G-code to run when selecting a tool,
83 | # for example 'KTC_T' runs for a ktc_tool.
84 | # The toolchanger state is set to 'SELECTING' at the begining and
85 | # the code here needs to change it to 'SELECTED' or 'ERROR'.
86 |
87 | #tool_deselect_gcode = ""
88 | # Macro name or G-code to run when selecting a tool,
89 | # for example 'KTC_T' or 'KTC_DESELECT_ALL' runs for a ktc_tool.
90 | # The toolchanger state is set to 'DESELECTING' at the begining and
91 | # the code here needs to change it to 'READY' or 'ERROR'.
92 |
93 | #force_deselect_when_parent_deselects = True
94 | # Used with nested toolchangers.
95 | # Forces all child tools to deselect before deselecting the parent.
96 | # For the toolchanger in the 'Strcture' example above when changing from 0-1 to 2:
97 | # If True then it will deselect 0-1 and 0 before selecting 2.
98 | # If False then it will deselect 0 before selecting 2. 0-1 will be selected on ERCF
99 | # toolchanger and 2 will be selected on the main toolchanger and active on ktc.
100 | # When changing back to 0-1 from 2, it will select 0 and not need to select 0-1 again.
101 | # This saves time on expensive toolchanges.
102 |
103 | #parent_must_be_selected_on_deselect = True
104 | # Used with nested toolchangers having 'force_deselect_when_parent_deselects = False'
105 | # When deselecting all tools with 'KTC_DESELECT_ALL' if 0-1 is selected but not 0 is:
106 | # If True, it will first select 0 before deselecting 0-1 and then 0.
107 | # If False, it will run 'tool_deselect_gcode' for 0-1 while not 0 is selected.
108 | # Setting it to False can be usefull when the tools are not dependent on eachother.
109 |
110 | #heater =
111 | # Used by ktc_tool to specify if the tool has one or more heaters and if it has a offset.
112 | # Heater names are comma separated with optional collon separated temperature offset.
113 | # 'heater = extruder3:-100, extruder2'
114 | # Will set the tool to have 2 heaters. When setting temperature to 210*C,
115 | # ktc will set the temperature to 210 for extruder2 and 110 for extruder3
116 | # Having multiple heaters per tool allows preheating filament for high speed printing.
117 | # When waiting for temperatures, KTC will wait for all the heaters on the tool.
118 |
119 | #fans =
120 | # Used by ktc_tool to specify if the tool has one or more partcooling fans
121 | # and if it has a offset.
122 | # Fan names are comma separated with optional collon separated speed offset.
123 | # 'fans = partfan_t11:-0.2, curtain_cooler'
124 | # Will set the tool to have 2 fans. When setting fan speed to 80%,
125 | # ktc will set the speed to 80% for curtain_cooler and 64% for partfan_t11
126 |
127 | #requires_axis_homed = XYZ
128 | # Specifies axis to ensure are homed before trying to select or deselect a tool.
129 | # 'requires_axis_homed =' disables any check of axis.
130 |
131 | #heater_active_to_standby_delay = 0.1
132 | # When changing the heaters of a tool from active to standby, the temperatures
133 | # will not change imediatley but after the specified time in seconds.
134 | # 0.1 seconds is actually instant. This can be usefull for verry short toolchanges
135 | # to spped up the time it takes to get up to active tool temerature.
136 |
137 | #heater_standby_to_powerdown_delay = 600
138 | # After the heaters of a tool have entered standby, a timer will start counting down
139 | # to the specified seconds and then change state to turn off the heaters.
140 | # Default is 10 minutes. This prevents having a tool run hot for a long time when
141 | # not being used. When selecting the tool again, it will enter active mode and heat
142 | # back up.
143 |
144 | ```
145 |
146 | ###     Custom parameters
147 |
148 | User defined parameters can be set to the ktc, any tool or toolchanger. Theese are also inherited. To specify such a parameter use the prefix "params_". For example `params_meltzone_lenght = 14`. All user parameters are accessible from macros as read-only. They can be named as anything as long as they have the right prefix and do not use spaces or invalid characters.
149 |
150 | ###     [KTC]
151 |
152 | The topmost object contains inheritable options that will be inherited by all other objects unless they are specifically overridden.
153 |
154 | ```
155 | [ktc]
156 | #propagate_state = True
157 | # Propagate state when changed on a tool, down through the tree to the ktc object.
158 | # For example setting a tool state as selected will set it's changer to engaged.
159 |
160 | #default_toolchanger =
161 | # This is required when specifying more than one ktc_toolchanger section.
162 | # Otherwise it will default to the name of the only
163 | # ktc_toolchanger object available.
164 |
165 | #debug_with_profile = False
166 | # Use profiler to measure time it takes to run diffrent commands and output to ktc.log
167 | ```
168 |
169 | ###     [ktc_toolchanger]
170 |
171 | For each toolchanger. If no such section is defined a toolchanger named default_toolchanger with the default options will be created.
172 |
173 | ```
174 | [ktc_toolchanger default_toolchanger]
175 | #parent_tool =
176 | # Not applicable for default_toolchanger and required for all other.
177 | # Specifies the tool this toolchanger has as parent.
178 | ```
179 |
180 | ###     [ktc_tool]
181 |
182 | Requires one ktc_tool section for each tool to be used. Only the section name is required as all other options have default values.
183 |
184 | ```
185 | [ktc_tool name_of_this_tool]
186 | #tool_number = -3
187 | # Map this tool to a number. Available numbers start at 0. Needs one to be usefull.
188 | # Default -3 denotes it not having a number.
189 |
190 | #toolchanger =
191 | # The name of the toolchanger when using layered toolchangers.
192 | # Defauts to the 'default_toolchanger' of ktc.
193 |
194 | ```
195 |
196 | ##     Log and persistance
197 |
198 | KTC uses it's owm logging module that creates a file named "ktc.log".
199 |
200 | Persistant options are saved in a file named "ktc_variables.cfg" and does not require any conflicting configurations of Klippers "varaibles.cfg" file.
201 |
202 | The log module needs no referenced in the configuration if using default options while the persistance module has no options.
203 |
204 | ```
205 | [ktc_log]
206 | #log_level = 1
207 | # Determines the amount of logging displayed on the console.
208 | # Log levels:
209 | # - 0 = Only the Always messages
210 | # - 1 = Info messages and above
211 | # - 2 = Debug messages and above
212 | # - 3 = Trace messages and above
213 |
214 | #logfile_level = 3
215 | # Determines the amount of logging saved to file, levels as above.
216 |
217 | #rollover_logfile_at_startup = False
218 | # When enabled, it will clear the log file existing under another name at each startup.
219 | # Usefull when debugging.
220 | ```
221 |
--------------------------------------------------------------------------------
/install.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # KTC - Klipper Tool Changer code (v.2)
4 | # Installation script
5 | #
6 | # Copyright (C) 2023 Andrei Ignat
7 | #
8 | # This file may be distributed under the terms of the GNU GPLv3 license.
9 | #
10 |
11 | #
12 | # The responsibility of this script is to setup the Python extensions
13 | # and configure the update processes.
14 |
15 | # Set this to terminate on error.
16 | set -e
17 |
18 | # Get the root path of the repo, aka, where this script is executing
19 | REPO_DIR=$(realpath $(dirname "$0"))
20 |
21 | # This is where Klipper is installed
22 | KLIPPER_HOME="${HOME}/klipper"
23 |
24 | # This is where the extension are downloaded to, a subdirectory of the repo.
25 | EXTENSION_PATH="${REPO_DIR}/extensions"
26 |
27 | # This is where Moonraker is installed
28 | MOONRAKER_HOME="${HOME}/moonraker"
29 |
30 | # This is where Klipper config files are stored
31 | KLIPPER_CONFIG_HOME="${HOME}/printer_data/config"
32 |
33 | # This is where Klipper config files were stored before the 0.10.0 release
34 | OLD_KLIPPER_CONFIG_HOME="${HOME}/klipper_config"
35 |
36 | #
37 | # Console Write Helpers
38 | #
39 | c_default=$(echo -en "\e[39m")
40 | c_green=$(echo -en "\e[92m")
41 | c_yellow=$(echo -en "\e[93m")
42 | c_magenta=$(echo -en "\e[35m")
43 | c_red=$(echo -en "\e[91m")
44 |
45 | log_header()
46 | {
47 | echo -e "${c_magenta}$1${c_default}"
48 | }
49 |
50 | log_important()
51 | {
52 | echo -e "${c_yellow}$1${c_default}"
53 | }
54 |
55 | log_error()
56 | {
57 | log_blank
58 | echo -e "${c_red}$1${c_default}"
59 | log_blank
60 | }
61 |
62 | log_info()
63 | {
64 | echo -e "${c_green}$1${c_default}"
65 | }
66 |
67 | log_blank()
68 | {
69 | echo ""
70 | }
71 |
72 | #
73 | # Logic to check if Klipper is installed
74 | #
75 | check_klipper() {
76 | # Check if Klipper is installed
77 | log_blank
78 | log_header "Checking if Klipper is installed..."
79 | if [ "$(sudo systemctl list-units --full -all -t service --no-legend | grep -F "klipper.service")" ]; then
80 | log_important "${INFO}Klipper service found"
81 | else
82 | log_error "${ERROR}Klipper service not found! Please install Klipper first"
83 | exit -1
84 | fi
85 | }
86 |
87 | #
88 | # Logic to verify the home directories
89 | #
90 | verify_home_dirs() {
91 | log_blank
92 | log_header "Verifying home directories..."
93 | if [ ! -d "${KLIPPER_HOME}" ]; then
94 | log_error "Klipper home directory (${KLIPPER_HOME}) not found. Use '-k ' option to override"
95 | exit -1
96 | fi
97 | if [ ! -d "${KLIPPER_CONFIG_HOME}" ]; then
98 | if [ ! -d "${OLD_KLIPPER_CONFIG_HOME}" ]; then
99 | log_error "Klipper config directory (${KLIPPER_CONFIG_HOME} or ${OLD_KLIPPER_CONFIG_HOME}) not found. Use '-c ' option to override"
100 | exit -1
101 | fi
102 | KLIPPER_CONFIG_HOME="${OLD_KLIPPER_CONFIG_HOME}"
103 | fi
104 | log_info "Klipper config directory (${KLIPPER_CONFIG_HOME}) found"
105 |
106 | if [ ! -d "${MOONRAKER_HOME}" ]; then
107 | log_error "Moonraker home directory (${MOONRAKER_HOME}) not found. Use '-m ' option to override"
108 | exit -1
109 | fi
110 | }
111 |
112 | restart_klipper()
113 | {
114 | log_header "Restarting Klipper..."
115 | sudo systemctl restart klipper
116 | }
117 |
118 | restart_moonraker()
119 | {
120 | log_header "Restarting Moonraker..."
121 | sudo systemctl restart moonraker
122 | }
123 |
124 | verify_ready()
125 | {
126 | if [ "$EUID" -eq 0 ]; then
127 | log_error "This script must not run as root"
128 | exit -1
129 | fi
130 | }
131 |
132 | function nextfilename {
133 | local name="$1"
134 | if [ -d "${name}" ]; then
135 | printf "%s-%s" ${name%%.*} $(date '+%Y%m%d_%H%M%S')
136 | else
137 | printf "%s-%s.%s-old" ${name%%.*} $(date '+%Y%m%d_%H%M%S') ${name#*.}
138 | fi
139 | }
140 |
141 | #
142 | # Logic to link the extension to Klipper
143 | #
144 | link_extension()
145 | {
146 | log_blank
147 | log_header "Linking extension files to Klipper..."
148 |
149 | for file in $(cd ${EXTENSION_PATH}/ ; ls *.py); do
150 | ln -sf "${EXTENSION_PATH}/${file}" "${KLIPPER_HOME}/klippy/extras/${file}"
151 | log_info "Linking extension file: (${file})."
152 | done
153 | }
154 |
155 | #
156 | # Logic to install the update manager to Moonraker
157 | #
158 | install_update_manager() {
159 | log_blank
160 | log_header "Adding update manager to moonraker.conf"
161 | dest=${KLIPPER_CONFIG_HOME}/moonraker.conf
162 | if test -f "$dest"; then
163 | already_included=$(grep -c "\[update_manager KTC\]" ${dest} || true)
164 | if [ "${already_included}" -eq 0 ]; then
165 | # Backup the original moonraker.conf file
166 | next_dest="$(nextfilename $dest)"
167 | log_info "Copying original moonraker.conf file to ${next_dest}"
168 | cp ${dest} ${next_dest}
169 |
170 | # Add the configuration to moonraker.conf
171 | echo "" >> "${dest}" # Add a blank line
172 | echo "" >> "${dest}" # Add a blank line
173 | echo -e "[update_manager KTC]" >> "${dest}" # Add the section header
174 | echo -e "type: git_repo" >> "${dest}"
175 | echo -e "path: ${REPO_DIR}" >> "${dest}"
176 | echo -e "origin: https://github.com/TypQxQ/KTC.git" >> "${dest}"
177 | echo -e "primary_branch: main" >> "${dest}"
178 | echo -e "install_script: install.sh" >> "${dest}"
179 | echo -e "managed_services: klipper" >> "${dest}"
180 |
181 | restart_moonraker
182 | else
183 | log_error "[update_manager KTC] already exists in moonraker.conf - skipping installing it there"
184 | fi
185 | else
186 | log_error "moonraker.conf not found!"
187 | fi
188 | }
189 |
190 | #
191 | # Logic to install the configuration to Klipper
192 | #
193 | install_klipper_config() {
194 | log_header "Adding configuration to printer.cfg"
195 |
196 | # Add configuration to printer.cfg if it doesn't exist
197 | dest=${KLIPPER_CONFIG_HOME}/printer.cfg
198 | if test -f $dest; then
199 | # Backup the original printer.cfg file
200 | next_dest="$(nextfilename "$dest")"
201 | log_info "Copying original printer.cfg file to ${next_dest}"
202 | cp ${dest} ${next_dest}
203 |
204 | # Add the configuration to printer.cfg
205 | # This example assumes that that both the server and the webcam stream are running on the same machine as Klipper
206 | # The ktc section is not needed if a tool is configured but loaded here for the macros to work if no tool is configured
207 | already_included=$(grep -c "\[ktc\]" ${dest} || true)
208 | if [ "${already_included}" -eq 0 ]; then
209 | echo "" >> "${dest}" # Add a blank line
210 | echo "" >> "${dest}" # Add a blank line
211 | echo -e "[ktc]" >> "${dest}" # Add the section header
212 |
213 | log_info "Added KTC configuration to printer.cfg"
214 | log_important "Please check the configuration in printer.cfg and adjust it as needed"
215 | else
216 | log_error "[ktc] already exists in printer.cfg - skipping adding it there"
217 | fi
218 |
219 | # Add the inclusion of macros to printer.cfg if it doesn't exist
220 | already_included=$(grep -c "\[include ktc/base/*.cfg\]" ${dest} || true)
221 | if [ "${already_included}" -eq 0 ]; then
222 | echo "" >> "${dest}" # Add a blank line
223 | echo -e "[include ktc/base/*.cfg]" >> "${dest}" # Add the section header
224 | echo -e "[include ktc/optional_rrf_compability/*.cfg]" >> "${dest}" # Add the section header
225 | else
226 | log_error "[include ktc/base/*.cfg] already exists in printer.cfg - skipping adding it and the optional macros there"
227 | fi
228 | else
229 | log_error "File printer.cfg file not found! Cannot add KTC configuration. Do it manually."
230 | fi
231 |
232 | if [ ! -d "${KLIPPER_CONFIG_HOME}/ktc" ]; then
233 | log_info "Creating the ${KLIPPER_CONFIG_HOME}/ktc directory"
234 | mkdir ${KLIPPER_CONFIG_HOME}/ktc
235 | else
236 | log_error "ktc directory already exists in ${KLIPPER_CONFIG_HOME} - skipping creating it"
237 | fi
238 |
239 | if [ ! -d "${KLIPPER_CONFIG_HOME}/ktc/base" ]; then
240 | log_info "Copying base macros to ${KLIPPER_CONFIG_HOME}/ktc"
241 | cp -r ${REPO_DIR}/macros/base ${KLIPPER_CONFIG_HOME}/ktc
242 | else
243 | log_error "Base macros already exists in ${KLIPPER_CONFIG_HOME}/ktc/base - skipping copying it there"
244 | fi
245 |
246 | if [ ! -d "${KLIPPER_CONFIG_HOME}/ktc/optional_rrf_compability" ]; then
247 | log_info "Copying optional_rrf_compability macros to ${KLIPPER_CONFIG_HOME}/ktc"
248 | cp -r ${REPO_DIR}/macros/optional_rrf_compability ${KLIPPER_CONFIG_HOME}/ktc
249 | else
250 | log_error "Optional RRF compability macros already exists in ${KLIPPER_CONFIG_HOME}/ktc/optional_rrf_compability - skipping copying it there"
251 | fi
252 | # Restart Klipper
253 | restart_klipper
254 |
255 | }
256 |
257 | #
258 | # Logic to ask a question and get a yes or no answer while displaying a prompt under installation
259 | #
260 | prompt_yn() {
261 | while true; do
262 | read -n1 -p "
263 | $@ (y/n)? " yn
264 | case "${yn}" in
265 | Y|y)
266 | echo "y"
267 | break;;
268 | N|n)
269 | echo "n"
270 | break;;
271 | *)
272 | ;;
273 | esac
274 | done
275 | }
276 |
277 | log_blank
278 | log_blank
279 | log_blank
280 | log_blank
281 | log_blank
282 | log_blank
283 | log_blank
284 | log_blank
285 | log_blank
286 | log_blank
287 | log_blank
288 | log_blank
289 | log_blank
290 | log_blank
291 | log_blank
292 | log_blank
293 | log_blank
294 | log_blank
295 | log_blank
296 | log_blank
297 | log_blank
298 | log_blank
299 | log_blank
300 | log_blank
301 | log_blank
302 | log_blank
303 | log_blank
304 | log_blank
305 | log_blank
306 | log_blank
307 | log_blank
308 | log_blank
309 | log_blank
310 | log_blank
311 | log_blank
312 | log_header " KTC"
313 | log_header " Klipper Tool Changer code (v2)"
314 | log_blank
315 | log_blank
316 | log_important "KTC is used to facilitate toolchanging under Klipper."
317 | log_blank
318 | log_info "Usage: $0 [-k ] [-c ] [-m ]"
319 | log_blank
320 | log_blank
321 | log_important "This script will install the KTC extensions and macros."
322 | log_important "It will add the base configuration in printer.cfg and moonraker.conf."
323 | log_blank
324 | yn=$(prompt_yn "Do you want to continue?")
325 | echo
326 | case $yn in
327 | y)
328 | ;;
329 | n)
330 | log_info "You can run this script again later to install KTC."
331 | log_blank
332 | exit 0
333 | ;;
334 | esac
335 |
336 |
337 |
338 | # Make sure we aren't running as root
339 | verify_ready
340 |
341 | # Check that Klipper is installed
342 | check_klipper
343 |
344 | # Check that the home directories are valid
345 | verify_home_dirs
346 |
347 | # Link the extension to Klipper
348 | link_extension
349 |
350 | # Install the update manager to Moonraker
351 | install_update_manager
352 |
353 | # Install the configuration to Klipper
354 | install_klipper_config
355 |
356 | log_blank
357 | log_blank
358 | log_important "KTC is now installed. Settings can be found in the printer.cfg file."
359 |
--------------------------------------------------------------------------------
/extensions/ktc_toolchanger.py:
--------------------------------------------------------------------------------
1 | # KTC - Klipper Tool Changer code
2 | # Toollock and general Tool support
3 | #
4 | # Copyright (C) 2024 Andrei Ignat
5 | #
6 | # This file may be distributed under the terms of the GNU GPLv3 license.
7 | #
8 |
9 | # from enum import unique
10 | import typing
11 | # import cProfile, pstats
12 | from enum import unique
13 | from .ktc_base import KtcConstantsClass, KtcBaseChangerClass, KtcConfigurableEnum # pylint: disable=relative-beyond-top-level
14 |
15 | # Only import these modules in Dev environment. Consult Dev_doc.md for more info.
16 | if typing.TYPE_CHECKING:
17 | from ...klipper.klippy import configfile
18 | from ...klipper.klippy.extras import gcode_macro as klippy_gcode_macro
19 | from . import ktc_tool
20 |
21 | @typing.final
22 | class KtcToolchanger(KtcBaseChangerClass, KtcConstantsClass):
23 | """Class initialized for each toolchanger.
24 | At least one toolchanger will be initialized for each printer.
25 | A "default_toolchanger" will be initialized if no toolchanger
26 | is specified in the config."""
27 |
28 | def __init__(self, config: 'configfile.ConfigWrapper'):
29 | # Most of the function is inherited from the base class.
30 | super().__init__(config)
31 |
32 | # When is the toolchanger initialized in relation to printer start and homing.
33 | self.init_mode = self.InitModeType.get_value_from_configuration(
34 | config, "init_mode", self.InitModeType.MANUAL) # type: ignore
35 |
36 | # And in relation to the parent tool.
37 | self.init_order = self.InitOrderType.get_value_from_configuration(
38 | config, "init_order", self.InitOrderType.INDEPENDENT)
39 |
40 | self._selected_tool = self.TOOL_UNKNOWN # The currently active tool. Default is unknown.
41 |
42 | # Load the parent tool if it is defined.
43 | parent_tool_name = config.get("parent_tool", None) # type: ignore
44 | if parent_tool_name is not None and parent_tool_name != "":
45 | self.parent_tool = typing.cast('ktc_tool.KtcTool',
46 | self.printer.load_object( # type: ignore
47 | config, "ktc_tool " + parent_tool_name)) # type: ignore
48 | if self.parent_tool is None:
49 | raise config.error(
50 | "parent_tool %s not found for ktc_toolchanger %s."
51 | % (parent_tool_name, self.name)
52 | )
53 |
54 | @property
55 | def selected_tool(self):
56 | return self._selected_tool
57 |
58 | @selected_tool.setter
59 | def selected_tool(self, value: 'ktc_tool.KtcTool'):
60 | if self._selected_tool == value:
61 | return
62 | self._selected_tool = value
63 | self.persistent_state_set("selected_tool", value.name)
64 |
65 | def configure_inherited_params(self):
66 | super().configure_inherited_params()
67 | self.gcode_macro = typing.cast('klippy_gcode_macro.PrinterGCodeMacro', # type: ignore # pylint: disable=attribute-defined-outside-init
68 | self.printer.lookup_object("gcode_macro")) # type: ignore
69 | self.state = self.StateType.CONFIGURED # pylint: disable=attribute-defined-outside-init # pylint bug
70 |
71 | def initialize(self):
72 | """Initialize the tool lock."""
73 | # Sanity check. If the parent tool is not defined,
74 | # the init_order should be set to independent.
75 | if (self.init_order != self.InitOrderType.INDEPENDENT and
76 | self.parent_tool is not None
77 | ):
78 | raise Exception(
79 | "Toolchanger %s has no parent tool " % self.name
80 | + "defined but init_order is set to AFTER_PARENT."
81 | )
82 |
83 | # If tool is anything but configured, log it.
84 | if self.state != self.StateType.CONFIGURED:
85 | self.log.debug("Initializing toolchanger %s from state %s." % (self.name, self.state))
86 | self.state = self.StateType.INITIALIZING
87 |
88 | # Order check. If dependent on parent.
89 | if (self.init_order == self.InitOrderType.AFTER_PARENT_INITIALIZATION or
90 | self.init_order == self.InitOrderType.AFTER_PARENT_SELECTED):
91 | # Initialize parent if not already.
92 | if self.parent_tool.toolchanger.state < self.StateType.INITIALIZED:
93 | self.parent_tool.toolchanger.initialize()
94 | # Select parent if not already and needed.
95 | if self.init_order == self.InitOrderType.AFTER_PARENT_SELECTED:
96 | self.parent_tool.select()
97 |
98 | # Restore the active tool from the persistent variables.
99 | selected_tool_name = str.lower(self.persistent_state.get(
100 | "selected_tool", self.TOOL_UNKNOWN.name
101 | ))
102 |
103 | # Set the active tool to the tool with the name from the persistent variables.
104 | # If not found in the tools that are loaded for this changer, set it to TOOL_UNKNOWN.
105 | if selected_tool_name == self.TOOL_NONE.name:
106 | self.selected_tool = self.TOOL_NONE
107 | else:
108 | self.selected_tool = self.tools.get(selected_tool_name, self.TOOL_UNKNOWN)
109 |
110 | if (self.selected_tool == self.TOOL_UNKNOWN and
111 | selected_tool_name != self.TOOL_UNKNOWN.name
112 | ):
113 | self.log.always(
114 | "Initial tool %s not found for ktc_toolchanger %s. Using tool %s."
115 | % (selected_tool_name, self.name, self.selected_tool.name)
116 | )
117 |
118 | # Run the init gcode template if it is defined.
119 | if self._init_gcode != "":
120 | self.log.trace(f"Initalizing ktc_toolchanger {self.name}.")
121 | init_gcode_template = self.gcode_macro.load_template( # type: ignore
122 | self.config, "", self._init_gcode)
123 | context = init_gcode_template.create_template_context()
124 | context['myself'] = self.get_status()
125 | context['ktc'] = self._ktc.get_status()
126 | context['STATE_TYPE'] = self.StateType
127 | init_gcode_template.run_gcode_from_command(context)
128 | # Check that the gcode has changed the state.
129 | if self.state == self.StateType.CONFIGURED:
130 | raise self.config.error(
131 | ("ktc_toolchanger %s: init_gcode did not " % self.name)
132 | + "change the state. Use for example "
133 | + "'KTC_SET_STATE TOOLCHANGER={myself.name} STATE=READY' to "
134 | + "change the state to READY."
135 | )
136 | else:
137 | self.state = self.StateType.READY
138 |
139 | # Set the tool as engaged. Fir tools it is equivalent to selected.
140 | self.selected_tool.state = self.StateType.ENGAGED
141 |
142 | def engage(self, disregard_engaged=False):
143 | '''Engage the lock on the tool so it can be removed.'''
144 | try:
145 | if self.state < self.StateType.INITIALIZING:
146 | raise Exception(
147 | "Status is: %s. Can't engage %s." % (self.state, self.name)
148 | )
149 |
150 | if self._engage_gcode == "":
151 | self.state = self.StateType.ENGAGED
152 | return
153 |
154 | if not disregard_engaged and self.state >= self.StateType.ENGAGED:
155 | self.log.always(
156 | "ktc_toolchanger %s is already engaged with tool %s."
157 | % (self.name, self.selected_tool.name)
158 | + " DISREGARD_ENGAGED is not set. No action taken."
159 | )
160 | return
161 |
162 | if self.state >= self.StateType.ENGAGING:
163 | self.state = self.StateType.ENGAGING
164 |
165 | engage_gcode_template = self.gcode_macro.load_template(
166 | self.config, "", self._engage_gcode)
167 | context = engage_gcode_template.create_template_context()
168 | context['myself'] = self.get_status()
169 | context['ktc'] = self._ktc.get_status()
170 | context['STATE_TYPE'] = self.StateType
171 | engage_gcode_template.run_gcode_from_command(context)
172 |
173 | if (self.state == self.StateType.ENGAGING or
174 | self.state == self.StateType.INITIALIZING):
175 | raise self.config.error(
176 | ("engage_gcode did not change the state. Use for example "
177 | + "'KTC_SET_STATE TOOLCHANGER={myself.name} STATE=ENGAGED' to "
178 | + "change the state to ENGAGED. Or ERROR if it failed.")
179 | )
180 | elif self.state == self.StateType.ERROR:
181 | raise self.config.error(
182 | "disengage_gcode failed. Check the logs for more information."
183 | )
184 |
185 | self.log.changer_stats[self.name].engages += 1
186 | self.log.trace(f"ktc_toolchanger.engage(): Setting state to {self.state}.")
187 | except Exception as e:
188 | self.state = self.StateType.ERROR
189 | # self._ktc.state = self.StateType.ERROR
190 | raise self.printer.command_error(
191 | "Engage failed for ktc_toolchanger %s with error: %s"
192 | % (self.name, e)) from e
193 |
194 | def disengage(self, disregard_disengaged=True):
195 | """Disengage the lock on the tool so it can be removed."""
196 | try:
197 | if self.state < self.StateType.INITIALIZING:
198 | raise Exception(
199 | "Status is: %s. Can't disengage %s." % (self.state, self.name)
200 | )
201 |
202 | if self._disengage_gcode == "":
203 | self.state = self.StateType.READY
204 | return
205 |
206 | if not disregard_disengaged and self.state == self.StateType.READY:
207 | self.log.always(
208 | "ktc_toolchanger %s is already disengaged with tool %s."
209 | % (self.name, self.selected_tool.name)
210 | + " DISREGARD_DISENGAGED is not set. No action taken."
211 | )
212 | return
213 |
214 | if self.state >= self.StateType.DISENGAGING:
215 | self.state = self.StateType.DISENGAGING
216 |
217 | disengage_gcode_template = self.gcode_macro.load_template(
218 | self.config, "", self._disengage_gcode)
219 | context = disengage_gcode_template.create_template_context()
220 | context['myself'] = self.get_status()
221 | context['ktc'] = self._ktc.get_status()
222 | context['STATE_TYPE'] = self.StateType
223 | disengage_gcode_template.run_gcode_from_command(context)
224 |
225 | if (self.state == self.StateType.DISENGAGING or
226 | self.state == self.StateType.INITIALIZING):
227 | raise self.config.error(
228 | ("disengage_gcode did not "
229 | + "change the state. Use for example "
230 | + "'KTC_SET_STATE TOOLCHANGER={myself.name} STATE=READY' to "
231 | + "change the state to READY. Or ERROR if it failed.")
232 | )
233 | elif self.state == self.StateType.ERROR:
234 | raise self.config.error(
235 | "disengage_gcode failed. Check the logs for more information."
236 | )
237 |
238 | self.log.changer_stats[self.name].disengages += 1
239 | self.log.trace("ktc_toolchanger.engage(): Setting state to %s." % self.state)
240 | except Exception as e:
241 | self.state = self.StateType.ERROR
242 | # self._ktc.state = self.StateType.ERROR
243 | raise self.printer.command_error(
244 | "Disengage failed for ktc_toolchanger %s with error: %s" %
245 | (self.name, e))
246 |
247 | @KtcBaseChangerClass.state.setter
248 | def state(self, value):
249 | super(KtcBaseChangerClass, type(self)).state.fset(self, value) # type: ignore
250 | if self._ktc.propagate_state:
251 | self._ktc.state = value
252 |
253 | if value == self.StateType.ENGAGING:
254 | self.selected_tool = self.TOOL_UNKNOWN
255 | elif value == self.StateType.READY:
256 | self.selected_tool = self.TOOL_NONE
257 | elif value == self.StateType.ERROR:
258 | self.log.always("KTC is now in error state.")
259 | self.selected_tool = self.TOOL_UNKNOWN
260 |
261 | def get_status(self, eventtime=None): # pylint: disable=unused-argument
262 | status = {
263 | "name": self.name,
264 | "selected_tool": self.selected_tool.name,
265 | "selected_tool_n": self.selected_tool.number,
266 | "state": self.state,
267 | "init_mode": self.init_mode,
268 | "tools": list(self.tools),
269 | "params_available": str(self.params.keys()),
270 | **self.params,
271 | }
272 | return status
273 |
274 | @unique
275 | class InitModeType(str, KtcConfigurableEnum):
276 | """Constants for the initialization mode of the toolchanger.
277 | Inherits from str so it can be JSON serializable."""
278 | MANUAL = "manual"
279 | ON_START = "on_start"
280 | ON_FIRST_USE = "on_first_use"
281 |
282 | @unique
283 | class InitOrderType(str, KtcConfigurableEnum):
284 | """Constants for the initialization order of the toolchanger."""
285 | INDEPENDENT = "independent"
286 | AFTER_PARENT_SELECTED = "after_parent_selected"
287 | AFTER_PARENT_INITIALIZATION = "after_parent_initialization"
288 |
289 | def load_config_prefix(config):
290 | """Load the toolchanger object with the given config.
291 | This is called by Klipper to initialize the toolchanger object."""
292 | # prof = cProfile.Profile()
293 |
294 | # retval = prof.runcall(KtcToolchanger, config)
295 |
296 | # output = io.StringIO()
297 | # stats = pstats.Stats(prof, stream=output).sort_stats('cumtime')
298 | # stats.print_stats()
299 | # stats_string = output.getvalue()
300 | # output.close()
301 | # carriage_return_count = stats_string.count('\n')
302 | # if carriage_return_count >= 20:
303 | # index = -1
304 | # for _ in range(20):
305 | # index = stats_string.find('\n', index + 1)
306 | # # index now contains the index of the 10th carriage return
307 | # else:
308 | # index = len(stats_string) - 1
309 | # retval.debug_init_profile = stats_string[:index]
310 |
311 | # return retval
312 |
313 | return KtcToolchanger(config)
314 |
--------------------------------------------------------------------------------
/Dev_doc.md:
--------------------------------------------------------------------------------
1 | # Development doc for KTC
2 |
3 | ## Setting up enviroment.
4 | It is assumed KTC and Klipper folders are in same directory for typing to work.
5 |
6 | ## Why so many classes?
7 | > Using inherited classes from Ktc code can use the BaseClass for typechecks and not cross import.
8 | > This minimizes risk for circular imports.
9 | >
10 | > Each class can import ktc and ktc can not import them inside the init().
11 | > The classes should not import or load eachother inside the init()
12 |
13 | ## Load paths
14 | ### Minimum configuration load path:
15 | Minimum configuration would be one tool declared.
16 |
17 | - The tool loads ktc in it's init.
18 | - ktc loads ktc_persistent at init.
19 | - ktc_persistent loads log at init.
20 | - ktc_persistent loads persistent data from file at init.
21 | - ktc_config_default_toolchanger adds default_toolchanger
22 | - ktc_config_default_toolchanger adds the toolchanger to ktc.toolchangers
23 | - ktc._config_tools adds the tool(s) to ktc.default_toolchanger.tools
24 | - ktc._config_tools adds the tool(s) to ktc.all_toolls
25 |
26 | 1- (Run configure_inherited_params recursevly)
27 | 1- Run on ktc
28 | 2- Run on default_toolchanger
29 | 3- Make a dictionary of tools that are toolchanger parents.
30 | 3- Run on first tool of default_toolchanger
31 | 4- Run on first toolchanger having the above tool as parent from (3)
32 | 4b- Run on next
33 | 3b- Run on next
34 | All obj having ran configure_inherited_params get state=configured.
35 |
36 | ## SELECT
37 | - If no tool is selected then just select
38 | - If active tool needs deselecting, deselect.
39 | - Check if toolchanger on same level has a tool selected
40 | - Check if tool needs force deselect.
41 | - Check if toolchanger over this needs deselecting
42 |
43 | - If tool on same changer is selected deselect first.
44 | - If active tool is on changer under a sibling
45 | - If active tool is on changer
46 |
47 |
48 | ## Tool Heaters
49 | When a tool has a heater it checks if a heater obj exists for it in ktc.all_heaters[]
50 | If it exists, then link to it.
51 | If it does not exist, create with own timers. Own object.
52 | When selecting tool, check if heater changes.
53 | - Setting state
54 | - State is set on tool.extruder.
55 | - For each heater it sets state if ACTIVE
56 | - Sets timers and ACTIVE temperatures with offset.
57 | - For each heater it checks if active on another tool too
58 | - If STANDBY
59 | - Set to STANDBY
60 | - Sets timers and STANDBY temperatures with offset.
61 | - If OFF
62 | - just set to OFF
63 |
64 |
65 | - ktc runs .initialize() on all toolchangers with .init_mode == "ON_START" recursevly.
66 |
67 | ## Configuration:
68 | ### Inheritable
69 | - engage_gcode = "": Gcode to run at toochanger engage, status from READY to ENGAGED
70 | - disengage_gcode = "": Gcode to run at toochanger disengage, status from ENGAGED to READY
71 | - init_gcode = "": Gcode to run at toolchanger initialization, from CONFIGURED to READY. If used, it is important tha t the Gcode changes the state of toolchanger.
72 | - requires_axis_homed = "": Axis in XYZ to be required before tool can be changed, for select
73 | - tool_select_gcode = "": Gcode to run whan selecting the tool, from ready to SELECTED
74 | - tool_deselect_gcode = "": Oposite of above.
75 | - standby_to_powerdown_time = 0.1: Seconds to wait when a tool has been deselected, before changing temperature on heater to standy temperature. 0.1 is a tenth of a second.
76 | Use something like 86400 to wait 24h if you want to run indefinitly.
77 | - heater_standby_to_powerdown_delay = 0.2: As above but from active to off.
78 | - init_offset = "": Toolhead offset. If not set anywhere, will default to "0.0,0.0,0.0". Must be deleted after the value has been read once. Can be put in again to overwrite to other value. Or use the KTC_TOOL_OFFSET_SAVE GCode command.
79 | - force_deselect_when_parent_deselects = True:
80 | Does nothing for tools on default toolchanger.
81 | When deselecting the parent tool, deselect this tool first. Otherwise it will be left
82 | selected on the toolchanger but not active on ktc.
83 | - parent_must_be_selected_on_deselect = True:
84 | Does nothing for tools on default toolchanger or tools having force_deselect_when_parent_deselects True.
85 | Used to speed up multilayer toolchanging when False.
86 | When deselecting the tool and the parent tool for this tools toolchanger is not selected, select it recursivley for all tools also having this as True, before deselecting.
87 | - heater: A list of heaters and their offset: Example: "heater0:0, preheater:-100.5"
88 | This configures heater0 and heater1 where preheater will be set to 100 degrees less than the configured temperature for the tool.
89 | At least heater_name is required if tool has a heater.
90 | To override inheritance, add it without any values: "heater:"
91 |
92 | When the tool is deselected, the heater goes in standby after "active to standby delay" seconds and then to off after "standby to powerdown time". This is so the heater waits in standby for short toolchanges and shuts down if not used for a while.
93 | Speeds up toolchanging while providing security
94 |
95 | ### NonInheritable
96 | #### KTC (all optional)
97 | - propagate_state = True. When state is changed on a tool then it's toolchanger and the ktc object also changes state accordigly. Use False if you need to control the state manually from GCode.
98 |
99 |
100 | #### KtcToolchanger
101 | - init_mode = MANUAL: When is the toolchanger initialized in relation to printer start and homing.
102 | - init_order = INDEPENDENT: And in relation to the parent tool.
103 | - force_deselect_when_parent_deselects = False
104 | - parent_tool = ""
105 |
106 | ### KtcTool
107 | tool_number = None: For use with "T#" gcode commands in by slicer. Defaults to not using.
108 | toolchanger = Default: Toolchanger this is on, defaults to Default changer.
109 |
110 |
111 | ## Base clases defined in ktc.py
112 |
113 | > ### KtcBaseClass:
114 | > The base all Ktc Classes inherits.
115 | > - functions:
116 | > - __init__: Optional config. If config is not None, Load self.config, self.printer and self.gcode reference.
117 | > - configure_inherited_params: Loads inherited parameters from instances that this instance inherits from.
118 | > - variables:
119 | > - self.config:
120 | > - self.name:
121 | > - self.printer:
122 | > - self.gcode:
123 | > - self.reactor:
124 |
125 | > ### KtcBaseChangerClass(KtcBaseClass)
126 | > The base all Ktc_Toolchanger inherits.
127 | > - functions:
128 | > - __init__: config required.
129 | > - configure_inherited_params: Loads inherited parameters from instances that this instance inherits from.
130 | > - variables:
131 | > - self.parent_tool: None if main toolchanger. Otherwise the tool this tool uses
132 | > - self.tools{}: List of all tools on the toolchanger.
133 | > - self.active_tool: Selected Tool.
134 |
135 | > ### KtcBaseToolClass(KtcBaseClass)
136 | > The base all Ktc_Toolchanger inherits.
137 | > - functions:
138 | > - __init__: config required.
139 | > - configure_inherited_params: Loads inherited parameters from instances that this instance inherits from.
140 | > - variables:
141 | > - self.parent_tool: None if main toolchanger. Otherwise the tool this tool uses
142 | > - self.tools{}: List of all tools on the toolchanger.
143 | > - self.active_tool: Selected Tool.
144 |
145 |
146 |
147 | > ### KtcConstantsClass:
148 | > Class to include CONSTANTS. This are instances of KtcBaseToolClass so they must be inherited paralel.
149 | > - CONSTANTS:
150 | > - TOOL_NUMBERLESS_N = TOOL_NUMBERLESS_N
151 | > - TOOL_NONE_N: -1
152 | > - TOOL_UNKNOWN_N: -2
153 | > - TOOL_UNKNOWN: Instance KtcBaseToolClass: name="tool_unknown", number=TOOL_UNKNOWN_N
154 | > - TOOL_NONE = Instance KtcBaseToolClass:name="tool_none", number=TOOL_NONE_N
155 |
156 |
157 | ## Python files:
158 |
159 |
160 | > ###class INIT_MODE(str, Enum):
161 | > Constants for the initialization mode of the toolchanger.
162 | > Inherits from str so it can be JSON serializable.
163 | > Not using StrEnum as it was first introduced in Python 3.11.
164 | > Enum was introduced in Python 3.4.
165 |
166 |
167 |
168 | ktc.py has all common methods that need only initialized once.
169 | -constants
170 | TOOL_UNKNOWN : Special tool indicating stateunknown.
171 | TOOL_NONE : Special tool when known state is that a toolchanger has no tool engaged.
172 |
173 | - configurable
174 | global_offset: X,Y,Z.
175 | params_*: Aditional personizable options that can be used by macros.
176 | default_toolchanger:Toolchanger object
177 | params_*: Aditional personizable options that can be used by macros.
178 |
179 | -params
180 | tools: dict[tool_name:tool]
181 | tools_by_number: dict[int, ktc_tool.KtcTool]
182 | self.toolchangers: dict[str, ktc_toolchanger.KtcToolchanger]
183 |
184 | -get_status
185 | global_offset: X,Y,Z
186 | active_tool:
187 | ? active_tool_n:
188 | saved_fan_speed:
189 | ? restore_axis_on_toolchange:
190 | ? saved_position
191 | tools: list of tool names
192 | TOOL_NONE: TOOL_NONE.name
193 | TOOL_UNKNOWN: TOOL_UNKNOWN.name
194 | **self.params
195 |
196 |
197 | ktc_log.py is is initialized once and used for logging, statistics and saving persistant settings like offsets.
198 |
199 |
200 | ktc_toolchanger.py is initialized for each toolchanger system and can have a parent_tool.
201 | - configurable
202 | Name: is case sensitive and can contain spaces
203 | params_*: Aditional personizable options that can be used by macros.
204 | disengage_gcode: G-Code run when disengaging
205 | init_mode: When to initialize the toolchanger: manual, on_start, on_first_use, homing_start, homing_end
206 | Can also be set to manual and called manualy inside the homing file for example.
207 | init_order: Defaults to independent Required if not default, not usable on default.
208 | Defaults to manual.
209 | parent_tool: Required for changers other than the default.
210 | init_gcode: G-code running on initialization. active_tool is loaded before running this
211 | engage_gcode: G-code running when engaging tool-lock.
212 | disengage_gcode: G-code running when disengaging tool-lock.
213 |
214 | -params
215 | tools: dict[tool_name:tool]
216 | persistent_state: Get the persistend state. ex. {'active_tool':'20',}
217 | state : ktc_toolchanger.STATE attr indicating current state.
218 | init_mode: ktc_toolchanger.INIT_MODE attr indicating method of initialization.
219 | active_tool: tool object currently active. Defaults to TOOL_UNKNOWN
220 | init_order:
221 |
222 | tools:
223 |
224 | - get_status:
225 | tools: list of tool.names in tools
226 | active_tool: active_tool.name
227 | init_mode: ktc_toolchanger.INIT_MODE attr indicating method of initialization.
228 | active_tool: tool object currently active. Defaults to TOOL_UNKNOWN
229 |
230 | - methods
231 | engage : method to engage the tool lock. Locking the tool
232 | disengage : method to disengage the tool lock. Unlocking the tool.
233 | change : method to change the tool.
234 | init: Method to init the changer.
235 | Loads persisted active_tool.
236 | Then checks if a init_gcode has been specified.
237 | If no init_gcode is specified then it will set state to STATE.INITIALIZED.
238 | If init_gcode is specified, it will run it.
239 | Atleast myself.state should be set for example to STATE.INITIALIZED.
240 | Can access this context:
241 | myself: The ktc_toolchanger being initialized.
242 | ktc: The ktc object.
243 | STATE: Constants for setting and comparing myself.state
244 | INIT_MODE: Constants for setting and comparing myself.init_mode
245 | persistent_state_set: Set the persistend state. ex. {'active_tool':'20',}
246 | - G-Code commands
247 |
248 |
249 |
250 | ktc_tool.py is initialized for each tool.
251 | Name is case sensitive and can contain spaces
252 | params_*: Aditional personizable options that can be used by macros.
253 | toolchanger: Optional alternative. Uses default if not specified.
254 |
255 | Offset is overwritten to persistant variable.
256 |
257 |
258 |
259 | - If final_selected has same changer as active_tool.
260 | - Deselect active_tool and continue selecting final_selected.
261 | - Else
262 | - Recursivly check tools from active_tool to ktc if force_deselect_when_parent_change.
263 | - Deselect those tools while checking.
264 | - Recursivly check all layers from final_selected to ktc If not selected
265 | - Add to ordered list?
266 | - Select all tools in ordered list one by one.
267 |
268 | Function get_list_from_tool_traversal_(checking)(start_tool, parameter_to_check, value_to_check, comparer_to_check)
269 |
270 | force_deselect_when_parent_deselects
271 | final_selected
272 |
273 |
274 |
275 | # To try to keep terms apart:
276 | Inheritance: tool <- inheriting_tool <- toolchanger <- tool <- inheriting_tool <- toolchanger <- ktc
277 | - Add T# macros if option (default) is True. Do trough adding a gcodemacro object and rename any existing. Maybe renaming to random number, recursive until not already existing.
278 | Each tool has a id (name) (ktc_tool name) and a nr.
279 |
280 | # Select: Tool is selected and loaded for use, be it a physical or a virtual on physical.
281 | When a child tool is selected it will be active on it's toolchanger and on ktc while the parent only on it's toolchanger.
282 | # Deselect: Tool is deselected and unloaded, be it a physical or a virtual on physical.
283 |
284 | ## TESTS TO DO
285 | - Check if it selects previous tool for deselecting a tool that needs tool selected.
286 | - If T0 -> T11 -> Deselect_all should: Deselect T11, select T20, deselect T0, deselect T20.
287 |
288 | class ktc_MeanLayerTime:
289 | def __init__(self, printer):
290 | # Run before toolchange to set time like in StandbyToolTimer.
291 | # Save time for last 5 (except for first) layers
292 | # Provide a mean layer time.
293 | # Have Tool have a min and max 2standby time.
294 | # If mean time for 3 layers is higher than max, then set min time.
295 | # Reset time if layer time is higher than max time. Pause or anything else that has happened.
296 | # Method to reset layer times.
297 | pass
298 |
299 |
300 | - Extruder -> heater_collection (HeaterCollectionWrapper)
301 | - Add context as constants that are inherited. Add a ktc._run_gcode_from_context()
302 | - Combine KTC_SET_STATUS with TOOL and TOOLCHANGER
303 | - Add Tn in addition to KTC_Tn
304 |
305 | - Idea for preprocessing to get time of toolchange is using a module that has a opiton named time before ToolChange.
306 | - CMD in GCODE before waiting for bed to reach temperature.
307 | - The cmd is searching for T# commands that do toolchange.
308 | - Parse chunks of rows before T# and see how much time it takes.
309 | - If takes less than option above then add a chunk, but not more than untill previous T#.
310 | - If takes more than option above then note row and have T# heat up when gcode file has been run past that command.
311 | - Check line once a second or twice a second, configurable.
312 | -Maybe using something from:
313 | https://github.com/Annex-Engineering/klipper_estimator
--------------------------------------------------------------------------------
/extensions/ktc_tool.py:
--------------------------------------------------------------------------------
1 | # KTC - Klipper Tool Changer code (v.2)
2 | # Tool module, for each tool.
3 | #
4 | # Copyright (C) 2024 Andrei Ignat
5 | #
6 | # This file may be distributed under the terms of the GNU GPLv3 license.
7 |
8 | from __future__ import annotations
9 | import typing, operator
10 | from .ktc_base import ( # pylint: disable=relative-beyond-top-level
11 | KtcBaseToolClass,
12 | KtcConstantsClass,
13 | KtcBaseChangerClass,
14 | )
15 | from .ktc_heater import HeaterStateType, KtcHeaterSettings # pylint: disable=relative-beyond-top-level
16 |
17 | # Only import these modules in Dev environment. Consult Dev_doc.md for more info.
18 | if typing.TYPE_CHECKING:
19 | from ...klipper.klippy import configfile
20 | from ...klipper.klippy.extras import gcode_macro as klippy_gcode_macro
21 | from . import ktc_toolchanger
22 |
23 | class KtcTool(KtcBaseToolClass, KtcConstantsClass):
24 | """Class for a single tool in the toolchanger"""
25 |
26 | def __init__(self, config: "configfile.ConfigWrapper"):
27 | super().__init__(config)
28 | ##### Name #####
29 | self.name = config.get_name().split(" ", 1)[1]
30 | if self.name == self.TOOL_NONE.name or self.name == self.TOOL_UNKNOWN.name:
31 | raise config.error(
32 | "Name of section '%s' is not well formated. Name is reserved for internal use."
33 | % (config.get_name())
34 | )
35 |
36 | ##### Tool Number #####
37 | # Will be added to the ktc.tools_by_number dict in ktc._config_tools()
38 | self.number = config.getint("tool_number", None) # type: ignore
39 |
40 | ##### Toolchanger #####
41 | # If none, then the default toolchanger will be set in ktc._config_default_toolchanger()
42 | toolchanger_name = config.get("toolchanger", None) # type: ignore # None is default.
43 | if toolchanger_name is not None:
44 | self.toolchanger = typing.cast( # type: ignore
45 | "ktc_toolchanger.KtcToolchanger",
46 | self.printer.load_object(config, "ktc_toolchanger " + toolchanger_name),
47 | )
48 |
49 | @property
50 | def toolchanger(self) -> "ktc_toolchanger.KtcToolchanger":
51 | return self._toolchanger
52 |
53 | @toolchanger.setter
54 | def toolchanger(self, value):
55 | if value is not None and not isinstance(value, KtcBaseChangerClass):
56 | raise ValueError("Toolchanger must be a KtcToolchanger object.")
57 | self._toolchanger = value # type: ignore
58 |
59 | @KtcBaseToolClass.state.setter
60 | def state(self, value):
61 | super(KtcBaseToolClass, type(self)).state.fset(self, value) # type: ignore
62 |
63 | def configure_inherited_params(self):
64 | # If this is TOOL_NONE or TOOL_UNKNOWN.
65 | if self.config is None:
66 | return
67 |
68 | super().configure_inherited_params()
69 |
70 | self.gcode_macro = typing.cast('klippy_gcode_macro.PrinterGCodeMacro', # type: ignore # pylint: disable=attribute-defined-outside-init
71 | self.printer.lookup_object("gcode_macro")) # type: ignore
72 |
73 | self.extruder.active_to_standby_delay = self._heater_active_to_standby_delay_in_config
74 | self.extruder.standby_to_powerdown_delay = self._heater_standby_to_powerdown_delay_in_config
75 | # Settings for any heaters.
76 | if self._heaters_config is not None:
77 | heaters = self._heaters_config.replace(" ", "").split(",")
78 | for heater_string in heaters:
79 | if heater_string == "":
80 | continue
81 | heater_settings = KtcHeaterSettings.from_string(heater_string)
82 | self.extruder.heaters.append(heater_settings)
83 | # Initialize the heater if first time used.
84 | if heater_settings.name not in self._ktc.all_heaters:
85 | self._ktc.all_heaters[heater_settings.name] = (
86 | self.printer.load_object(
87 | self.config, "ktc_heater " + heater_settings.name)
88 | )
89 |
90 | self.state = self.StateType.CONFIGURED
91 |
92 | def cmd_SelectTool(self, gcmd): # pylint: disable=invalid-name, unused-argument
93 | self.log.trace("KTC Tool " + str(self.number) + " Selected.")
94 | self.run_with_profile(self.select, final_selected=True)
95 |
96 | def select(self, final_selected=False):
97 | self.state = self.StateType.SELECTING
98 | try:
99 | self.log.always("KTC Tool %s Selecting." % self.name)
100 | at = self._ktc.active_tool
101 |
102 | # Check if homed
103 | self._ktc.confirm_ready_for_toolchange(self)
104 |
105 | # None of this is needed if this is not the final tool.
106 | if final_selected:
107 | # If already selected as final tool then do nothing.
108 | if self == at:
109 | return
110 |
111 | if at == self.TOOL_UNKNOWN:
112 | msg = ("Unknown tool already mounted."
113 | + "Can't automatically deselect unknown tool"
114 | + " before selecting new tool.")
115 | self.log.always(msg)
116 | raise self.printer.command_error(msg)
117 |
118 | # If the new tool to be selected has any heaters prepare warmup before
119 | # actual tool change so all moves will be done while heating up.
120 | if len(self.extruder.heaters) > 0:
121 | self.set_heaters(heater_state=HeaterStateType.ACTIVE)
122 |
123 | # Put all other active heaters in standby.
124 | for heater in ( heater for heater in self._ktc.all_heaters.values()
125 | if heater.state == HeaterStateType.ACTIVE
126 | and heater.name not in self.extruder.heater_names()):
127 | heater.state = HeaterStateType.STANDBY
128 |
129 | # If another tool is selected it needs to be deselected first.
130 | if at is not self.TOOL_NONE:
131 | # If the new tool is on the same toolchanger as the current tool.
132 | if self.toolchanger == at.toolchanger:
133 | at.deselect()
134 | # If on different toolchanger:
135 | else:
136 | # First deselect all tools recursively.
137 | # Only if force_deselect_when_parent_deselects is True for the tool.
138 | tools = self._get_list_from_tool_traversal_conditional(
139 | at, "force_deselect_when_parent_deselects", True)
140 | for t in tools:
141 | t.deselect()
142 | # Check if the tool to be deselected is on the same toolchanger.
143 | # Then don't deselect beyond that tool.
144 | if t.toolchanger == self.toolchanger:
145 | break
146 | # Then select the new tools recursively in reverse order
147 | # by getting the list of tools not already selected.
148 | tools = self._get_list_from_tool_traversal_conditional(
149 | self, "state", self.StateType.SELECTED, operator.ne)
150 | for t in reversed(tools):
151 | t.select()
152 |
153 | # If already selected then do nothing.
154 | if self.state == self.StateType.SELECTED or self.state == self.StateType.ACTIVE:
155 | return
156 |
157 | # Now we asume tool has been dropped if needed be.
158 | # Increase the number of selects started.
159 | self.log.tool_stats[self.name].selects_started += 1
160 | # Log the time it takes for tool mount.
161 | self.log.track_tool_selecting_start(self)
162 |
163 | # Run the gcode for pickup.
164 | try:
165 | self.state = self.StateType.SELECTING
166 | self.toolchanger.state = self.toolchanger.StateType.CHANGING
167 | self._ktc.state = self.StateType.CHANGING
168 | tool_select_gcode_template = self.gcode_macro.load_template(
169 | self.config, "", self._tool_select_gcode)
170 | context = tool_select_gcode_template.create_template_context()
171 | context['myself'] = self.get_status()
172 | context['ktc'] = self._ktc.get_status()
173 | context['STATE_TYPE'] = self.StateType
174 | tool_select_gcode_template.run_gcode_from_command(context)
175 | # Check that the gcode has changed the state.
176 | except Exception as e:
177 | raise Exception("Failed to run tool_select_gcode: " + str(e)) from e
178 | if self.state == self.StateType.SELECTING:
179 | raise self.config.error(
180 | ("tool_select_gcode has not changed the state while running "
181 | + "code in tool_select_gcode. Use for example "
182 | + "'KTC_SET_STATE TOOL={myself.name} STATE=SELECTED' to "
183 | + "indicate it is selected successfully. Or ERROR if it failed.")
184 | )
185 | elif self.state == self.StateType.ERROR:
186 | raise self.config.error(
187 | ("tool_select_gcode changed the state to ERROR while running.")
188 | )
189 |
190 | if final_selected and self.state == self.StateType.SELECTED:
191 | # Restore fan if has a fan.
192 | for fan in self.fans:
193 | self.gcode.run_script_from_command(
194 | "SET_FAN_SPEED FAN="
195 | + fan[0]
196 | + " SPEED="
197 | + str(self._ktc.saved_fan_speed * float(fan[1]))
198 | )
199 |
200 | self._ktc.active_tool = self
201 | self.log.track_tool_selected_start(self)
202 | self.state = self.StateType.ACTIVE
203 |
204 | self.log.tool_stats[self.name].selects_completed += 1
205 |
206 | except Exception as e:
207 | self.log.always("KTC Tool %s failed to select: %s" % (self.name, str(e)))
208 | self.state = self.StateType.ERROR
209 | self._ktc.state = self.StateType.ERROR
210 | raise e from e
211 | finally:
212 | self.log.track_tool_selecting_end(self)
213 |
214 | def deselect(self): # pylint: disable=arguments-differ
215 | self.state = self.StateType.DESELECTING
216 | try:
217 | # Check if homed
218 | self._ktc.confirm_ready_for_toolchange(self)
219 |
220 | self.log.track_tool_selected_end(self)
221 | self.log.track_tool_deselecting_start(self)
222 | self.log.tool_stats[self.name].deselects_started += 1
223 |
224 | self.extruder.state = HeaterStateType.STANDBY
225 |
226 | # Turn off fan if has a fan.
227 | self._ktc.tool_fan_speed_set(self, 0)
228 |
229 | # Check if toolchanger is not topmost and
230 | # parent tool must be selected on deselect and
231 | # parent tool is not selected.
232 | if (
233 | self.toolchanger.parent_tool is not None and
234 | self.parent_must_be_selected_on_deselect and
235 | self.toolchanger.parent_tool.state != self.StateType.SELECTED
236 | ):
237 | tools_to_select = self._get_list_from_tool_traversal_conditional(
238 | self, "parent_must_be_selected_on_deselect", True)
239 | for t in reversed(tools_to_select):
240 | t.select()
241 |
242 | try:
243 | gcode_template = self.gcode_macro.load_template(
244 | self.config, "", self._tool_deselect_gcode)
245 | context = gcode_template.create_template_context()
246 | context['myself'] = self.get_status()
247 | context['ktc'] = self._ktc.get_status()
248 | context['STATE_TYPE'] = self.StateType
249 | gcode_template.run_gcode_from_command(context)
250 | except Exception as e:
251 | raise Exception("Failed to run tool_deselect_gcode: " + str(e)) from e
252 | # Check that the gcode has changed the state.
253 | if self.state == self.StateType.DESELECTING:
254 | raise self.config.error(
255 | ("tool_deselect_gcode has not changed the state while running "
256 | + "code in tool_select_gcode. Use for example "
257 | + "'KTC_SET_STATE TOOL={myself.name} STATE=SELECTED' to "
258 | + "indicate it is selected successfully. Or ERROR if it failed.")
259 | )
260 | elif self.state == self.StateType.ERROR:
261 | raise self.config.error(
262 | ("tool_select_gcode has changed the state to ERROR while running.")
263 | )
264 |
265 | self._ktc.active_tool = self.TOOL_NONE # Dropoff successfull
266 | self.log.track_tool_deselecting_end(
267 | self
268 | ) # Log the time it takes for tool change.
269 | except Exception as e:
270 | self.log.always("KTC Tool %s failed to deselect: %s" % (self.name, str(e)))
271 | self.state = self.StateType.ERROR
272 | self._ktc.state = self.StateType.ERROR
273 | raise e from e
274 |
275 | def _get_list_from_tool_traversal_conditional(
276 | self, start_tool: KtcBaseToolClass, param: str,
277 | value, condition = operator.eq) -> typing.List[KtcTool]:
278 | return_list = []
279 |
280 | if start_tool in (
281 | self.TOOL_NONE,
282 | self.TOOL_UNKNOWN,
283 | self._ktc,
284 | None
285 | ):
286 | return return_list
287 |
288 | if condition(getattr(start_tool, param), value):
289 | return_list.append(start_tool)
290 |
291 | upper_tool = start_tool.toolchanger.parent_tool
292 |
293 | if upper_tool is not None:
294 | return_list += self._get_list_from_tool_traversal_conditional(
295 | upper_tool, param, value, condition)
296 |
297 | return return_list
298 |
299 | def set_heaters(self, **kwargs) -> None:
300 | if len(self.extruder.heaters) < 1:
301 | self.log.debug(
302 | "set_heater: KTC Tool %s has no heaters! Nothing to do." % self.name
303 | )
304 | return None
305 |
306 | self.log.trace(f"set_heater: KTC Tool {self.name} heater is at begining " +
307 | f"{self.extruder.state}. {self.extruder.active_temp}*C, " +
308 | f"{self.extruder.standby_temp}*C")
309 |
310 | changing_timer = False
311 | ex = self.extruder
312 |
313 | if self in self.INVALID_TOOLS:
314 | self.log.always("KTC Tool %s is not a valid tool to set heaters for." % self.name)
315 | return
316 |
317 | for i in kwargs: # pylint: disable=consider-using-dict-items
318 | if i == "heater_active_temp":
319 | ex.active_temp = kwargs[i]
320 | elif i == "heater_standby_temp":
321 | ex.standby_temp = kwargs[i]
322 | elif i == "heater_active_to_standby_delay":
323 | ex.active_to_standby_delay = kwargs[i]
324 | changing_timer = True
325 | elif i == "heater_standby_to_powerdown_delay":
326 | ex.standby_to_powerdown_delay = kwargs[i]
327 | changing_timer = True
328 | if "heater_state" in kwargs:
329 | chng_state = HeaterStateType.parse_heater_state(kwargs["heater_state"])
330 | ex.state = chng_state
331 |
332 | # If already in standby and timers are counting down,
333 | # i.e. have not triggered since set in standby,
334 | # then reset the ones counting down.
335 | if ex.state == HeaterStateType.STANDBY and changing_timer:
336 | self.log.trace("ex.state == HeaterStateType.STANDBY and changing_timer.")
337 | for hs in ex.heaters:
338 | ht = self._ktc.all_heaters[hs.name]
339 | if ht.timer_heater_standby_to_powerdown_delay.counting_down:
340 | ht.timer_heater_standby_to_powerdown_delay.set_timer(
341 | ex.standby_to_powerdown_delay)
342 | if ht.timer_heater_active_to_standby_delay.counting_down:
343 | ht.timer_heater_active_to_standby_delay.set_timer(
344 | ex.active_to_standby_delay)
345 |
346 | def get_status(self, eventtime=None): # pylint: disable=unused-argument
347 | status = {
348 | "name": self.name,
349 | "number": self.number,
350 | "state": self.state,
351 | "toolchanger": self.toolchanger.name,
352 | "fans": self.fans,
353 | "offset": [self.offset[i] + self._ktc.global_offset[i] for i in range(3)],
354 | "heater_names": [heater.name for heater in self.extruder.heaters],
355 | "heater_state": self.extruder.state,
356 | "heater_active_temp": self.extruder.active_temp,
357 | "heater_standby_temp": self.extruder.standby_temp,
358 | "heater_active_to_standby_delay": self.extruder.active_to_standby_delay,
359 | "standby_to_powerdown_delay": self.extruder.standby_to_powerdown_delay,
360 | "params_available": str(self.params.keys()),
361 | **self.params,
362 | }
363 | return status
364 |
365 | ###########################################
366 | # Dataclassess for KtcTool
367 | ###########################################
368 | def load_config_prefix(config):
369 | return KtcTool(config)
370 |
--------------------------------------------------------------------------------
/extensions/ktc_heater.py:
--------------------------------------------------------------------------------
1 | # KTC - Klipper Tool Changer code (v.2)
2 | # Heater control for controlling the temperature of the tools
3 | #
4 | # Copyright (C) 2024 Andrei Ignat
5 | #
6 | # This file may be distributed under the terms of the GNU GPLv3 license.
7 | import typing, dataclasses
8 | from enum import IntEnum, unique
9 |
10 | # Only import these modules in Dev environment. Consult Dev_doc.md for more info.
11 | if typing.TYPE_CHECKING:
12 | from ...klipper.klippy import configfile, gcode, klippy, reactor
13 | from ...klipper.klippy.extras import heaters as klippy_heaters
14 |
15 | # from ...klipper.klippy.extras import gcode_macro as klippy_gcode_macro
16 | from . import ktc_log, ktc_toolchanger, ktc_tool, ktc
17 |
18 | DEFAULT_HEATER_ACTIVE_TO_STANDBY_DELAY = 0.1
19 | DEFAULT_HEATER_STANDBY_TO_POWERDOWN_DELAY = 600
20 | NOW = 0.1
21 | NEVER = 0
22 |
23 |
24 | @unique
25 | class HeaterStateType(IntEnum):
26 | OFF = 0
27 | STANDBY = 1
28 | ACTIVE = 2
29 |
30 | @classmethod
31 | def parse_heater_state(cls, state: str):
32 | state = str(state).strip()
33 | if state is not None:
34 | if state.lower() in ("0", "off", "heaterstatetype.off"):
35 | return cls.OFF
36 | elif state.lower() in ("1", "standby", "heaterstatetype.standby"):
37 | return cls.STANDBY
38 | elif state.lower() in ("2", "active", "heaterstatetype.active"):
39 | return cls.ACTIVE
40 | else:
41 | raise ValueError(
42 | f"Invalid value for heater state: {state}. "
43 | + "Valid values are: 0/OFF, 1/STANDBY, 2/ACTIVE."
44 | )
45 |
46 |
47 | @unique
48 | class HeaterTimerType(IntEnum):
49 | TIMER_TO_SHUTDOWN = 0
50 | TIMER_TO_STANDBY = 1
51 |
52 |
53 | # @dataclasses_json.dataclass_json
54 | @dataclasses.dataclass
55 | class KtcHeaterSettings:
56 | name: str
57 | temperature_offset: float
58 |
59 | def __init__(self, name: str, temperature_offset: float):
60 | self.name = name
61 | self.temperature_offset = temperature_offset
62 |
63 | @classmethod
64 | def from_list(cls, list_value: list):
65 | temp = [list_value[0], 0.0] # Default temperature temperature_offset
66 | for i, val in enumerate(list_value[1:]):
67 | temp[i + 1] = float(val)
68 | return cls(*temp)
69 |
70 | @classmethod
71 | def from_string(cls, string_value: str):
72 | list_value = string_value.split(":")
73 | return cls.from_list(list_value)
74 |
75 | @classmethod
76 | def from_dict(cls, data):
77 | return cls(name=data["name"], temperature_offset=data["temperature_offset"])
78 |
79 | def to_dict(self):
80 | return {"name": self.name, "temperature_offset": self.temperature_offset}
81 |
82 |
83 | class KtcToolExtruder:
84 | def __init__(self, tool: "ktc_tool.KtcTool"):
85 | self._tool = tool
86 | self._state = HeaterStateType.OFF
87 | self._active_temp = 0
88 | self._standby_temp = 0
89 | self._active_to_standby_delay = DEFAULT_HEATER_ACTIVE_TO_STANDBY_DELAY
90 | self._standby_to_powerdown_delay = DEFAULT_HEATER_STANDBY_TO_POWERDOWN_DELAY
91 | self.heaters: list["KtcHeaterSettings"] = []
92 | # dataclasses.field(default_factory=list)
93 |
94 | if tool.name not in ("tool_unknown", "tool_none"):
95 | self._ktc = tool._ktc
96 |
97 | def heater_names(self) -> list[str]:
98 | return [heater.name for heater in self.heaters]
99 |
100 | @property
101 | def state(self):
102 | return self._state
103 |
104 | @state.setter
105 | def state(self, value: HeaterStateType):
106 | self._state = value
107 | _ktc = self._tool._ktc
108 | self._tool._ktc.log.trace(
109 | f"In extr. Setting heater state to {value} "
110 | + f"for tool {self._tool.name}"
111 | )
112 |
113 | def set_heater_options(self: KtcToolExtruder, heater_settings: KtcHeaterSettings):
114 | heater: KtcHeater = self._tool._ktc.all_heaters[heater_settings.name]
115 | heater.heater_active_temp = heater_settings.temperature_offset + self.active_temp
116 | heater.standby_temp = heater_settings.temperature_offset + self.standby_temp
117 | heater.active_to_standby_delay = self.active_to_standby_delay
118 | heater.standby_to_powerdown_delay = self.standby_to_powerdown_delay
119 | self._tool._ktc.log.trace(
120 | f"Setting heater options for heater {heater.name} "
121 | + f"{heater.heater_active_temp=}, {heater.standby_temp=}, "
122 | + f"{heater.active_to_standby_delay= }, {heater.standby_to_powerdown_delay= }"
123 | )
124 |
125 | # Allways set active state on all heaters
126 | if value == HeaterStateType.ACTIVE:
127 | self._tool._ktc.log.trace(
128 | "In extr. Setting heater state to ACTIVE "
129 | + f"for tool {self._tool.name}"
130 | + f" with active_temp {self._active_temp}"
131 | )
132 | for hs in self.heaters:
133 | set_heater_options(self, hs)
134 | self._tool._ktc.all_heaters[hs.name].state = value
135 | self._tool._ktc.log.track_heater_active_start(self._tool)
136 | return
137 |
138 | # For STANDY and OFF, check if the heater is active on another tool.
139 | heaters_active_with_other_tool: list[str] = []
140 | invalid_tools = (
141 | self._tool,
142 | self._tool._ktc.TOOL_NONE,
143 | self._tool._ktc.TOOL_UNKNOWN,
144 | None,
145 | )
146 | for tool in self._tool._ktc.all_tools.values():
147 | if tool not in invalid_tools:
148 | if tool.extruder.state == HeaterStateType.ACTIVE:
149 | heaters_active_with_other_tool.extend(tool.extruder.heater_names())
150 |
151 | for hs in self.heaters:
152 | if hs.name not in heaters_active_with_other_tool:
153 | if value == HeaterStateType.STANDBY:
154 | self._tool._ktc.log.trace(
155 | f"Setting heater state to STANDBY for tool {self._tool.name}"
156 | + f" with heater {hs.name}"
157 | )
158 | set_heater_options(self, hs)
159 | self._tool._ktc.all_heaters[hs.name].state = value
160 | else:
161 | # Can't track standby for tool if heater is in active state on another tool.
162 | self._tool._ktc.log.trace(
163 | f"Tool {self._tool.name} has heater {hs.name} active on another tool. "
164 | )
165 | self._tool._ktc.log.track_heater_active_end(self._tool)
166 | self._tool._ktc.log.track_heater_standby_end(self._tool)
167 | self._state = HeaterStateType.OFF
168 |
169 | @property
170 | def active_temp(self):
171 | return self._active_temp
172 |
173 | @active_temp.setter
174 | def active_temp(self, value):
175 | self._active_temp = value
176 | if self.state == HeaterStateType.ACTIVE:
177 | for hs in self.heaters:
178 | self._tool._ktc.all_heaters[hs.name].heater_active_temp = (
179 | value + hs.temperature_offset
180 | )
181 |
182 | @property
183 | def standby_temp(self):
184 | return self._standby_temp
185 |
186 | @standby_temp.setter
187 | def standby_temp(self, value):
188 | self._standby_temp = value
189 | if self.state == HeaterStateType.STANDBY:
190 | for hs in self.heaters:
191 | self._tool._ktc.all_heaters[hs.name].standby_temp = value
192 |
193 | @property
194 | def active_to_standby_delay(self):
195 | return self._active_to_standby_delay
196 |
197 | @active_to_standby_delay.setter
198 | def active_to_standby_delay(self, value):
199 | self._active_to_standby_delay = value
200 | # If heater is active on only this tool or
201 | # standby on only this tool and the timer is counting down
202 |
203 | if (
204 | self.state == HeaterStateType.ACTIVE
205 | or self.state == HeaterStateType.STANDBY
206 | ):
207 | for hs in self.heaters:
208 | ht = self._tool._ktc.all_heaters[hs.name]
209 | if ht.state == HeaterStateType.ACTIVE or (
210 | ht.state == HeaterStateType.STANDBY
211 | and ht.timer_heater_active_to_standby_delay.counting_down
212 | ):
213 | ht.active_to_standby_delay = value
214 |
215 | @property
216 | def standby_to_powerdown_delay(self):
217 | return self._standby_to_powerdown_delay
218 |
219 | @standby_to_powerdown_delay.setter
220 | def standby_to_powerdown_delay(self, value):
221 | self._standby_to_powerdown_delay = value
222 |
223 | self._tool._ktc.log.trace(
224 | f"Setting standby_to_powerdown_delay to {value} for tool {self._tool.name}"
225 | + f" with state {self.state}"
226 | )
227 |
228 | if self.state == HeaterStateType.STANDBY:
229 | for hs in self.heaters:
230 | if (
231 | self._tool._ktc.all_heaters[hs.name].state
232 | == HeaterStateType.STANDBY
233 | and self._tool._ktc.all_heaters[
234 | hs.name
235 | ].timer_heater_standby_to_powerdown_delay.counting_down
236 | ):
237 | self._tool._ktc.all_heaters[hs.name].standby_to_powerdown_delay = (
238 | value
239 | )
240 |
241 |
242 | class KtcHeater:
243 | def __init__(self, config: "configfile.ConfigWrapper"):
244 | self.printer: "klippy.Printer" = config.get_printer()
245 | self.name = typing.cast(str, config.get_name().split(" ", 1)[1])
246 | self.temperature_offset = 0.0
247 |
248 | self._state = HeaterStateType.OFF
249 | # Timer to set temperature to standby temperature
250 | # after heater_active_to_standby_delay seconds. Set if this tool has an heaters.
251 | self.timer_heater_active_to_standby_delay = KtcHeaterTimer(
252 | self.printer, self, HeaterTimerType.TIMER_TO_STANDBY
253 | )
254 |
255 | # Timer to set temperature to 0 after heater_standby_to_powerdown_delay seconds.
256 | # Set if this tool has an heaters.
257 | self.timer_heater_standby_to_powerdown_delay = KtcHeaterTimer(
258 | self.printer, self, HeaterTimerType.TIMER_TO_SHUTDOWN
259 | )
260 |
261 | # Temperature to set when in active mode.
262 | # Requred on Physical and virtual tool if any has heaters.
263 | self._heater_active_temp = 0
264 | # Temperature to set when in standby mode.
265 | # Requred on Physical and virtual tool if any has heaters.
266 | self._standby_temp = 0
267 |
268 | self.__active_to_standby_delay = DEFAULT_HEATER_ACTIVE_TO_STANDBY_DELAY
269 | self.__standby_to_powerdown_delay = DEFAULT_HEATER_STANDBY_TO_POWERDOWN_DELAY
270 |
271 | self.klippy_heater = typing.cast(
272 | "klippy_heaters.Heater",
273 | self.printer.lookup_object("heaters").lookup_heater(self.name),
274 | )
275 |
276 | @property
277 | def active_to_standby_delay(self) -> float:
278 | return self.__active_to_standby_delay
279 |
280 | @active_to_standby_delay.setter
281 | def active_to_standby_delay(self, value: float):
282 | self.__active_to_standby_delay = value
283 | self.printer.lookup_object("ktc_log").trace(
284 | f"Setting heater_active_to_standby_delay to {value} for heater {self.name}"
285 | )
286 | if self.state == HeaterStateType.STANDBY:
287 | self.printer.lookup_object("ktc_log").trace(
288 | f"Setting timer for active to standby to {value} for heater {self.name}"
289 | )
290 | self.timer_heater_active_to_standby_delay.set_timer(value)
291 |
292 | @property
293 | def standby_to_powerdown_delay(self) -> float:
294 | return self.__standby_to_powerdown_delay
295 |
296 | @standby_to_powerdown_delay.setter
297 | def standby_to_powerdown_delay(self, value: float):
298 | self.__standby_to_powerdown_delay = value
299 | self.printer.lookup_object("ktc_log").trace(
300 | f"Setting timer for standby to powerdown to {value} for heater {self.name}"
301 | + f" with state {self.state}"
302 | )
303 | if self.state == HeaterStateType.OFF:
304 | self.printer.lookup_object("ktc_log").trace("State is OFF")
305 | self.timer_heater_standby_to_powerdown_delay.set_timer(value)
306 |
307 | @property
308 | def state(self) -> HeaterStateType:
309 | return self._state
310 |
311 | @state.setter
312 | def state(self, value: HeaterStateType) -> None:
313 | """Set the state of the heater. The state can be OFF, STANDBY or ACTIVE.
314 | Disregard the previous state.
315 | Restart the timers if the state is changed to STANDBY."""
316 | self.printer.lookup_object("ktc_log").trace(
317 | f"In heater.state.setter. Setting heater state to {value} for heater {self.name}"
318 | )
319 |
320 | set_timer_to_standby = self.timer_heater_active_to_standby_delay.set_timer
321 | set_timer_to_powerdown = self.timer_heater_standby_to_powerdown_delay.set_timer
322 |
323 | if value == HeaterStateType.ACTIVE:
324 | set_timer_to_standby(NEVER)
325 | set_timer_to_powerdown(NEVER)
326 | # Log the start of the heater
327 | self.printer.lookup_object("ktc_log").trace(
328 | f"Setting heater state to ACTIVE for heater {self.name}"
329 | + f" with klippy heater {self.klippy_heater.name}"
330 | + f" and heater_active_temp {self.heater_active_temp}"
331 | )
332 | self.klippy_heater.set_temp(self.heater_active_temp)
333 | elif value == HeaterStateType.STANDBY:
334 | if self._state != HeaterStateType.ACTIVE:
335 | self.printer.lookup_object("ktc_log").trace(
336 | "Heater state is set to STANDBY without being ACTIVE first."
337 | + f" State is {self._state} for heater {self.name}"
338 | )
339 | set_timer_to_standby(NOW)
340 | else:
341 | if self.timer_heater_active_to_standby_delay.counting_down:
342 | self.printer.lookup_object("ktc_log").trace(
343 | "Heater state is set to STANDBY while the active to "
344 | + "standby timer is counting down."
345 | )
346 | set_timer_to_standby(NOW)
347 | else:
348 | self.printer.lookup_object("ktc_log").trace(
349 | f"Setting heater state to STANDBY for heater {self.name}"
350 | + f" with klippy heater {self.klippy_heater.name}"
351 | + f" and delay {self.active_to_standby_delay}"
352 | )
353 | set_timer_to_standby(self.active_to_standby_delay)
354 | # set_timer_to_powerdown(self.standby_to_powerdown_delay)
355 | elif value == HeaterStateType.OFF:
356 | set_timer_to_standby(NEVER)
357 | set_timer_to_powerdown(NOW)
358 | self._state = value
359 |
360 | @property
361 | def heater_active_temp(self):
362 | return self._heater_active_temp
363 |
364 | @heater_active_temp.setter
365 | def heater_active_temp(self, value):
366 | self._heater_active_temp = value if value > 0 else 0
367 | if self.state == HeaterStateType.ACTIVE:
368 | self.klippy_heater.set_temp(self._heater_active_temp)
369 |
370 | @property
371 | def standby_temp(self):
372 | return self._standby_temp
373 |
374 | @standby_temp.setter
375 | def standby_temp(self, value):
376 | self._standby_temp = value if value > 0 else 0
377 | if (
378 | self.state == HeaterStateType.STANDBY
379 | and not self.timer_heater_active_to_standby_delay.counting_down
380 | ):
381 | self.klippy_heater.set_temp(self._standby_temp)
382 |
383 |
384 | class KtcHeaterTimer:
385 | def __init__(
386 | self, printer: "klippy.Printer", heater: KtcHeater, timer_type: HeaterTimerType
387 | ):
388 | self.printer = printer
389 | self.heater = heater
390 |
391 | self.duration = 0.0
392 | self.timer_type = timer_type # 0= Time to shutdown, 1= Time to standby.
393 |
394 | self.reactor: "reactor.Reactor" = self.printer.get_reactor()
395 | self.gcode = typing.cast(
396 | "gcode.GCodeDispatch", self.printer.lookup_object("gcode")
397 | )
398 | self.timer_handler = None
399 | self.inside_timer = self.repeat = False
400 | self.printer.register_event_handler("klippy:ready", self.__handle_ready)
401 | self.log = typing.cast("ktc_log.KtcLog", self.printer.lookup_object("ktc_log"))
402 |
403 | self.counting_down = False
404 | self.nextwake = self.reactor.NEVER
405 |
406 | def __handle_ready(self):
407 | self.timer_handler = self.reactor.register_timer(
408 | self._temp_timer_event, self.reactor.NEVER
409 | )
410 |
411 | def _temp_timer_event(self, eventtime):
412 | self.inside_timer = True
413 | self.counting_down = False
414 | self.log.trace(
415 | f"Running heater timer for {self.heater.name}: "
416 | + f"{('Standby' if self.timer_type == HeaterTimerType.TIMER_TO_STANDBY else 'OFF')}"
417 | )
418 |
419 | try:
420 | if self.timer_type == HeaterTimerType.TIMER_TO_STANDBY:
421 | self.log.track_heater_standby_start_for_standby_tools_having_heater(
422 | self.heater
423 | )
424 | self.log.track_heater_active_end_for_tools_having_heater(self.heater)
425 | self.heater.klippy_heater.set_temp(self.heater.standby_temp)
426 | self.heater.timer_heater_active_to_standby_delay.set_timer(NEVER)
427 | self.heater.timer_heater_standby_to_powerdown_delay.set_timer(
428 | self.heater.standby_to_powerdown_delay
429 | )
430 | self.log.trace(
431 | f"Setting temperature to {self.heater.standby_temp} "
432 | + f"for heater {self.heater.name} "
433 | )
434 | else:
435 | self.heater.klippy_heater.set_temp(0)
436 | self.heater.timer_heater_active_to_standby_delay.set_timer(NEVER)
437 | self.heater.timer_heater_standby_to_powerdown_delay.set_timer(NEVER)
438 | self.log.trace(
439 | f"Setting temperature to 0 for heater {self.heater.name} "
440 | )
441 | self.log.track_heater_end_for_tools_having_heater(self.heater)
442 |
443 | except Exception as e:
444 | self.log.always(
445 | f"Failed to run {('Standby' if self.timer_type == 1 else 'OFF')} "
446 | + f"timer for heater {self.heater.name}: {str(e)}"
447 | )
448 | raise Exception(
449 | f"Failed to run{('Standby' if self.timer_type == 1 else 'OFF')} "
450 | + f"timer for heater {self.heater.name}: {str(e)}"
451 | ) from e
452 |
453 | if self.repeat:
454 | self.nextwake = eventtime + self.duration
455 | self.counting_down = True
456 | else:
457 | self.nextwake = self.reactor.NEVER
458 | self.inside_timer = self.repeat = False
459 | return self.nextwake
460 |
461 | def set_timer(self, duration: float):
462 | """Set the timer for the heater and the duration.
463 | If duration is 0, the timer is stopped."""
464 | self.duration = float(duration)
465 | if self.inside_timer:
466 | self.repeat = self.duration != 0.0
467 | else:
468 | waketime = self.reactor.NEVER
469 | if self.duration:
470 | waketime = self.reactor.monotonic() + self.duration
471 | self.nextwake = waketime
472 | self.reactor.update_timer(self.timer_handler, waketime)
473 | self.log.trace(
474 | f"heatertimer set_timer {self.timer_type}: "
475 | + f"duration: {self.duration}, "
476 | + f"nextwake: {self._time_left()} "
477 | f"counting_down: {self.counting_down}"
478 | )
479 | if self.duration:
480 | self.counting_down = True
481 | else:
482 | self.counting_down = False
483 |
484 | self.log.trace(
485 | f"Time until heater {str(self.heater.name)} "
486 | + f"changes to {('Standby' if self.timer_type == 1 else 'OFF')}: "
487 | + f"{self._time_left()}"
488 | )
489 |
490 | def get_status(self, eventtime=None): # pylint: disable=unused-argument
491 | status = {
492 | "timer_type": self.timer_type,
493 | "duration": self.duration,
494 | "counting_down": self.counting_down,
495 | "next_wake": self._time_left(),
496 | }
497 | return status
498 |
499 | def _time_left(self):
500 | if self.nextwake == self.reactor.NEVER:
501 | return "never"
502 | else:
503 | return str(self.nextwake - self.reactor.monotonic())
504 |
505 |
506 | def load_config_prefix(config):
507 | return KtcHeater(config)
508 |
--------------------------------------------------------------------------------
/extensions/ktc_base.py:
--------------------------------------------------------------------------------
1 | # KTC - Klipper Tool Changer code (v.2)
2 | # Base classes and types for KTC to inherit from.
3 | # This file is part of the KTC extension for the Klipper firmware.
4 | # This should not import any other KTC module but can be imported by any KTC module.
5 | #
6 | # Copyright (C) 2024 Andrei Ignat
7 | #
8 | # This file may be distributed under the terms of the GNU GPLv3 license.
9 | #
10 | from __future__ import annotations
11 | import ast, typing, re
12 | import cProfile, pstats, io
13 | from enum import IntEnum, Enum
14 | from .ktc_heater import ( # pylint: disable=relative-beyond-top-level
15 | KtcToolExtruder,
16 | DEFAULT_HEATER_ACTIVE_TO_STANDBY_DELAY,
17 | DEFAULT_HEATER_STANDBY_TO_POWERDOWN_DELAY,
18 | )
19 |
20 |
21 | # Only import these modules in Dev environment. Consult Dev_doc.md for more info.
22 | if typing.TYPE_CHECKING:
23 | from ...klipper.klippy import configfile, gcode, klippy
24 | from ...klipper.klippy.extras import gcode_macro as klippy_gcode_macro
25 | from . import ktc_log, ktc_toolchanger, ktc_tool, ktc, ktc_persisting
26 |
27 | # Value of Unknown and None tools.
28 | TOOL_NUMBERLESS_N = -3
29 | TOOL_UNKNOWN_N = -2
30 | TOOL_NONE_N = -1
31 |
32 | # Parameters available for inheritance by all tools and their default values.
33 | PARAMS_TO_INHERIT = {"_engage_gcode": "",
34 | "_disengage_gcode": "",
35 | "_init_gcode": "",
36 | "_tool_select_gcode": "",
37 | "_tool_deselect_gcode": "",
38 | "force_deselect_when_parent_deselects": True,
39 | "parent_must_be_selected_on_deselect": True,
40 | "_heaters_config": "",
41 | "fans": "",
42 | "offset": [0.0, 0.0, 0.0],
43 | "requires_axis_homed": "XYZ",
44 | "_heater_active_to_standby_delay_in_config":
45 | DEFAULT_HEATER_ACTIVE_TO_STANDBY_DELAY,
46 | "_heater_standby_to_powerdown_delay_in_config":
47 | DEFAULT_HEATER_STANDBY_TO_POWERDOWN_DELAY,
48 | }
49 |
50 | class KtcConfigurableEnum(Enum):
51 | @classmethod
52 | def get_value_from_configuration(cls, config: 'configfile.ConfigWrapper', value_name: str,
53 | default_name: typing.Optional[str] = None):
54 | val = typing.cast(str, config.get(value_name, default_name)) # type: ignore
55 | val = val.strip().upper()
56 | if val == "":
57 | raise ValueError(f"Value {value_name} not found in configuration.")
58 | if val not in cls.list_valid_values():
59 | raise ValueError(f"Value {val} not valid for {value_name}"
60 | +f" in configuration for {config.get_name()}."
61 | + f"Valid values are: {cls.list_valid_values()}")
62 | return cls[val]
63 |
64 | @classmethod
65 | def list_valid_values(cls):
66 | return [str(name) for name in cls.__members__]
67 |
68 | def __str__(self):
69 | return f"'{self.name}'"
70 |
71 | class KtcBaseClass:
72 | """Base class for KTC. Contains common methods and properties."""
73 | def __init__(self, config: "configfile.ConfigWrapper"): # type: ignore
74 | self.config = typing.cast('configfile.ConfigWrapper', config)
75 | self.name: str = ""
76 |
77 | #: To store performance data on startup for later logging.
78 | self.debug_init_profile:str = None # type: ignore
79 |
80 | self.debug_with_profile: bool = False
81 |
82 | # Can contain "X", "Y", "Z" or a combination.
83 | self.requires_axis_homed: str = ""
84 | self._state = self.StateType.NOT_CONFIGURED
85 |
86 | self.force_deselect_when_parent_deselects: bool = None # type: ignore
87 | self.parent_must_be_selected_on_deselect: bool = None # type: ignore
88 |
89 | # If this is a empty object then don't load the config.
90 | if config is None:
91 | return
92 |
93 | self.force_deselect_when_parent_deselects: bool = config.getboolean(
94 | "force_deselect_when_parent_deselects", None) # type: ignore
95 |
96 | self.parent_must_be_selected_on_deselect: bool = config.getboolean(
97 | "parent_must_be_selected_on_deselect", None) # type: ignore
98 |
99 | self.printer : 'klippy.Printer' = config.get_printer()
100 | self.reactor: 'klippy.reactor.Reactor' = self.printer.get_reactor()
101 | self.gcode = typing.cast('gcode.GCodeDispatch', self.printer.lookup_object("gcode"))
102 | self.log: 'ktc_log.KtcLog' = None # type: ignore # We are loading it later.
103 | self._ktc: 'ktc.Ktc' = None # type: ignore # We are loading it later.
104 |
105 | self._state = self.StateType.NOT_CONFIGURED
106 | self.offset: list[float, float, float] = None # type: ignore
107 |
108 | self.params = self.get_params_dict_from_config(config)
109 | # Get inheritable parameters from the config.
110 | # Empty strings are NOT overwritten by the parent object in configure_inherited_params.
111 | # Must be set to None as standard.
112 | # Initalized to default values in KTC as topmost parent.
113 | self._engage_gcode = config.get("engage_gcode", None) # type: ignore
114 | self._disengage_gcode = config.get("disengage_gcode", None) # type: ignore
115 | self._init_gcode = config.get("init_gcode", None) # type: ignore
116 | self._tool_select_gcode = config.get("tool_select_gcode", None) # type: ignore
117 | self._tool_deselect_gcode = config.get("tool_deselect_gcode", None) # type: ignore
118 |
119 | self._heaters_config: str = self.config.get("heater", None) # type: ignore
120 |
121 | # Minimum time is 0.1 seconds. 0 disables the timer thus never changes the temperature.
122 | self._heater_active_to_standby_delay_in_config = self.config.getfloat(
123 | "heater_active_to_standby_delay", None, 0.1) # type: ignore
124 | self._heater_standby_to_powerdown_delay_in_config = self.config.getfloat(
125 | "heater_standby_to_powerdown_delay", None, 0.1) # type: ignore
126 |
127 | # Fans are a list of lists with the first value being the name
128 | # of the fan and the second value being the speed scaling 0-1.
129 | f = typing.cast(str, self.config.get("fans", "")).replace(" ", "")
130 | self.fans = [x.split(":") for x in f.split(",")] if f != "" else []
131 | fan: list[typing.Any]
132 | for fan in self.fans:
133 | errmsg = ("Invalid fan speed scaling for" +
134 | f" {self.config.get_name()}: {fan[0]}. " +
135 | "Fan speed must be a float between 0 and 1.")
136 | if len(fan) == 1:
137 | fan.append(1.0)
138 | elif not self.is_float(fan[1]):
139 | raise config.error(errmsg)
140 | else:
141 | if fan[1] is not None:
142 | fan[1] = fan[1]
143 | if fan[1] < 0 or fan[1] > 1:
144 | raise config.error(errmsg)
145 | if len(fan) != 2:
146 | raise config.error(f"Fan settings for {self.config.get_name()} are invalid.")
147 |
148 | # requires_axis_homed can contain "X", "Y", "Z" or a combination. Remove all other.
149 | self.requires_axis_homed: str = self.config.get(
150 | "requires_axis_homed", None) # type: ignore
151 | if self.requires_axis_homed is not None and self.requires_axis_homed != "":
152 | self.requires_axis_homed = re.sub(r'[^XYZ]', '', self.requires_axis_homed.upper())
153 |
154 | # Initiating values are only red once and then saved to the persistent state and
155 | # must be removed from the config file to continue.
156 | self._initiating_config = {}
157 | # Offset as a list of 3 floats. Also valid for global_offset.
158 | init: str = ""
159 | # Check first if the section exists in the configuration, get_prefix_options will fail otherwise.
160 | if config.has_section(config.get_name()):
161 | for init in config.get_prefix_options("init_"):
162 | init = init.strip().lower()
163 | if 'offset' in init:
164 | try:
165 | if init == "init_global_offset" and self.__class__.__name__ != "Ktc":
166 | raise ValueError(
167 | "init_global_offset is only valid for the topmost KTC object.")
168 | elif init != "init_global_offset" or init == "init_offset":
169 | raise ValueError(
170 | f"Invalid initializing option name {init} "
171 | + "for {self.config.get_name()}.")
172 | v = typing.cast(str, config.get(init)).replace(" ", "")
173 | if v:
174 | vl = [float(x) for x in v.split(",")]
175 | if len(vl) != 3:
176 | raise ValueError(f"{init} must be a list of 3 floats.")
177 | self._initiating_config[init.lstrip("init_")] = vl
178 | except Exception as e:
179 | raise self.config.error(f"Invalid {init} for {self.config.get_name()}: {e}")
180 |
181 | def configure_inherited_params(self):
182 | '''Load inherited parameters from instances that this instance inherits from.
183 | This is called after all instances are loaded.'''
184 | # Ref. to the ktc_persisting object. Loaded by ktc_log.
185 | self._ktc_persistent: 'ktc_persisting.KtcPersisting' = ( # type: ignore # pylint: disable=attribute-defined-outside-init
186 | self.printer.lookup_object("ktc_persisting")
187 | )
188 |
189 | # Check if any initiating values are set.
190 | # offset and global_offset are valid.
191 | if len(self._initiating_config) > 0:
192 | for key in (key for key in self._initiating_config if "offset" in key):
193 | self.persistent_state_set(key, self._initiating_config[key])
194 | raise self.config.error(
195 | f"{key} for {self.config.get_name()} successfully saved as"
196 | + f" {self._initiating_config[key]}. "
197 | + "Remove the setting from config and restart Klipper to continue.")
198 |
199 | # Check for circular inheritance.
200 | if self.state >= self.StateType.CONFIGURED:
201 | return
202 | elif self.state == self.StateType.CONFIGURING:
203 | raise ValueError("Can't configure inherited parameters while already configuring "
204 | + self.config.get_name())
205 | # Ref. to ktc objects.
206 | self._ktc = typing.cast('ktc.Ktc', self.printer.lookup_object("ktc"))
207 | self.log = typing.cast('ktc_log.KtcLog', self.printer.lookup_object(
208 | "ktc_log")) # Load the log object.
209 |
210 | if self.debug_init_profile is not None:
211 | self.log.trace("KTC startup profile: " + str(self.debug_init_profile))
212 |
213 | self.state = self.StateType.CONFIGURING
214 |
215 | # Get Offset from persistent storage
216 | self.offset = self.persistent_state.get("offset", None)
217 |
218 | # Set the parent object
219 | if isinstance(self, KtcBaseToolClass):
220 | parent = self.toolchanger
221 | elif isinstance(self, KtcBaseChangerClass):
222 | parent = self.parent_tool
223 | if parent is None:
224 | parent = typing.cast('ktc.Ktc', self.printer.lookup_object("ktc"))
225 | elif isinstance(self, KtcBaseClass):
226 | parent = self
227 | else:
228 | raise ValueError("Can't configure inherited parameters for object: " + str(type(self)))
229 |
230 | if self != parent:
231 | # Set the parameters from the parent object if they are not set.
232 | for attr, _ in PARAMS_TO_INHERIT.items():
233 | if getattr(self, attr) is None:
234 | setattr(self, attr, getattr(parent, attr))
235 | else:
236 | # For top ktc object initialize unused parameters.
237 | for attr, default_value in PARAMS_TO_INHERIT.items():
238 | if getattr(self, attr) is None:
239 | setattr(self, attr, default_value)
240 |
241 | for v in parent.params: # type: ignore
242 | if v not in self.params:
243 | self.params[v] = parent.params[v] # type: ignore
244 |
245 | @staticmethod
246 | def get_params_dict_from_config(config: 'configfile.ConfigWrapper'):
247 | """Get a dict of atributes starting with params_ from the config."""
248 | result = {}
249 |
250 | if config is None or not config.has_section(config.get_name()):
251 | return result
252 |
253 | # Get all options that start with "params_" and add them to the result dict.
254 | for option in config.get_prefix_options("params_"):
255 | try:
256 | value : str = config.get(option)
257 | # Boolean:
258 | if value.lower().strip() in ("true", "false"):
259 | result[option] = config.getboolean(option)
260 | # Integer:
261 | elif value.replace("-", "").replace(" ", "").isdigit():
262 | result[option] = config.getint(option)
263 | # Float:
264 | elif value.replace(".", "").replace("-", "").replace(" ", "").isdigit():
265 | result[option] = config.getfloat(option)
266 | # List of Integers:
267 | elif value.replace("-", "").replace(" ", "").replace(",", "").isdigit():
268 | result[option] = [int(x) for x in value.split(",")]
269 | # List of Floats:
270 | elif value.replace(".", "").replace("-", "").replace(
271 | " ", "").replace(",", "").isdigit():
272 | result[option] = [float(x) for x in value.split(",")]
273 | # String with quotes:
274 | elif value.startswith('"') and value.endswith('"'):
275 | result[option] = ast.literal_eval(value)
276 | # String with single quotes:
277 | elif value.startswith("'") and value.endswith("'"):
278 | result[option] = ast.literal_eval(value)
279 | # Check if it is a valid String:
280 | else:
281 | result[option] = ast.literal_eval('"' + value + '"')
282 | except ValueError as e:
283 | raise config.error(
284 | "Option '%s' in section '%s' is not a valid literal: %s."
285 | % (option, config.get_name(), e)
286 | )
287 | return result
288 |
289 | class StateType(IntEnum, KtcConfigurableEnum):
290 | """Constants for the status of the toolchanger.
291 | Using dataclasses to allow for easy traversal of the values."""
292 | ERROR= -50 # Toolchanger or tool is in error state.
293 | NOT_CONFIGURED = -12 # Toolchanger or tool is not configured.
294 | CONFIGURING = -11 # Toolchanger or tool is configuring.
295 | CONFIGURED = -10 # Toolchanger or tool is configured but not initialized.
296 | UNINITIALIZED = -2 # Toolchanger or tool is uninitialized.
297 | INITIALIZING = -1 # Toolchanger or tool is initializing.
298 | INITIALIZED = 0 # Toolchanger or tool is initialized but not ready.
299 | READY = 1 # Toolchanger or tool is ready to be used.
300 | CHANGING = 2 # Toolchanger or tool is changing tool.
301 | ENGAGING = 3 # Toolchanger is engaging.
302 | SELECTING = 3 # Tool is selecting.
303 | DISENGAGING = 4 # Toolchanger or tool is disengaging.
304 | DESELECTING = 4 # Tool is deselecting.
305 | ENGAGED = 5 # Tollchanger or tool is engaged.
306 | SELECTED = 5 # Tool is selected.
307 | ACTIVE = 10 # Tool is active as main engaged tool for ktc.
308 |
309 | @classmethod
310 | def list_valid_values(cls):
311 | return [name for name, _ in cls.__members__]
312 |
313 | def __str__(self):
314 | return f'{self.name}'
315 |
316 | @property
317 | def state(self):
318 | return self._state
319 | @state.setter
320 | def state(self, value):
321 | try:
322 | self._state = self.StateType[str(value).upper()]
323 | except KeyError as e:
324 | raise ValueError("Invalid state value: " + str(value)) from e
325 |
326 |
327 | @property
328 | def persistent_state(self) -> dict:
329 | '''Return the persistent state from file.
330 | Is initialized inside _handle_connect.
331 | Use persistent_state_set to set the state.'''
332 | c = self._get_type_for_persistent_state()
333 | v: dict = self._ktc_persistent.content.get("State", {})
334 | return v.get(c, {})
335 |
336 | def persistent_state_set(self, key: str, value: typing.Any):
337 | '''Set the persistent state for the object. Use persistent_state to get the state.'''
338 | c = self._get_type_for_persistent_state()
339 |
340 | state: dict = self._ktc_persistent.content.get("State", {}).get(c, {})
341 | state[key] = value
342 |
343 | self._ktc_persistent.save_variable(c, str(state), "State", True)
344 |
345 | def _get_type_for_persistent_state(self) -> str:
346 | if self._ktc_persistent is None:
347 | self._ktc_persistent: 'ktc_persisting.KtcPersisting' = ( # type: ignore # pylint: disable=attribute-defined-outside-init
348 | self.printer.lookup_object("ktc_persisting")
349 | )
350 | if isinstance(self, KtcBaseToolClass):
351 | return "ktc_tool_" + self.name.lower()
352 | elif isinstance(self, KtcBaseChangerClass):
353 | return "ktc_toolchanger_" + self.name.lower()
354 | elif isinstance(self, KtcBaseClass):
355 | return "ktc"
356 | else:
357 | raise ValueError(f"Can't get persistent state for object: {type(self)}")
358 |
359 | @staticmethod
360 | def is_float(value: str) -> bool:
361 | try:
362 | float(value)
363 | return True
364 | except ValueError:
365 | return False
366 |
367 | @staticmethod
368 | def parse_bool(value: str) -> bool:
369 | if value.isnumeric():
370 | return bool(int(value))
371 | return value.strip().lower() in ("true", "1", "yes")
372 |
373 | def run_with_profile(self, method, *args, **kwargs):
374 | '''Run a profile on a method. Used for debugging.'''
375 | if not self.run_with_profile:
376 | method(*args, **kwargs)
377 | return
378 | pr = cProfile.Profile()
379 | pr.enable()
380 | method(*args, **kwargs)
381 | pr.disable()
382 | s = io.StringIO()
383 | ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
384 | ps.print_stats()
385 | stats_string = s.getvalue()
386 | s.close()
387 |
388 | # Trim to 20 lines.
389 | carriage_return_count = stats_string.count('\n')
390 | if carriage_return_count >= 20:
391 | index = -1
392 | for _ in range(20):
393 | index = stats_string.find('\n', index + 1)
394 | # index now contains the index of the 10th carriage return
395 | else:
396 | index = len(stats_string) - 1
397 |
398 | self.log.trace(
399 | f"Performance profile for {method.__name__}:\n" + stats_string[:index])
400 |
401 | class KtcBaseChangerClass(KtcBaseClass):
402 | '''Base class for toolchangers. Contains common methods and properties.'''
403 | def __init__(self, config: 'configfile.ConfigWrapper'):
404 | super().__init__(config)
405 | self.name: str = str(config.get_name()).split(" ", 1)[1]
406 | # The parent tool of the toolchanger if it is not default changer.
407 | self.parent_tool: 'ktc_tool.KtcTool' = None # type: ignore
408 | # self.selected_tool = KtcConstantsClass.TOOL_NONE
409 | self.tools: dict[str, 'ktc_tool.KtcTool'] = {}
410 | self._engage_gcode_template: klippy_gcode_macro.GCodeMacro = None # type: ignore
411 | self._disengage_gcode_template: klippy_gcode_macro.GCodeMacro = None # type: ignore
412 |
413 | class KtcBaseToolClass(KtcBaseClass):
414 | '''Base class for tools. Contains common methods and properties.'''
415 | def __init__(self, config: "configfile.ConfigWrapper",
416 | name: str = "", number: int = TOOL_NUMBERLESS_N):
417 | super().__init__(config)
418 |
419 | self.name = name # Override the name in case it is supplied.
420 | self.number = number
421 | # Is overridden by the tool object.
422 | self._toolchanger: 'ktc_toolchanger.KtcToolchanger' = None # type: ignore
423 | self.toolchanger: 'ktc_toolchanger.KtcToolchanger' = self._toolchanger # type: ignore
424 | self.extruder = KtcToolExtruder(self)
425 |
426 | @KtcBaseClass.state.setter
427 | def state(self, value):
428 | '''Set state of the tool. If the tool is selected or active then the toolchanger
429 | is also set to the same state.'''
430 | super(KtcBaseToolClass, type(self)).state.fset(self, value) # type: ignore
431 |
432 | # TOOL_UNKNOWN and TOOL_NONE has no _ktc object.
433 | if self in KtcConstantsClass.INVALID_TOOLS:
434 | return
435 |
436 | if self._ktc.propagate_state:
437 | self.toolchanger.state = value
438 |
439 | if value == self.StateType.SELECTED and self._ktc.propagate_state:
440 | self.toolchanger.selected_tool = self # type: ignore # Child class
441 | elif value == self.StateType.ACTIVE and self._ktc.propagate_state:
442 | self.toolchanger.selected_tool = self # type: ignore # Child class
443 | self._ktc.active_tool = self
444 |
445 | if value == self.StateType.ERROR:
446 | self.log.always("KTC Tool %s is now in error state." % self.name)
447 |
448 | def select(self, final_selected=False):
449 | pass
450 |
451 | def deselect(self):
452 | pass
453 |
454 | class KtcConstantsClass:
455 | '''Constants for KTC. These are to be inherited by other classes.
456 | '''
457 | # Value of Unknown and None tools are set in module scope.
458 | TOOL_NUMBERLESS_N = TOOL_NUMBERLESS_N
459 | TOOL_UNKNOWN_N = TOOL_UNKNOWN_N
460 | TOOL_NONE_N = TOOL_NONE_N
461 | TOOL_UNKNOWN = typing.cast(
462 | 'ktc_tool.KtcTool',
463 | KtcBaseToolClass(name="tool_unknown",
464 | number=TOOL_UNKNOWN_N,
465 | config = None)) # type: ignore
466 | TOOL_NONE = typing.cast(
467 | 'ktc_tool.KtcTool',
468 | KtcBaseToolClass(name="tool_none",
469 | number=TOOL_NONE_N,
470 | config = None)) # type: ignore
471 | TOOL_NONE._state = TOOL_UNKNOWN._state = KtcBaseClass.StateType.CONFIGURED # pylint: disable=protected-access
472 | INVALID_TOOLS = (TOOL_UNKNOWN, TOOL_NONE, None)
473 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------