Showing preview only (252K chars total). Download the full file or copy to clipboard to get everything.
Repository: TypQxQ/Klipper_ToolChanger
Branch: master
Commit: 0ae005a540da
Files: 35
Total size: 240.6 KB
Directory structure:
gitextract_03dvn_i_/
├── LICENSE
├── README.md
├── assets/
│ └── q
├── config/
│ ├── SuperSlicer_Custom_Gcode.md
│ ├── example_complex/
│ │ ├── readme.md
│ │ ├── tool_macro.cfg
│ │ └── tools.cfg
│ ├── example_simple/
│ │ ├── readme.md
│ │ └── tools.cfg
│ ├── optional_macros/
│ │ ├── G10.cfg
│ │ ├── M104.cfg
│ │ ├── M106.cfg
│ │ ├── M107.cfg
│ │ ├── M109.cfg
│ │ ├── M116.cfg
│ │ ├── M204.cfg
│ │ ├── M568.cfg
│ │ └── readme.md
│ └── readme.md
├── doc/
│ └── command_ref.md
├── install.sh
├── klipper_macros/
│ ├── G10.cfg
│ ├── M104.cfg
│ ├── M106.cfg
│ ├── M107.cfg
│ ├── M109.cfg
│ ├── M116.cfg
│ ├── M204.cfg
│ ├── M566.cfg
│ ├── M568.cfg
│ └── readme.md
├── ktcclog.py
├── tool.py
├── toolgroup.py
└── toollock.py
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
<p align="center">
<img src="assets/toolchanger.jpg?raw=true" alt='A Toolchenager' width='40%'>
<h1 align="center">Tools for klipper (KTCC - Klipper Tool Changer Code)</h1>
</p>
<p align="center">
Universal Toolchanger driver for Klipper
</p>
This are python modules, macros and example config for the
[Klipper 3D printer firmware](https://github.com/Klipper3d/klipper) to be able to work as a toolchanger.
<p align="center">
<a aria-label="Downloads" href="https://github.com/TypQxQ/Klipper_ToolChanger/releases">
<img src="https://img.shields.io/github/release/TypQxQ/Klipper_ToolChanger?display_name=tag&style=flat-square">
</a>
<a aria-label="Stars" href="https://github.com/TypQxQ/Klipper_ToolChanger/stargazers">
<img src="https://img.shields.io/github/stars/TypQxQ/Klipper_ToolChanger?style=flat-square">
</a>
<a aria-label="Forks" href="https://github.com/TypQxQ/Klipper_ToolChanger/network/members">
<img src="https://img.shields.io/github/forks/TypQxQ/Klipper_ToolChanger?style=flat-square">
</a>
<a aria-label="License" href="https://github.com/TypQxQ/Klipper_ToolChanger/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/TypQxQ/Klipper_ToolChanger?style=flat-square">
</a>
</p>
Klipper Tool Changer code v.2 is now released for preview:
https://github.com/TypQxQ/KTC
At it's simplest you need to specify extruder, fan, offset for each extruder tool.
Then add your macros for pickup, dropoff, toollock and toolunlock.
It doesn't matter if you lock the tool by a servo, stepper or moving the toolhead in a special way. Just as long as it can be written in GCODE.
Pickups are also custom Gcode. You can uses the parameters stored for each tool to aproach he ZONE fast, slow in
to PARKING place and lock. Or it have a robotic arm place the tool. It's all posible. :D
[This](https://www.youtube.com/watch?v=cbRXn7R7JZM&t=52s) is a more complex example of it running on a toolchanger with an aditional ERCF under one tool. T0-8 uses first tool with virtual tools for the ERCF, calling the toolchanges recursively.
Inspiration comes mainly from how RRF enables toolchanging and from the HappyHare project.
I welcome any and all input and contributions. Don't be afraid to make a pull request :D
Thank you!
## Readme Table of Contents
**[Major feature](#---major-features)**<br>
**[Installation](#---installation)**<br>
\- [1-Install with Moonraker Autoupdate Support](#1-install-with-moonraker-autoupdate-support)<br>
\- [2-Manual Install](#2-manual-install)<br>
**[Configuration requirements](#---configuration-requirements)**<br>
**[G-Code commands](#---g-code-commands)**<br>
**[Values accesible from Macro for each object](#---values-accesible-from-macro-for-each-object)**<br>
**[Example configuration](#---example-configuration)**<br>
#### Other Docs:
**[Command Reference](./doc/command_ref.md)**<br>
**[Required and Optional Macros](./klipper_macros/readme.md)**<br>
**[Configuration Reference](./config/readme.md)**<br>
<br>
##    Major features:
<ul>
<li>Support any type of toolchanger and any type of tool</li>
<li>Tools don't need to be extruders/hotends, can be anything.</li>
<li>Each Tool is treated as an object and has it's own configuration having configurable coordinates for parking, tool offset, extruder, part cooling fan, etc.</li>
<li>Tools don't need to be extruders/hotends, can be anything.</li>
<li>Virtual tools - One tool can have multiple tools. Your T0-T8 can be on same extruder, fan and heater but having an MMU while T9 is another extruder and T10-T12 is another tool with 3 markers that can switched by a servo and finally T13 is a pick and place tool.</li>
<li>Multiple tools can be grouped in ToolGroup. -Most configuration can be inherited from the group and overwritten when needed by the tool config section.</li>
<li>Partcooling Fan speed is carried over on toolchange if the tool has a fan. M106/M107 defaults to fan of current_tool but can also specify another tool.</li>
<li>Extensive extruder temperature control:</li>
<ul>
<li>A tool heater can be set as Active, Standby or Off mode</li>
<li>Diffrent Active and Standby temperatures for any tool. Switches to Active when selected and to Standby when Parked.</li>
<li>Configurable delay from Standby to off when parked. If tool isn't used for 30 minutes it cools down until used again.</li>
<li>Wait to reach temperature with configurable tolerance.</li>
<li>Position prior to toolchange can optionaly be saved and restored after toolchange. Configurable axis.</li>
</ul>
<li>Current Tool persists at powerdown. Default but optional.</li>
<li>Tool remaping. Remap a tool to another, no need to reslice.</li>
<li>Sophisticated logging options (console and ktcc.log file)</li>
<li>Moonraker update-manager support</li>
<li>Persitance of state and statistics across restarts.</li>
<li>Vast customization options!</li>
</ul>
<br>
##    Installation
### 1\. Install with Moonraker Autoupdate Support
This plugin assumes that you installed Klipper into your home directory (usually `/home/pi`).
1) Clone this repo into your home directory where Klipper is installed:
```
cd ~
git clone https://github.com/TypQxQ/Klipper_ToolChanger.git
```
2) Edit `moonraker.conf` by adding the following entry:
```
[update_manager client klipper_toolchanger]
type: git_repo
path: ~/Klipper_ToolChanger
origin: https://github.com/TypQxQ/Klipper_ToolChanger.git
install_script: install.sh
is_system_service: False
```
3) Run the `install.sh` script
```
~/Klipper_ToolChanger/install.sh
```
Klipper_ToolChanger will show up in the update the next time you restart moonraker, or you can restart mooraker right away with: `sudo systemctl restart moonraker`.
If you encouter errors after an automatic Klipper update you can safetly run the `install.sh` scipt again to repair the links to the extension.
### 2\. Manual Install
Copy the python (`*.py`) files into the `\klipper\klipper\extras` directory. Assuming Klipper is installed in your home directory:
```
cp ./*.py ~/klipper/klippy/extras/
```
Then restart Klipper to pick up the extensions.
##    Configuration requirements
* `[input_shaper]` needs to be used for input shaper to wordk.
##    G-Code commands:
Reffer to the [Command Reference](./doc/command_ref.md).<br>
##    Values accesible from Macro for each object
- **Toollock**
- `global_offset` - Global offset.
- `tool_current` - -2: Unknown tool locked, -1: No tool locked, 0: and up are toolnames.
- `saved_fan_speed` - Speed saved at each fanspeedchange to be recovered at Toolchange.
- `purge_on_toolchange` - For use in macros to enable/disable purge/wipe code globaly.
- `restore_axis_on_toolchange` - The axis to restore position:
- : No restore
- XY: Restore XY
- XYZ: Restore XYZ
- Etc
- `saved_position` - The position saved when the latest T# command had a RESTORE_POSITION parameter to other than 0
- **Tool** - The tool calling this macro is referenced as `myself` in macros. When running for example `T3` to pickup the physical tool, in `pickup_gcode:` of one can write `{myself.name}` which would return `3`.
- `name` - id. 0, 1, 2, etc.
- `is_virtual` - If this tool has another layer of toolchange possible.
- `physical_parent_id` - Parent physical tool that holds tool coordinates. Can be same as this.
- `extruder` - extruder name as configured.
- `fan` - fan name.
- `lazy_home_when_parking` - When set to 1, will home unhomed XY axes if needed and will not move any axis if already homed and parked. 2 Will also home Z if not homed.
- `meltzonelength` - Meltzonelength to unload/load filament at toolpak. See e3d documentation.
- `zone` - Fast aproach coordinates when parking
- `park` - Parking spot, slow aproach.
- `offset` - Tool offset.
- `heater_state` - 0 = off, 1 = standby temperature, 2 = active temperature. Placeholder.
- `heater_active_temp` - Temperature to set when in active mode.
- `heater_standby_temp` - Temperature to set when in standby mode.
- `idle_to_standby_time` - Time in seconds from being parked to setting temperature to standby the temperature above. Use 0.1 to change imediatley to standby temperature.
- `idle_to_powerdown_time` - Time in seconds from being parked to setting temperature to 0. Use something like 86400 to wait 24h if you want to disable. Requred on Physical tool.
- **ToolGroup**
- `is_virtual` - As above
- `physical_parent_id` - As above
- `lazy_home_when_parking` - As above
##    Example configuration
My corrent configuration is for v.2 where work progresses fast.
##    Updates 21/09/2023
Added individual axis to position saving and restoring commands. Commited by viesturz.
##    Updates 09/03/2023
Added Tool Remap. Point one or more tools to another one. Including fan and temperature. This is persistent at reboot.
* `KTCC_DISPLAY_TOOL_MAP` - Display the current mapping of tools to other KTCC tools.
* `KTCC_REMAP_TOOL` - The command to remap a tool or reset the remaping.
* `KTCC_CHECK_TOOL_REMAP` - Display all tool remaps.
##    Updates 08/03/2023
Added per print statistics and a wrapper around G28 to disable saving statistics while homing.
The latter led to MCU Timer to close error when loading a tool at homing.
* `KTCC_INIT_PRINT_STATS` - Run at start of a print to reset the KTCC print statistics.
* `KTCC_DUMP_PRINT_STATS` - Run at end of a print to list statistics since last print reset.
##    Updates 22/02/2023
This is not a simple upgrade, it has some configuration updates.
A namechange to KTCC (Klipper Tool Changer Code) is also in the works).
- **News:**
- Virtual Tools
- Logfile
- Statistics
- **Changes to Configuration:**
- LogLevel under ToolLock is deprecated.
- Must include new section ```[ktcclog]``` before all other Toollock, tool, and the others..
- New ```virtual_toolload_gcode:`` parameter to tools.
- New ```virtual_toolunload_gcode:`` parameter to tools.
- **Changes to commands:**
- T_1 => KTCC_TOOL_DROPOFF_ALL
- T# => KTCC_T# (ex. T0 => KTCC_T0)
- **New commands:**
- KTCC_SET_GCODE_OFFSET_FOR_CURRENT_TOOL
- KTCC_LOG_TRACE
- KTCC_LOG_DEBUG
- KTCC_LOG_INFO
- KTCC_LOG_ALWAYS
- KTCC_SET_LOG_LEVEL
- KTCC_DUMP_STATS
- KTCC_RESET_STATS
================================================
FILE: assets/q
================================================
================================================
FILE: config/SuperSlicer_Custom_Gcode.md
================================================
Here are the custom G-codes I use in SuperSlicer on my ToolChanger as an example.
Start G-code:
- I don't heat the tools before actually using them so I don't degrade filament.
- Using e3d Revo the heatup times for the tools are verry fast.
```
KTCC_INIT_PRINT_STATS
; Don't heat the tools yet. (Using G10 so SuperSlicer and PrusaSlicer recognizes we set a tool temperature)
G10 P0 R0 S0 A0 ; Don't heat the tools yet. (Using G10 so SuperSlicer and PrusaSlicer recognizes we set a tool temperature)
G10 P1 R0 S0 A0 ; Don't heat the tools yet
G10 P2 R0 S0 A0 ; Don't heat the tools yet
; Heat the bed first
M140 S[first_layer_bed_temperature]
; Wait for bed to reach temperature with 2 degrees tolerance
M116 H0 S2 ; Wait for bed to reach temperature with 2 degrees tolerance
M568 P[initial_extruder] R{filament_toolchange_temp[initial_extruder]} S{first_layer_temperature[initial_extruder]+extruder_temperature_offset[initial_extruder]} A1
G28
;Custom Mesh only on print area
BED_MESH_CALIBRATE AREA_START={first_layer_print_min[0]},{first_layer_print_min[1]} AREA_END={first_layer_print_max[0]},{first_layer_print_max[1]}
G0 Z3 F5000 ; Ensure nozzle is at 3mm over the bed
SAVE_POSITION X={first_layer_print_max[0]} Y={first_layer_print_min[1]}
T[initial_extruder] ; Mount extruder first used (even if only one extruder used). Waits for temperature inside the script.
;G0 Z3 F5000 ; Ensure nozzle is at 3mm over the bed
G0 X{first_layer_print_max[0]} Y{first_layer_print_min[1]} Z3 F30000
```
End G-code
```
; Custom gcode to run at end of print
M104 S0 ; turn off temperature
G10 P0 S0 R0 A0 ; turn off extruder 0
G10 P1 S0 R0 A0 ; turn off extruder 1
G10 P2 S0 R0 A0 ; turn off extruder 2
M140 S0 ; turn off bed
T_1 ; dropoff current tool
G91 ; relative moves
G0 Z20 ; move bed down another 30mm
G90 ; absolute moves
G0 X1 Y1 F30000 ; Move toolhead out of the way
SAVE_POSITION ; Reset saved position.
KTCC_DUMP_PRINT_STATS ; Print statistics to console.
```
ToolChange G-code
- Sets the temperature before activating the tool in case this is the first time the tool is selected.
- On first layer it sets the temperature for the next tool to first layer temperature.
```
{if layer_num < 2}M568 P[next_extruder] R{filament_toolchange_temp[next_extruder]} S{first_layer_temperature[next_extruder]+extruder_temperature_offset[next_extruder]} A2 ;First layer temperature for next extruder
{else}M568 P[next_extruder] R{filament_toolchange_temp[next_extruder]} S{temperature[next_extruder]+extruder_temperature_offset[next_extruder]} A2 ;Other layer temperature for next extruder
{endif}
T{next_extruder}```
================================================
FILE: config/example_complex/readme.md
================================================
# More complex example
This are example files with macros to get you started.
* It uses T0 as a physical tool having T1-T8 as virtual tools.
* T9 and T10 are physical tools without virtual tools.
* T49 is a physical tool without a heater, fan or extruder. Only has a Z probe.
The files should be added to your printer.cfg like:
```
[include custom/tools.cfg]
[include custom/tools.cfg]
```
This is for use with a Jubilee style printer.
================================================
FILE: config/example_complex/tool_macro.cfg
================================================
[gcode_macro TOOL_LOCK_CHECK]
description: Check so the tool is mounted by slightly advancing the lock again until hit endstop, only if endstop not already hit. Do not wait for it to finish.
gcode:
# If endstop is not triggered then try to lock again for safety. Best to check the endstops before calling this.
{% if printer.query_endstops.last_query['manual_stepper tool_lock']|default(0) == 0 %}
SET_TMC_CURRENT STEPPER=tool_lock CURRENT=1.0
MANUAL_STEPPER STEPPER=tool_lock Move=20 SPEED=50 STOP_ON_ENDSTOP=1 SYNC=0
SET_TMC_CURRENT STEPPER=tool_lock CURRENT=0.8
{% endif %}
[gcode_macro M106]
variable_fan_speed: 0
description: Snnn Pnnn
Set fan speed. A tool and toollock must be configured for this to work.
S: Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
P: Tool (optional, defaults to the currently selected tool)
The P parameter specifies tool instead of fan number as in RRF.
gcode:
{% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
# S= Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
{% if params.S is defined %}
{% set newparameters = newparameters ~ " S="~params.S %} # Set heater_standby_temp to new parameters.
{% endif %}
# P= Tool number
{% if params.P is defined %}
{% set newparameters = newparameters ~ " P="~params.P %} # Set heater_standby_temp to new parameters.
{% endif %}
SET_AND_SAVE_FAN_SPEED{newparameters}
[gcode_macro M107]
description: Pnnn
Turn off fan.
P = Tool (optional and defaults to the currently selected tool)
gcode:
{% if params.P is defined %}
{% set p = " P"~params.P %}
{% endif %}
M106 {p|default("")} S0
[gcode_macro G10]
description: See M568. Passtrough to M568.
gcode:
M568 {rawparams}
[gcode_macro M568]
description: Pnnn Rnnn Snnn An Nnnn Mnnn
Set tool temperature.
P= Tool number, optional. If this parameter is not provided, the current tool is used.
R= Standby temperature(s), optional
S= Active temperature(s), optional
A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature(s).
N = Time in seconds to wait between changing heater state to standby and setting heater target temperature to standby temperature when standby temperature is lower than tool temperature.
Use for example 0.1 to change immediately to standby temperature.
O = Time in seconds to wait from docking tool to shutting off the heater, optional.
Use for example 86400 to wait 24h if you want to disable shutdown timer.
gcode:
# RESPOND MSG="M568: Seting new temperature: {rawparams}"
{% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
# P= Tool number
{% if params.P is defined %}
{% set newparameters = newparameters ~ " TOOL="~params.P %} # Set heater_standby_temp to new parameters.
{% endif %}
# R= Standby temperature
{% if params.R is defined %}
{% set newparameters = newparameters ~ " STDB_TMP="~params.R %} # Set heater_standby_temp to new parameters.
{% endif %}
# S= Active temperature
{% if params.S is defined %}
{% set newparameters = newparameters ~ " ACTV_TMP="~params.S %} # Set heater_active_temp to new parameters.
{% endif %}
# N = Time in seconds to wait from docking tool to putting the heater in standy
{% if params.N is defined %}
{% set newparameters = newparameters ~ " STDB_TIMEOUT="~params.N %} # Set idle_to_standby_time to new parameters.
{% endif %}
# M = Time in seconds to wait from docking tool to shuting off the heater
{% if params.O is defined %}
{% set newparameters = newparameters ~ " SHTDWN_TIMEOUT="~params.O %} # Set idle_to_powerdown_time to new parameters.
{% endif %}
# A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature
{% if params.A is defined %}
{% set newparameters = newparameters ~ " CHNG_STATE="~params.A %} # Set idle_to_powerdown_time to new parameters.
{% endif %}
{action_respond_info("M568: Running: SET_TOOL_TEMPERATURE"~newparameters)}
SET_TOOL_TEMPERATURE{newparameters}
[gcode_macro M116]
description: Pnnn Hnnn Snnn
Waits for all temperatures, or a specified tool or heater's temperature.
This command can be used without any additional parameters.
Without parameters it waits for bed and current extruder.
Only one of either P or H may be used.
Pnnn Tool number.
Hnnn Heater number. 0="heater_bed", 1="extruder", 2="extruder1", etc.
Snnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
gcode:
{% set newparameters = "" %} # Parameters to be passed to subroutine in new format.
{% if params.P is defined %}
{% set newparameters = newparameters ~ " TOOL=" ~ params.P %} # Set Tool to new parameters.
{% endif %}
{% if params.H is defined %}
{% set newparameters = newparameters ~ " HEATER=" ~ params.H %} # Set Tool to new parameters.
{% endif %}
{% if params.S is defined %}
{% set newparameters = newparameters ~ " TOLERANCE=" ~ params.S %} # Set Tool to new parameters.
{% endif %}
TEMPERATURE_WAIT_WITH_TOLERANCE{newparameters}
[gcode_macro TOOL_DROPOFF]
gcode:
KTCC_TOOL_DROPOFF_ALL
[gcode_macro SAVE_ACCELERATION]
variable_max_accel: 0
gcode:
SET_GCODE_VARIABLE MACRO=SAVE_ACCELERATION VARIABLE=max_accel VALUE={printer.toolhead.max_accel}
[gcode_macro RESTORE_ACCELERATION]
gcode:
{% if printer['gcode_macro SAVE_ACCELERATION'].max_accel|int == 0 %}
{ action_respond_info("RESTORE_ACCELERATION: No acceleration saved.") }
{% else %}
M204 S{printer['gcode_macro SAVE_ACCELERATION'].max_accel}
{% endif %}
================================================
FILE: config/example_complex/tools.cfg
================================================
# Config order: ToolGroups must come before tools that use them. Tool that are used as physical_parent must be configured before other virtual tools that use that as parent.
# Enables saving of variables between powerdown of machine. Must be configured before [toollock].
[save_variables]
filename: ~/variables.cfg
[ktcclog] # Log_level & logfile_level can be set to one of (0 = essential, 1 = info, 2 = debug, 3 = trace)
log_level: 2
logfile_level: 3
[toollock]
purge_on_toolchange = True # Here we can disable all purging. When disabled it overrides all other purge options. Defaults to true. This can be turned off by a macro for automatic probing hot tools without probing them. For example when doing TAMV or ZTATP.
global_offset = 0,0,0
#init_printer_to_last_tool = True #Initialise as it was turned off, unlock tool if none was loaded or lock if one was loaded. Defaults to True
tool_lock_gcode:
SAVE_GCODE_STATE NAME=tool_unlock_state # Save gcode state
MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=0 # Set assumed possition as rotated to min
MANUAL_STEPPER STEPPER=tool_lock Move=1 SPEED=30 STOP_ON_ENDSTOP=-1 SYNC=1 # Move until no longer endstop is triggered, max 1degree. If Endstop is not untriggered then raise an error. Wait for the movement before continuing.
SET_TMC_CURRENT STEPPER=tool_lock CURRENT=1.0 # Raise current of stepper temporarily
MANUAL_STEPPER STEPPER=tool_lock Move=150 SPEED=50 STOP_ON_ENDSTOP=1 SYNC=1 # Move to max and stop on endstop. If Endstop is not triggered then raise an error. Wait for the movement before continuing.
M400
MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=0 # Set manual extruder position as 0
SET_TMC_CURRENT STEPPER=tool_lock CURRENT=0.7 # Decrease current to standard current.
RESTORE_GCODE_STATE NAME=tool_unlock_state MOVE=0 # Restore gcode state
M117 "Unknown tool Loaded" # Tool Loaded Message that stays on display.
tool_unlock_gcode:
SAVE_GCODE_STATE NAME=tool_lock_state # Save gcode state
MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=180 # Set assumed possition as rotated to max
MANUAL_STEPPER STEPPER=tool_lock Move=179 SPEED=30 STOP_ON_ENDSTOP=-1 SYNC=1 # Move until no longer endstop is triggered, max 1degree. If Endstop is not untriggered then raise an error. Wait for the movement before continuing.
MANUAL_STEPPER STEPPER=tool_lock Move=0 SPEED=100 STOP_ON_ENDSTOP=1 SYNC=1 # Move to min and stop on endstop. If Endstop is not triggered then raise an error. Wait for the movement before continuing.
M400
MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=0 # Set manual extruder position as 0
MANUAL_STEPPER STEPPER=tool_lock ENABLE=0 # Turn off the stepper while unlocked so it can rest without triggering the endswitch
RESTORE_GCODE_STATE NAME=tool_lock_state MOVE=0 # Restore gcode state
M117 Tool Unloaded # Tool UnLoaded Message that stays on display.
[toolgroup 0]
is_virtual: True # If True then must have a physical_parent declared and shares extruder, hotend and fan with the physical_parent
physical_parent: 0 # Tool used as a Physical parent for all toos of this group. Only used if the tool i virtual.
#idle_to_standby_time: 30
#idle_to_powerdown_time: 600
virtual_toolload_gcode:
# Because the virtual tools match the number on ERCF I just call that.
SUB_VIRTUALTOOL_LOAD T={myself.name}
virtual_toolunload_gcode:
SUB_VIRTUALTOOL_UNLOAD T={myself.name}
# Used to group several tools with similar settings.
[toolgroup 1]
is_virtual: False # If True then must have a physical_parent declared and shares extruder, hotend and fan with the physical_parent
pickup_gcode:
SUB_TOOL_PICKUP_START T={myself.name}
SUB_TOOL_PICKUP_END T={myself.name}
dropoff_gcode:
SUB_TOOL_DROPOFF_START T={myself.name}
SUB_TOOL_DROPOFF_END T={myself.name}
##### Selectable tool. Must be configured after [toolgroup n].
[tool 0]
tool_group: 0 # Must be used and configured before this tool
##### Following can be inherited from Physical parent if not specified for this tool. Needed only by physical tools.
extruder: extruder
fan: partfan_t0
zone: 550,5
park: 598,5
offset: 11.406,3.778,3.537
#####
##### Following can be inherited from ToolGroup if not specified for this tool or inherited from a Physical parent.
#physical_parent: # Defaults to None.
#is_virtual: False # Defaults to False
meltzonelength: 14 #18 # Defaults to 0
#####
##### Options below have no effect on Virtual tools.
idle_to_standby_time: 0.1 # Time in seconds from being parked to setting temperature to standby the temperature above. Use 0.1 to change imediatley to standby temperature. Defaults to 30
#idle_to_powerdown_time: 600 # Time in seconds from being parked to setting temperature to 0. Use something like 86400 to wait 24h if you want to disable. Defaults to 600
lazy_home_when_parking: 1 # (default: 0 - disabled) - When set to 1, will home unhomed XY axes if needed and will not move any axis if already homed and parked. 2 Will also home Z if not homed.
shaper_freq_x: 137.2
shaper_freq_y: 116.4
shaper_type_x: 2hump_ei
shaper_type_y: 2hump_ei
#pickup_gcode= The code that is run when picking up the physical tool. Variable {myself} refers to the tool calling this code.
pickup_gcode:
SUB_TOOL_PICKUP_START T={myself.name}
SUB_TOOL_PICKUP_END T={myself.name}
dropoff_gcode:
RESPOND MSG="dropoff_gcode. in t0"
SUB_TOOL_DROPOFF_START T={myself.name}
SUB_TOOL_DROPOFF_END T={myself.name}
[tool 1]
tool_group: 0
[tool 2]
tool_group: 0
[tool 3]
tool_group: 0
[tool 4]
tool_group: 0
[tool 5]
tool_group: 0
[tool 6]
tool_group: 0
[tool 7]
tool_group: 0
[tool 8]
tool_group: 0
# End of Tool 0 virtual tools.
[tool 9]
tool_group: 1
extruder: extruder1
fan: partfan_t9
zone: 550,100
park: 598,100
offset: -1.046,-0.220,-1.510
meltzonelength: 14 #18
idle_to_standby_time: 0.1
shaper_freq_x: 126.8
shaper_freq_y: 128.6
shaper_type_x: 3hump_ei
shaper_type_y: 3hump_ei
[tool 10]
tool_group: 1
extruder: extruder2
fan: partfan_t10
zone: 550,200
park: 598,200
offset: 12.069,4.472,3.180
meltzonelength: 14 #18
idle_to_standby_time: 0.1
shaper_freq_x: 119.8
shaper_freq_y: 126.6
shaper_type_x: mzv
shaper_type_y: 2hump_ei
[tool 49]
tool_group: 1
zone: 560,515
park: 598,515
offset: 0,0,0
# Just to reset the input shaper.
#shaper_freq_x: 0
#shaper_freq_y: 0
#shaper_type_x: mzv
#shaper_type_y: mzv
[gcode_macro SUB_TOOL_PICKUP_START]
description: Internal subroutine. Do not use!
# Tnnn: Tool to pickup
gcode:
{%set myself = printer['tool '~params.T]%}
M568 P{myself.name} A2 # Put tool heater in Active mode
SAVE_ACCELERATION # Save current acceleration value.
M204 S8000 # Set high acceleration for toolchanging
SAVE_GCODE_STATE NAME=TOOL_PICKUP # Save GCODE state. Will be restored at the end of SUB_TOOL_PICKUP_END
SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=0 # Don't use the X-max endstop as EmergencyStop.
G90
############## Move in to zone ##############
{% if printer.toolhead.position.x < 500 %} # If Printer inside safezone:
G0 X500 Y{myself.zone[1]} F40000 # Fast move XY inside the safezone.
{% else %} # Else, outside of safezone:
G0 X500 F40000 # Fast move X inside the safezone, so we don't crash into other tools.
G0 Y{myself.zone[1]} F40000 # Fast move Y in front of parking spot.
{% endif %} # /
############## Move in to parking spot ##############
G0 X{myself.park[0]|int - 15} F40000 # Fast Move near the pickup position for tool.
G0 X{myself.park[0]} F3000 # Slow Move to the pickup position for tool.
############## Lock Tool ##############
M400 # Wait for all moves to finish.
TOOL_LOCK # Lock the tool.
SET_GCODE_OFFSET Z={myself.offset[2]} MOVE=1 # Set and move the Z offset. Avoid crashing into bed when moving out later.
############## Wait for heater ##############
{% if myself.extruder|default("none")|lower !="none" %} # If the tool has an extruder:
M116 P{myself.name} # Wait for tool to reach target temperature.
{% endif %} # /
############## Move out to zone ##############
G0 X{myself.zone[0]} F6000 # Slow Move to the zone position for tool.
[gcode_macro SUB_TOOL_PICKUP_END]
description: Internal subroutine. Do not use!
# Tnnn: Tool to pickup
gcode:
{%set myself = printer['tool '~params.T]%}
{%set ktcc = printer['ktcc_toolchanger']%}
############## Move out to Safe position ##############
G0 X500 F40000 # Fast Move to the safe position for tools.
############## Check Tool Lock ##############
QUERY_ENDSTOPS # Check the endstops and save the state to be retrieved in the macro below.
TOOL_LOCK_CHECK # MAcro to check so the tool is mounted by slightly advancing the lock again until hit endstop, only if endstop not already hit. Do not wait for it to finish.
############## Finnish up ##############
M400 # Wait for current moves to finish.
SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=1 # Use the X max as EmergencyStop.
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.
# Set the toolhead offsets. Z is set and moved before any moves in SUB_TOOL_PICKUP_START. Needs to be after any RESTORE_GCODE_STATE!
SET_GCODE_OFFSET X={myself.offset[0]|float + ktc.global_offset[0]|float } Y={myself.offset[1]|float + ktc.global_offset[1]|float } Z={myself.offset[2]|float + ktc.global_offset[2]|float } MOVE=0
############## Return to saved position ##############
G1 F40000
RESTORE_POSITION
SAVE_GCODE_STATE NAME=TOOL_PICKUP2 # Save state for priming nozzle
# RESPOND MSG="First if:{myself.extruder|default("none")|lower}"
############## Prime the filament, asume it was retracted as per e3d Revo documentation ##############
{% if myself.extruder|default("none")|lower !="none" %} # If the tool has an extruder:
# RESPOND MSG="First if1:{myself.extruder|default("none")|lower}"
# RESPOND MSG="Second if:{printer[myself.extruder].can_extrude|default("false")|lower}"
# RESPOND MSG="Second if1:{printer.toollock.purge_on_toolchange}"
# If can extrude and global purge is active:
{% if printer[myself.extruder].can_extrude|default("false")|lower == 'true' and printer.toollock.purge_on_toolchange %}
# RESPOND MSG="Second if2:{printer[myself.extruder].can_extrude|default("false")|lower}"
# RESPOND MSG="Second if3:{printer.toollock.purge_on_toolchange}"
M83 # Relative extrusion
G1 E{myself.meltzonelength|float - 2} F1300 # DeRetract filament from meltzone
G1 E2 F400 # DeRetract filament from meltzone
{% endif %}
{% endif %}
RESTORE_GCODE_STATE NAME=TOOL_PICKUP2 # Restore state after priming nozzle
G1 F30000
RESTORE_ACCELERATION # Restore saved acceleration value.
[gcode_macro SUB_TOOL_DROPOFF_START]
description: Internal subroutine. Do not use!
# Tnnn: Tool to pickup
gcode:
{%set myself = printer['tool '~params.T]%}
SAVE_ACCELERATION # Save current acceleration value.
M204 S8000 # Set high acceleration for toolchanging
{% if myself.name|int != printer.toollock.tool_current|int %}
{ action_raise_error("SUB_TOOL_DROPOFF_START: Wrong tool. Asked to dropoff T" ~ myself.name ~ " while current is T" ~ printer.toollock.tool_current ~ ".") }
{% endif %}
############## Retract the filament as per e3d Revo documentation ##############
{% if myself.extruder|default("none")|lower !="none" %} # If the tool has an extruder:
M568 P{myself.name} A1 # Put tool heater in standby
{% if printer[myself.extruder].can_extrude|default("false")|lower == 'true' and printer.toollock.purge_on_toolchange %}
M83 # Relative extrusion
G1 E-4 F2700 # retract filament from meltzone
G1 E2 F800 # Extrude slightly to form a tip
G1 E-{myself.meltzonelength|float - 2} F800 # Retract filament from meltzone
{% endif %}
{% endif %}
SET_GCODE_OFFSET X=0 Y=0 # Set XY offset to 0 so we park the tool right.
SAVE_GCODE_STATE NAME=TOOL_DROPOFF_002 # Save GCode state.
G90 # Absolute positions
SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=0 # Don't use the X max as EmergencyStop.
# Fast Move to the general pickup position for tools.
{% if printer.toolhead.position.x|float < 500 %}
G0 X500 Y{myself.zone[1]} F40000 # Move near pickup and lift z so we don't crash the bed later.
{% else %}
G0 X500 F40000 # Move X and lift z so we don't crash the bed or into other tools.
G0 Y{myself.zone[1]} F40000 # Move Y after X and Z
{% endif %}
M400 # Wait for current moves to finish
G0 X{myself.zone[0]} F40000 # Fast Move near the dropoff position for tool.
G0 X{myself.park[0]} F3000 # Slow Move to the dropoff position for tool.
[gcode_macro SUB_TOOL_DROPOFF_END]
description: Internal subroutine. Do not use!
# Tnnn: Tool to pickup
gcode:
{%set myself = printer['tool '~params.T]%}
M400 # Wait for current moves to finish
TOOL_UNLOCK # Unlock the tool
G0 X{myself.park[0]|float - 15} F6000 # Slow Move to the pickup position for tool.
G0 X500 F40000 # Fast Move to the general pickup position for tools.
M400
SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=1 # Use the X max as EmergencyStop.
RESTORE_GCODE_STATE NAME=TOOL_DROPOFF_002 MOVE=0 # Restore Gcode state
RESTORE_ACCELERATION # Restore saved acceleration value.
[gcode_macro SUB_VIRTUALTOOL_LOAD]
description: Internal subroutine. Do not use!
# Tnnn: Tool to load
gcode:
{%set myself = printer['tool '~params.T]%}
SET_TOOL_TEMPERATURE TOOL={myself.name} CHNG_STATE=2 # Put tool heater in Active mode
SAVE_ACCELERATION # Save current acceleration value.
M204 S8000 # Set high acceleration for toolchanging
SAVE_GCODE_STATE NAME=VIRTUALTOOL_LOAD # Save GCODE state. Will be restored at the end of SUB_TOOL_PICKUP_END
SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=0 # Don't use the X-max endstop as EmergencyStop.
SET_GCODE_OFFSET X=0 Y=0 # Set XY offset to 0 so we park the tool right.
G90 # Absolute positions
############## Move in to zone ##############
{% if printer.toolhead.position.x < 500 %} # If Printer inside safezone:
G0 X500 Y{myself.zone[1]} F40000 # Fast move XY inside the safezone.
{% else %} # Else, outside of safezone:
G0 X500 F40000 # Fast move X inside the safezone, so we don't crash into other tools.
G0 Y{myself.zone[1]} F40000 # Fast move Y in front of parking spot.
{% endif %} # /
G0 X{myself.zone[0]} F40000 # Fast Move to the zone position for tool.
############## Wait for heater ##############
TEMPERATURE_WAIT_WITH_TOLERANCE TOOL={myself.name} # Wait for tool to reach target temperature.
############## Load ERCF Tool ##############
M400 # Wait for all moves to finish.
G4 P5000 # Wait 5s so any fiament inside the hotend will get molten before tip forming.
ERCF_CHANGE_TOOL TOOL={myself.name} STANDALONE=1 # Load the ERCF tool.
############## Clear the filament by purging ##############
M83 # Relative extrusion
G1 E50 F300 # Purge filament for new.
G1 E25 F300 # Purge filament for new.
G1 E-1 F2400 # Equalize pressure.
############## Wipe the nozzle ##############
SUB_TOOL_WIPE T={myself.name} # Wipe the tool at the toolpost.
G0 X{myself.zone[0]} F3000 # Fast Move to the zone position for tool.
############## Move in to parking spot ##############
G0 X{myself.park[0]} F3000 # Slow Move to the pickup position for tool.
############## Move out to zone ##############
G0 X{myself.zone[0]} F6000 # Slow Move to the zone position for tool.
############## Move out to Safe position ##############
G0 X500 F40000 # Fast Move to the safe position for tools.
############## Finnish up ##############
M400 # Wait for current moves to finish.
SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=1 # Use the X max as EmergencyStop.
RESTORE_GCODE_STATE NAME=VIRTUALTOOL_LOAD MOVE=0 # Restore GCODE state. Was saved at the begining of SUB_VIRTUALTOOL_LOAD_START. No move.
############## Return to saved position ##############
G1 F40000
RESTORE_POSITION # This checks if the position is to be restored or not.
RESTORE_ACCELERATION # Restore saved acceleration value.
[gcode_macro SUB_VIRTUALTOOL_UNLOAD]
description: Internal subroutine. Do not use!
# Tnnn: Tool to unload
gcode:
{%set myself = printer['tool '~params.T]%}
SAVE_ACCELERATION # Save current acceleration value.
M204 S8000 # Set high acceleration for toolchanging
SAVE_GCODE_STATE NAME=VIRTUALTOOL_UNLOAD # Save GCode state.
SET_GCODE_OFFSET X=0 Y=0 # Set XY offset to 0 so we park the tool right.
G90 # Absolute positions
SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=0 # Don't use the X max as EmergencyStop.
############## Move in to zone ##############
{% if printer.toolhead.position.x|int < 500 %}
G0 X500 Y{myself.zone[1]} F40000 # Move near pickup and lift z so we don't crash the bed later.
{% else %}
G0 X500 F40000 # Move X and lift z so we don't crash the bed or into other tools.
G0 Y{myself.zone[1]} F40000 # Move Y after X and Z
{% endif %}
M400 # Wait for current moves to finish
G0 X{myself.zone[0]} F40000 # Fast Move near the dropoff position for tool.
############## Wait for heater ##############
M116 P{myself.name} # Wait for tool to reach target temperature.
############## Ejecting filament from ERCF ##############
G4 P5000 # Wait 5s so any fiament inside the hotend will get molten before tip forming.
ERCF_EJECT
############## Wipe the nozzle ##############
SUB_TOOL_WIPE T={myself.name} # Wipe the tool at the toolpost.
############## Move in to parking spot ##############
G0 X{myself.park[0]} F3000 # Slow Move to the dropoff position for tool to remove any excess filament on tool.
M400 # Wait for current moves to finish
G0 X{myself.park[0]|int - 15} F6000 # Slow Move to the pickup position for tool.
G0 X500 F40000 # Fast Move to the general pickup position for tools.
M400
SET_GCODE_VARIABLE MACRO=HOMING_STATUS VARIABLE=maxx VALUE=1 # Use the X max as EmergencyStop.
RESTORE_GCODE_STATE NAME=VIRTUALTOOL_UNLOAD MOVE=0 # Restore Gcode state
RESTORE_ACCELERATION # Restore saved acceleration value.
[gcode_macro SUB_TOOL_WIPE]
description: Internal subroutine. Do not use!
# Tnnn: Tool
gcode:
{%set myself = printer['tool '~params.T]%}
############## Wipe the nozzle ##############
G0 X{myself.park[0]|int - 10} F3000 # Fast Move near the pickup position for tool.
G0 X{myself.zone[0]} F3000 # Fast Move to the zone position for tool.
G0 X{myself.park[0]|int - 10} F3000 # Fast Move near the pickup position for tool.
G0 X{myself.zone[0]} F3000 # Fast Move to the zone position for tool.
G0 X{myself.park[0]|int - 10} F3000 # Fast Move near the pickup position for tool.
G0 X{myself.zone[0]} F3000 # Fast Move to the zone position for tool.
G0 X{myself.park[0]|int - 10} F3000 # Fast Move near the pickup position for tool.
G0 X{myself.zone[0]} F3000 # Fast Move to the zone position for tool.
SET_GCODE_OFFSET Z=0 # Set Z offset to 0 after too is parked.
================================================
FILE: config/example_simple/readme.md
================================================
# Simple examples
This are basic example file to get you started.
the files should be added to your printer.cfg like:
`[include custom/tools.cfg]`
This is for use with a Jubilee style printer.
================================================
FILE: config/example_simple/tools.cfg
================================================
# Simple sample configuration for getting started with a ToolChanger with 2 tools.
# Enables saving of variables between powerdown of machine. Must be configured before [toollock].
[save_variables]
filename: ~/variables.cfg
[ktcclog] # Log_level & logfile_level can be set to one of (0 = essential, 1 = info, 2 = debug, 3 = trace)
log_level: 2
logfile_level: 3
[toollock]
tool_lock_gcode:
MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=0 # Set assumed possition as rotated to min
MANUAL_STEPPER STEPPER=tool_lock Move=1 SPEED=30 STOP_ON_ENDSTOP=-1 SYNC=1 # Move until no longer endstop is triggered, max 1degree. If Endstop is not untriggered then raise an error. Wait for the movement before continuing.
MANUAL_STEPPER STEPPER=tool_lock Move=150 SPEED=50 STOP_ON_ENDSTOP=1 SYNC=1 # Move to max and stop on endstop. If Endstop is not triggered then raise an error. Wait for the movement before continuing.
tool_unlock_gcode:
MANUAL_STEPPER STEPPER=tool_lock SET_POSITION=180 # Set assumed possition as rotated to max
MANUAL_STEPPER STEPPER=tool_lock Move=179 SPEED=30 STOP_ON_ENDSTOP=-1 SYNC=1 # Move until no longer endstop is triggered, max 1degree. If Endstop is not untriggered then raise an error. Wait for the movement before continuing.
MANUAL_STEPPER STEPPER=tool_lock Move=0 SPEED=100 STOP_ON_ENDSTOP=1 SYNC=1 # Move to min and stop on endstop. If Endstop is not triggered then raise an error. Wait for the movement before continuing.
MANUAL_STEPPER STEPPER=tool_lock ENABLE=0 # Turn off the stepper while unlocked so it can rest without triggering the endswitch
[toolgroup 0]
pickup_gcode:
M568 P{myself.name} A2 # Put tool heater in Active mode
SAVE_GCODE_STATE NAME=TOOL_PICKUP # Save GCODE state. Will be restored at the end of pickup code
G90
############## Move in to zone ##############
G0 X500 F40000 # Fast move X inside the safezone, so we don't crash into other tools.
G0 Y{myself.zone[1]} F40000 # Fast move Y in front of parking spot.
############## Move in to parking spot ##############
G0 X{myself.park[0]|float - 15} F40000 # Fast Move near the pickup position for tool.
G0 X{myself.park[0]} F3000 # Slow Move to the pickup position for tool.
############## Lock Tool ##############
M400 # Wait for all moves to finish.
TOOL_LOCK # Lock the tool.
SET_GCODE_OFFSET Z={myself.offset[2]} MOVE=1 # Set and move the Z offset. Avoid crashing into bed when moving out later.
############## Wait for heater ##############
{% if myself.extruder|default("none")|lower !="none" %} # If the tool has an extruder:
TEMPERATURE_WAIT_WITH_TOLERANCE TOOL={myself.name} # Wait for tool to reach target temperature.
{% endif %} # /
############## Move out to zone ##############
G0 X{myself.zone[0]} F6000 # Slow Move to the zone position for tool.
############## Move out to Safe position ##############
G0 X500 F40000 # Fast Move to the safe position for tools.
############## Finnish up ##############
M400 # Wait for current moves to finish.
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.
# Set the toolhead offsets. Z is set and moved before any moves in SUB_TOOL_PICKUP_START. Needs to be after any RESTORE_GCODE_STATE!
SET_GCODE_OFFSET X={myself.offset[0]|float + ktcc.global_offset[0]|float } Y={myself.offset[1]|float + ktcc.global_offset[1]|float } Z={myself.offset[2]|float + ktcc.global_offset[2]|float } MOVE=0
dropoff_gcode:
SUB_TOOL_DROPOFF T={myself.name}
[tool 0]
tool_group: 0
extruder: extruder
fan: partfan_t0
zone: 550,5
park: 598,5
offset: 11.278,3.766,3.528
meltzonelength: 18
[tool 1]
tool_group: 0
extruder: extruder1
fan: partfan_t1
zone: 550,100
park: 598,100
offset: -1.447,-0.295,-1.503
meltzonelength: 18
[gcode_macro SUB_TOOL_DROPOFF]
description: Internal subroutine. Do not use!
# Tnnn: Tool to pickup
gcode:
{%set myself = printer['tool '~params.T]%}
SET_GCODE_OFFSET X=0 Y=0 # Set XY offset to 0 so we park the tool right.
SAVE_GCODE_STATE NAME=TOOL_DROPOFF_002 # Save GCode state.
G90 # Absolute positions
# Fast Move to the general pickup position for tools.
G0 X500 F40000 # Move X and lift z so we don't crash the bed or into other tools.
G0 Y{myself.zone[1]} F40000 # Move Y after X and Z
M400 # Wait for current moves to finish
G0 X{myself.zone[0]} F40000 # Fast Move near the dropoff position for tool.
G0 X{myself.park[0]} F3000 # Slow Move to the dropoff position for tool.
M400 # Wait for current moves to finish
TOOL_UNLOCK # Unlock the tool
G0 X{myself.park[0]|float - 15} F6000 # Slow Move to the pickup position for tool.
G0 X500 F40000 # Fast Move to the general pickup position for tools.
RESTORE_GCODE_STATE NAME=TOOL_DROPOFF_002 MOVE=0 # Restore Gcode state
SET_GCODE_OFFSET Z=0 # Set Z offset to 0 after too is parked.
================================================
FILE: config/optional_macros/G10.cfg
================================================
[gcode_macro G10]
description: See M568. Passtrough to M568.
gcode:
M568 {rawparams}
================================================
FILE: config/optional_macros/M104.cfg
================================================
[gcode_macro M104]
rename_existing: M104.1
description: [T<index>] [S<temperature>]
Set tool temperature.
T= Tool number, optional. If this parameter is not provided, the current tool is used.
S= Active temperature(s), optional
gcode:
{% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
# P= Tool number and optional T.
{% if params.P is defined %}
{% set newparameters = newparameters ~ " P="~params.P %}
{% elif params.T is defined %}
{% set newparameters = newparameters ~ " P="~params.T %}
{% endif %}
# S= Active temperature
{% if params.S is defined %}
{% set newparameters = newparameters ~ " ACTV_TMP="~params.S %}
{% endif %}
KTCC_SET_TOOL_TEMPERATURE{newparameters}
================================================
FILE: config/optional_macros/M106.cfg
================================================
[gcode_macro M106]
variable_fan_speed: 0
description: Snnn Pnnn
Set fan speed. A KTCC tool must be configured for this to work.
S: Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
P: Tool (optional, defaults to the currently selected tool)
The P parameter specifies tool instead of fan number as in RRF.
gcode:
{% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
# S= Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
{% if params.S is defined %}
{% set newparameters = newparameters ~ " S="~params.S %}
{% endif %}
# P= Tool number and optional T.
{% if params.P is defined %}
{% set newparameters = newparameters ~ " P="~params.P %}
{% elif params.T is defined %}
{% set newparameters = newparameters ~ " P="~params.T %}
{% endif %}
KTCC_SET_AND_SAVE_PARTFAN_SPEED{newparameters}
================================================
FILE: config/optional_macros/M107.cfg
================================================
[gcode_macro M107]
description: Pnnn
Turn off fan.
P = Tool (optional and defaults to the currently selected tool)
gcode:
# P= Tool number and optional T.
{% if params.P is defined %}
{% set p = " P"~params.P %}
{% elif params.T is defined %}
{% set p = " P"~params.T %}
{% endif %}
M106 {p|default("")} S0
================================================
FILE: config/optional_macros/M109.cfg
================================================
[gcode_macro M109]
rename_existing: M109.1
description: T<index> P<index> H<index> S<temperature> W<Tolerance>
Waits for all temperatures, or a specified tool or heater's temperature.
This command can be used without any additional parameters.
Without parameters it waits for bed and current extruder.
Tnnn Tool number.
Pnnn Alternative to T.
Hnnn Heater number.
Snnn Temperature
Wnnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
gcode:
{% set newparameters = "" %} # Parameters to be passed to subroutine in new format.
# H= Heater
{% if params.H is defined %}
{% set newparameters = newparameters ~ " HEATER=" ~ params.H %}
{% endif %}
# P= Tool number and optional T.
{% if params.P is defined %}
{% set newparameters = newparameters ~ " TOOL=" ~ params.P %}
{% elif params.T is defined %}
{% set newparameters = newparameters ~ " TOOL=" ~ params.T %}
{% endif %}
# S= Active temperature
{% if params.S is defined and ( params.T is defined or params.P is defined) %}
{% set newTempParameters = newparameters ~ " ACTV_TMP="~params.S ~ " CHNG_STATE=2" %} # Set heater_active_temp to new parameters.
KTCC_SET_TOOL_TEMPERATURE{newTempParameters}
{% endif %}
{% if params.W is defined %}
{% set newparameters = newparameters ~ " TOLERANCE=" ~ params.W %} # Set Tolerance to new parameters.
{% else %}
{% set newparameters = newparameters ~ " TOLERANCE=1" %} # Set Tolerance to default of 1.
{% endif %}
KTCC_TEMPERATURE_WAIT_WITH_TOLERANCE{newparameters}
================================================
FILE: config/optional_macros/M116.cfg
================================================
[gcode_macro M116]
description: T<index> P<index> H<index> S<temperature> W<Tolerance>
Alias for M109.
Waits for all temperatures, or a specified tool or heater's temperature.
This command can be used without any additional parameters.
Without parameters it waits for bed and current extruder.
Tnnn Tool number.
Pnnn Alternative to T.
Hnnn Heater number.
Snnn Temperature
Wnnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
gcode:
M109 {rawparams}
================================================
FILE: config/optional_macros/M204.cfg
================================================
[gcode_macro M204]
rename_existing: M204.1
description: Snnn / Pnnn Tnnn
Set acceleration either S or P and T must be provided.
If P and T provided then will use the lower of the two.
gcode:
{% if params.S is defined %}
{% set accel = params.S|float %}
{% elif params.P is defined or params.T is defined %}
{% set p = params.P|default(999999)|int %}
{% set t = params.T|default(999999)|int %}
{% if p < t %}
{% set accel = p %}
{% else %}
{% set accel = t %}
{% endif %}
{% else %}
{ action_raise_error("M204: Must provide S, P or T parameter.") }
{% endif %}
SET_VELOCITY_LIMIT ACCEL={accel} ACCEL_TO_DECEL={accel*0.5}
================================================
FILE: config/optional_macros/M568.cfg
================================================
[gcode_macro M568]
description: Pnnn Tnnn Rnnn Snnn An Nnnn Mnnn
Set tool temperature.
P= Tool number, optional. If this parameter is not provided, the current tool is used.
T= Alternative to P.
R= Standby temperature(s), optional
S= Active temperature(s), optional
A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature(s).
N = Time in seconds to wait between changing heater state to standby and setting heater target temperature to standby temperature when standby temperature is lower than tool temperature.
Use for example 0.1 to change immediately to standby temperature.
O = Time in seconds to wait from docking tool to shutting off the heater, optional.
Use for example 86400 to wait 24h if you want to disable shutdown timer.
gcode:
# RESPOND MSG="M568: Seting new temperature: {rawparams}"
{% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
# P= Tool number
{% if params.P is defined %}
{% set newparameters = newparameters ~ " TOOL=" ~ params.P %}
{% elif params.T is defined %}
{% set newparameters = newparameters ~ " TOOL=" ~ params.T %}
{% endif %}
# R= Standby temperature
{% if params.R is defined %}
{% set newparameters = newparameters ~ " STDB_TMP="~params.R %} # Set heater_standby_temp to new parameters.
{% endif %}
# S= Active temperature
{% if params.S is defined %}
{% set newparameters = newparameters ~ " ACTV_TMP="~params.S %} # Set heater_active_temp to new parameters.
{% endif %}
# N = Time in seconds to wait from docking tool to putting the heater in standy
{% if params.N is defined %}
{% set newparameters = newparameters ~ " STDB_TIMEOUT="~params.N %} # Set idle_to_standby_time to new parameters.
{% endif %}
# M = Time in seconds to wait from docking tool to shuting off the heater
{% if params.O is defined %}
{% set newparameters = newparameters ~ " SHTDWN_TIMEOUT="~params.O %} # Set idle_to_powerdown_time to new parameters.
{% endif %}
# A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature
{% if params.A is defined %}
{% set newparameters = newparameters ~ " CHNG_STATE="~params.A %} # Set idle_to_powerdown_time to new parameters.
{% endif %}
# {action_respond_info("M568: Running: KTCC_SET_TOOL_TEMPERATURE"~newparameters)}
KTCC_SET_TOOL_TEMPERATURE{newparameters}
================================================
FILE: config/optional_macros/readme.md
================================================
# Required and Optional G-code macros
The required macros change how Klipper uses those commands to make use of the toolchanger. They are all backwards compatible. This macros are highly recommended to be included.
The optional macros are to add more commands for higher compatibility with for example RRF G-code.
> [!NOTE]
> You can add the whole directory to the printer.cfg by adding the relative path to the macros directory for example:
```
[include toolchanger/g-code_macros/*.cfg]
```
<br>
##    Required macros
| Command | Description | Parameters |
| ------- | ----------- | ---------- |
| `M104` | Set tool temperature. If Tool number is not provided, current tool is used. If no S parameter is provided it will dump current temperature settings for the tool.| `P[0..n]` Tool number, optional <br> `T[0..n]` Alternative to P. <br>`S...` Active temperature to set. |
| `M106` | Set fan speed. If Tool number is not provided, current tool is used. If no S parameter is provided, set full fan speed. | `P[0..n]` Tool number, optional <br> `T[0..n]` Alternative to P. <br>`S[0-1]` or `S[2-255]` Fan speed 0-1 or 2-255 |
| `M107` | Turn off fan. If Tool number is not provided, current tool is used| `P[0..n]` Tool number, optional <br> `T[0..n]` Alternative to P |
| `M109` | Waits temperature with a tolerance defaulting to +//1. Optional temperature can be defined when tool is defined, setting the tool as active with specified temperature. If heater is defined it will wait for that heater. Optional tolerance can be specified. Only waits if target temperature is >40*C | `H[0..n]` Heater number, optional <br>`T[0..n]` Tool number <br>`P[0..n]` Alternative to T <br>`W[-50]` Tolerance in degC |
<br>
##    Optional macros
| Command | Description | Parameters |
| ------- | ----------- | ---------- |
| `G10` | Alias to M568 | |
| `M116` | Alias to M109 | |
| `M568` |Set tool temperature. If Tool number is not provided, current tool is used | `P[0..n]` Tool number, optional <br> `T[0..n]` Alternative to P. <br>`S...` Set active temperature, optional <br>`R...` Set standby temperature, optional <br>`A...` Set Heater state, optional<br> (0= off), (1 = standby temperature), (2 = active temperature) <br>`N...` Standby timeout is the time to linger at Active temp. after setting the heater to standby. Could be used for a tool with long heatup times and is only put in standby short periods of thme throughout a print and should stay at active temperature longer time. <br>`O...` Timer from Standby to off. Used for example so a tool used only on first few layers shuts down after 30 minutes of inactivity and won't stay at 175*C standby for the rest of a 72h print. |
| `M204` | Set acceleration to either S or lowest of supplied P and T. | `S...` Acceleration, optional<br> `P...` Print acceleration, RRF compatible<br> `T...` Travel acceleration, RRF compatible |
| `M566` | Set Square Corner Velocity in RRF style. Only the lower of required X or Y will be used| `X...` X axis<br> `Y...` Y axis |
================================================
FILE: config/readme.md
================================================
# Configuration reference
This document is a reference for options available in the Klipper config file when adding the Tools module.
## Configuration examples
Can be found in the different subdirectories.
Feel free to add some for reference or send them my way and I will format, comment and add them.
-
## Configuration order
ToolGroups must come before tools that use them.
A Tool that is used as physical_parent must be configured before other virtual tools that use it as a parent.
## Configuration requirements
* `[save_variables]` must be used as described in the Klipper documentation.
* `[input_shaper]` needs to be used for input shaper to work.
### [toollock]
Configures the Locking mechanism and other common configuration for the Tools module.
```
#purge_on_toolchange: True
# Here we can disable all purging. When disabled it overrides all other purge options.
# This can be turned off by a macro for automatic probing hot tools without probing them.
# For example when doing TAMV or ZTATP. The default is True.
#global_offset: 0,0,0
# Optional offset that can be accesed in macros and added to all tools. Can be usefull for diailing in the first layer.
#init_printer_to_last_tool: True
# Initialise as it was turned off, unlock tool if none was loaded or lock if one was
# loaded. Defaults to True
tool_lock_gcode:
# A list of G-Code commands to execute when the tool is locked
# in place by the TOOL_LOCK command. This parameter must
# be provided. This can also call a macro.
tool_unlock_gcode:
# A list of G-Code commands to execute when the tool is unlocked
# in place by the TOOL_UNLOCK command. This parameter must
# be provided. This can also call a macro.
```
### [toolgroup]
Can be used for grouping settings common to multiple tools.
At least one (the 0) must be specified and can be empty.
```
[toolgroup 0]
#is_virtual: True
# If True then must have a physical_parent declared and shares extruder, hotend and
# fan with the physical_parent
#physical_parent: 0
# Tool used as a Physical parent for all toos of this group. Only used if the tool i virtual.
#lazy_home_when_parking: 0
# If the printer is able to home with the tool mounted.
# When set to 1, will home unhomed XY axes if needed and will not move any axis
# if already homed and parked. 2 Will also home Z if not homed.
#meltzonelength:0
#idle_to_standby_time: 30
#idle_to_powerdown_time: 600
#pickup_gcode
#dropoff_gcode
```
### [tool]
A tool can be a physical tool on a toolchanger, being picked up and dropped of, or it can be
virtual on a tool. A virtual tool can be a ERCF, a roatating wheel, etc.
A virtual tool is a second layer of toolchanging. For example if using a physical e3d Revo
with a Bondtech LGX Lite and two fans connected to a 9 port ERCF filament changer.
Then the [Tool 0] to [Tool 9] would have 0 as parent and all be virtual. When changing
from T0 to T2, then only the ERCF script would run. But if changing from T11 to T2,
then first a toolchange and then a ERCF filament change would occur.
A tool does not have to have a heater, extruder or fan. It can be a simple pen.
The only mandatory setting is "tool_group".
A virtual tool can inherit all and any configuration from the parent tool except for
"is_virtual" and "physical_parent". Both can be defined in a group, so basicly only
the group needs to be specified for a group of tools
```
[tool 0]
tool_group:
# The Toolgroup number for this tool
# Must be used and configured before thr tool using it.
#is_virtual: False
# Defines this tool as physical or virtual.
#physical_parent:
# Nr of the physical parent of this tool. Defaults not having one.
#extruder:
# Name of extruder connected to this tool. For example "extruder"
# or "extruder1" without the quotation marks. Defaults to having no extruder.
#fan:
# Name of general fan configuration used as a partcooling fan.
# For example "partfan_t0". Defaults to having no extruder.
#zone:
# Coordinates to when the toolhead is near the tool, used for fas aproach.
# For example "550,5". This would be X550 Y5 in the printer coordinates.
park:
# Coordinates to when the tool is parked, aproach slowly from zone coordinates.
# For example "598,5". This would be X598 Y5 in the printer coordinates.
#offset:
# Offset of the tip of the tool to the coordinates of the head in X,Y,Z
# For example "11.278,3.766,3.528". Defaults to "0,0,0"
#idle_to_standby_time: 0.1
# Time in seconds from the tool being parked to setting temperature to standby
# if the temperature current temperature is above the standby temperature.
# Use 0.1 to change imediatley to standby temperature. Defaults to 0.1
# If you use 0, then it disables the standby temperature.
#idle_to_powerdown_time: 600
# Time in seconds from being parked to turning off the heater, setting temperature to 0.
# Use something like 86400 to wait 24h if you want to disable. Defaults to 600 (10 minutes).
#lazy_home_when_parking: 0
# If the printer is able to home with the tool mounted.
# When set to 1, will home unhomed XY axes if needed and will not move any axis
# if already homed and parked. 2 Will also home Z if not homed.
#meltzonelength: 0
# Length of the meltzone for retracting and inserting filament on toolchange. 18mm for e3d Revo.
#shaper_freq_x: 0
#shaper_freq_y: 0
# Shaper frequency for this tool. For example "116.4". Defaults to "0".. See Klipper documentation for more details.
# shaper_type_x: "mzv"
# shaper_type_y: "mzv"
# Shaper type for this tool. Defaults to "mzv". See Klipper documentation for more details.
#shaper_damping_ratio_x: 0
#shaper_damping_ratio_x: 0
# Damping ratios of vibrations of X and Y axes used by input shaper.
# Defaults to "0.1". See Klipper documentation for more details.
#pickup_gcode:
# A list of G-Code commands to execute when the tool is locked
# in place by the TOOL_LOCK command. This can also call a macro.
#dropoff_gcode:
# A list of G-Code commands to execute when the tool is unlocked
# in place by the TOOL_UNLOCK command. This can also call a macro.
```
Not used yet:
```
#HeatMultiplyerAtFullFanSpeed = 1
# Multiplier to be aplied to hotend temperature when fan is at maximum.
# Will be multiplied with fan speed. Ex. 1.1 at 205*C and fan speed of 40% will set temperature to 213*C
```
================================================
FILE: doc/command_ref.md
================================================
# KTCC - Command Reference
##    Basic Toolchanger functionality
| Command | Description | Parameters |
| ------- | ----------- | ---------- |
| `TOOL_LOCK` | Lock the tool to the toolhead. | |
| `TOOL_UNLOCK` | Unlock the toolhead from tool. | |
| `Tn` | Activates heater, pick up and readyy the tool. If tool is mapped to another one then that tool will be selected instead. | `RESTORE_AXIS=[XYZ]` Restore specified axis position to the latest saved. |
| `TOOL_DROPOFF_ALL` | Unloads and parks the current tool without picking up another tool, leaving the toolhead free and unlocked. Actual active extruder eill still be last used one as Klipper needs an active extruder. | |
| `SET_TOOL_TEMPERATURE` | Set tool temperature. If `TOOL` parameter is omited then current tool is set. | `TOOL=[0..n]` Optional if other than current loaded tool<br>`ACTV_TMP=...` Set Active temperature, optional<br> `STDB_TMP =...` Standby temperature, optional<br> `CHNG_STATE=[0\|1\|2]` Change Heater State, optional:<br>(0 = Off) \| (1 = Standby) \| (2 = Active)<br> `SHTDWN_TIMEOUT=...` Time in seconds to wait with the heater in standby before changing it to off, optional. <br> `STDB_TIMEOUT=...` Time in seconds to linger at Active temp. after setting the heater to standby when the standby temperature is lower than current tool temperature, optional.<br> `SHTDWN_TIMEOUT` is used for example so a tool used only on first few layers shuts down after 30 minutes of inactivity and won't stay at 175*C standby for the rest of a 72h print.<br> `STDB_TIMEOUT=` Time to linger at Active temp. after setting the heater to standby. Could be used for a tool with long heatup times and is only put in standby short periods of thme throughout a print and should stay at active temperature longer time. |
| `SET_AND_SAVE_PARTFAN_SPEED` | Set the partcooling fan speed current or specified tool. Fan speed is carried over between toolchanges. | `S=[0-255 \| 0-1]` Fan speed with either a maximum of 255 or 1.<br> `P=[0-n]` Tool number if not current tool to set fan to. |
| `TEMPERATURE_WAIT_WITH_TOLERANCE` | Waits for all temperatures, or a specified tool or heater's temperature. This command can be used without any additional parameters and then waits for bed and current extruder. Only one of either TOOL or HEATER may be used. Only waits if target temperature is >40*C | `TOOL=[0-n]` Tool number to wait for, optional.<br> `HEATER=[0-n]` Heater number. 0="heater_bed", 1="extruder", 2="extruder1", 3="extruder2", etc. Only works if named as default, this way, optional.<br> `TOLERANCE=[0-50]` Tolerance in degC. Defaults to 1*C. Wait will wait until heater is in range of set temperature +/- tolerance. |
<br>
##    Offset commands
| Command | Description | Parameters   |
| ------- | ----------- | ---------- |
| `SET_GLOBAL_OFFSET` | Set a global offset that can be applied to all tools. Can use absolute offset or adjust relative to current offset. | `X=...` Set the new offset for the axis.<br> `Y=...` As above.<br> `Z=...` As above.<br> ----------<br>`X_ADJUST=...` Adjust the offset position incramentally.<br> `Y_ADJUST=...` As above.<br> `Z_ADJUST=...` As above.<br> |
| `SET_TOOL_OFFSET` | Set the offset of an individual tool. Can use absolute offset or adjust relative to current offset. | `TOOL=[0-n]` Tool number, optional. If not provided, the current tool is used.<br> ----------<br> `X=...` Set the new offset for the axis.<br> `Y=...` As above.<br> `Z=...` As above.<br> ----------<br>`X_ADJUST=...` Adjust the offset position incramentally.<br> `Y_ADJUST=...` As above.<br> `Z_ADJUST=...` As above.<br> |
| `KTCC_SET_GCODE_OFFSET_FOR_CURRENT_TOOL` | Sets the Klipper G-Code offset to the one for the current tool. | `MOVE=[0\|1]` Wheteher to move the toolhead to the new offset. ( 0 = Do not move, default ) ( 1 = Move )<br> |
<br>
##    Position saving and restoring commands
| Command | Description | Parameters   |
| ------- | ----------- | ---------- |
| `SAVE_POSITION` | Save the specified G-Code position for later restore. Without parameters it will set to not restoring axis. | `X=...` Set the restore position and set this axis to be restored.<br> `Y=...` As above.<br> `Z=...` As above. |
| `SAVE_CURRENT_POSITION` | Save the current G-Code position for later restore. Without parameters it will save previousley saved axis. | `RESTORE_POSITION_TYPE=[XYZ] or [0\|1\|2]` Axis to save or tyoe ( 0 = No restore ), ( 1 = Restore XY ), ( 2 = Restore XYZ ) |
| `RESTORE_POSITION` | Restore a previously saved G-Code position. With no parameters it will Restore to previousley saved type. | `RESTORE_POSITION_TYPE=[XYZ] or [0\|1\|2]` Axis to save or tyoe ( 0 = No restore ), ( 1 = Restore XY ), ( 2 = Restore XYZ ) |
<br>
##    Tool remapping commands
| Command | Description | Parameters |
| ------- | ----------- | ---------- |
| `KTCC_DISPLAY_TOOL_MAP` | Dump the current mapping of tools to other KTCC tools. | |
| `KTCC_REMAP_TOOL` | Remap a tool to another one. | `RESET=[0\|1]` If 1 the stored tooö remap will be reset.<br> `TOOL=[0-n]` The toolnumber to remap.<br> `SET=[0-n]` The toolnumber to remap to. |
<br>
##    Advanced commands, rarely used
| Command | Description | Parameters |
| ------- | ----------- | ---------- |
| `KTCC_SAVE_CURRENT_TOOL` | Set the current loaded tool manually to the specified. When loading a tool manually | `T=[-2-n]` Tool to set as current. ( -2 = Unknown tool ), ( -1 = Toollock unlocked without tool ) |
| `KTCC_SET_PURGE_ON_TOOLCHANGE` | Sets a global variable that can disable all purging (can be used in macros) when loading/unloading tools. For example for automated tool alignement such as TAMV/ZTATP. | `VALUE=[0\|1]` If enabled or disabled. |
| `KTCC_ENDSTOP_QUERY` | Wait for a ENDSTOP untill it is in the specified state indefinitly or for maximum atempts if specified. Checking state once a second. | `ENDSTOP=...` Name of the endstop to wait for.<br> `TRIGGERED=[0\|1]` If should be waiting for it to be triggered (1) or open (0).<br> `ATEMPTS=...` Number of atempts to make, indefinitly if not specified. |
| `KTCC_SET_ALL_TOOL_HEATERS_OFF` | Turns off all heaters configured for tools and saves changes made to be resumed later by KTCC_RESUME_ALL_TOOL_HEATERS. This does not affect heated beds or other heaters not defined as aan extruder in tools. | |
| `KTCC_RESUME_ALL_TOOL_HEATERS` | Resumes all heaters previously turned off by KTCC_SET_ALL_TOOL_HEATERS_OFF. | `MSG=...` The message to be sent |
<br>
##    Status, Logging and Persisted state
| Command | Description | Parameters |
| ------- | ----------- | ---------- |
| `KTCC_DUMP_STATS` | Dump the KTCC statistics to console. | |
| `KTCC_RESET_STATS` | Reset all the KTCC statistics. | `SUERE=[yes\|no]` If "yes" the stored statistics will be reset. |
| `KTCC_INIT_PRINT_STATS` | Run at start of a print to initialize and reset the KTCC print statistics | |
| `KTCC_DUMP_PRINT_STATS` | Run at end of a print to dump statistics since last print reset to console. | |
| `KTCC_SET_LOG_LEVEL` | Set the log level for the KTCC | `LEVEL=[0-3]` How much to log to console: ( 0 = Only the Always messages ) ( 1 = Info messages and above ) ( 2 = Debug messages and above ) ( 3 = Trace messages and above )<br> `LOGFILE=[0-3]` How much to log to file. Levels as above. |
| `KTCC_LOG_TRACE` | Send a message to log at this logging level | `MSG=...` The message to be sent |
| `KTCC_LOG_DEBUG` | Send a message to log at this logging level | `MSG=...` The message to be sent |
| `KTCC_LOG_INFO` | Send a message to log at this logging level | `MSG=...` The message to be sent |
| `KTCC_LOG_ALWAYS` | Send a message to log at this logging level | `MSG=...` The message to be sent |
<br>
================================================
FILE: install.sh
================================================
#!/bin/bash
# Constants
EXTENSION_NAME="klipper_toolchanger"
# Force script to exit if an error occurs
set -e
# Find SRCDIR from the pathname of this script
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/ && pwd )"
KLIPPER_PATH="${HOME}/klipper"
# Parse command line arguments to allow KLIPPER_PATH override
while getopts "k:" arg; do
case $arg in
k) KLIPPER_PATH=$OPTARG;;
esac
done
# Verify conditions for the install to take place
check_preconditions()
{
if [ "$EUID" -eq 0 ]; then
echo "This script must not run as root"
exit -1
fi
if [ "$(sudo systemctl list-units --full -all -t service --no-legend | grep -F "klipper.service")" ]; then
echo "Klipper service found!"
else
echo "Klipper service not found, please install Klipper first"
exit -1
fi
}
# Step 2: create a symlinks to the extension files in the klippy/extras directory
link_extension()
{
echo "Linking ${EXTENSION_NAME} to Klippy extras..."
ln -sf ${SRCDIR}/*.py ${KLIPPER_PATH}/klippy/extras/
}
# Step 3: restarting Klipper
restart_klipper()
{
echo "Restarting Klipper..."
sudo systemctl restart klipper
}
# Installation steps:
check_preconditions
link_extension
restart_klipper
================================================
FILE: klipper_macros/G10.cfg
================================================
[gcode_macro G10]
description: See M568. Passtrough to M568.
gcode:
M568 {rawparams}
================================================
FILE: klipper_macros/M104.cfg
================================================
[gcode_macro M104]
rename_existing: M104.1
description: [T<index>] [S<temperature>]
Set tool temperature.
T= Tool number, optional. If this parameter is not provided, the current tool is used.
S= Active temperature(s), optional
gcode:
{% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
# P= Tool number and optional T.
{% if params.P is defined %}
{% set newparameters = newparameters ~ " P="~params.P %}
{% elif params.T is defined %}
{% set newparameters = newparameters ~ " P="~params.T %}
{% endif %}
# S= Active temperature
{% if params.S is defined %}
{% set newparameters = newparameters ~ " ACTV_TMP="~params.S %}
{% endif %}
KTCC_SET_TOOL_TEMPERATURE{newparameters}
================================================
FILE: klipper_macros/M106.cfg
================================================
[gcode_macro M106]
variable_fan_speed: 0
description: Snnn Pnnn
Set fan speed. A KTCC tool must be configured for this to work.
S: Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
P: Tool (optional, defaults to the currently selected tool)
The P parameter specifies tool instead of fan number as in RRF.
gcode:
{% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
# S= Fan speed 0-1 or 2-255 (optional, defult 1, full speed)
{% if params.S is defined %}
{% set newparameters = newparameters ~ " S="~params.S %}
{% endif %}
# P= Tool number and optional T.
{% if params.P is defined %}
{% set newparameters = newparameters ~ " P="~params.P %}
{% elif params.T is defined %}
{% set newparameters = newparameters ~ " P="~params.T %}
{% endif %}
KTCC_SET_AND_SAVE_PARTFAN_SPEED{newparameters}
================================================
FILE: klipper_macros/M107.cfg
================================================
[gcode_macro M107]
description: Pnnn
Turn off fan.
P = Tool (optional and defaults to the currently selected tool)
gcode:
# P= Tool number and optional T.
{% if params.P is defined %}
{% set p = " P"~params.P %}
{% elif params.T is defined %}
{% set p = " P"~params.T %}
{% endif %}
M106 {p|default("")} S0
================================================
FILE: klipper_macros/M109.cfg
================================================
[gcode_macro M109]
rename_existing: M109.1
description: T<index> P<index> H<index> S<temperature> W<Tolerance>
Waits for all temperatures, or a specified tool or heater's temperature.
This command can be used without any additional parameters.
Without parameters it waits for bed and current extruder.
Tnnn Tool number.
Pnnn Alternative to T.
Hnnn Heater number.
Snnn Temperature
Wnnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
gcode:
{% set newparameters = "" %} # Parameters to be passed to subroutine in new format.
# H= Heater
{% if params.H is defined %}
{% set newparameters = newparameters ~ " HEATER=" ~ params.H %}
{% endif %}
# P= Tool number and optional T.
{% if params.P is defined %}
{% set newparameters = newparameters ~ " TOOL=" ~ params.P %}
{% elif params.T is defined %}
{% set newparameters = newparameters ~ " TOOL=" ~ params.T %}
{% endif %}
# S= Active temperature
{% if params.S is defined and ( params.T is defined or params.P is defined) %}
{% set newTempParameters = newparameters ~ " ACTV_TMP="~params.S ~ " CHNG_STATE=2" %} # Set heater_active_temp to new parameters.
KTCC_SET_TOOL_TEMPERATURE{newTempParameters}
{% endif %}
{% if params.W is defined %}
{% set newparameters = newparameters ~ " TOLERANCE=" ~ params.W %} # Set Tolerance to new parameters.
{% else %}
{% set newparameters = newparameters ~ " TOLERANCE=1" %} # Set Tolerance to default of 1.
{% endif %}
KTCC_TEMPERATURE_WAIT_WITH_TOLERANCE{newparameters}
================================================
FILE: klipper_macros/M116.cfg
================================================
[gcode_macro M116]
description: T<index> P<index> H<index> S<temperature> W<Tolerance>
Alias for M109.
Waits for all temperatures, or a specified tool or heater's temperature.
This command can be used without any additional parameters.
Without parameters it waits for bed and current extruder.
Tnnn Tool number.
Pnnn Alternative to T.
Hnnn Heater number.
Snnn Temperature
Wnnn Tolerance in degC. Defaults to 1*C. Wait will wait until heater is between set temperature +/- tolerance.
gcode:
M109 {rawparams}
================================================
FILE: klipper_macros/M204.cfg
================================================
[gcode_macro M204]
rename_existing: M204.1
description: Snnn / Pnnn Tnnn
Set acceleration either S or P and T must be provided.
If P and T provided then will use the lower of the two.
gcode:
{% if params.S is defined %}
{% set accel = params.S|float %}
{% elif params.P is defined or params.T is defined %}
{% set p = params.P|default(999999)|int %}
{% set t = params.T|default(999999)|int %}
{% if p < t %}
{% set accel = p %}
{% else %}
{% set accel = t %}
{% endif %}
{% else %}
{ action_raise_error("M204: Must provide S, P or T parameter.") }
{% endif %}
SET_VELOCITY_LIMIT ACCEL={accel} ACCEL_TO_DECEL={accel*0.5}
================================================
FILE: klipper_macros/M566.cfg
================================================
[gcode_macro M566]
description: Xnnn Ynnn
Set Square Corner Velocity in RRF style.
Only the lower of required X or Y will be used.
gcode:
# RESPOND MSG="M566: Seting new Square Corner Velocity." #: {rawparams}.
# { action_respond_info("M566: Seting new Square Corner Velocity: "~rawparams) }
{% if params.X is defined or params.Y is defined %}
{% set x = params.X|default(999999)|int %}
{% set y = params.Y|default(999999)|int %}
{% if x < y %}
{% set square_corenr_velocity = x %}
{% else %}
{% set square_corenr_velocity = y %}
{% endif %}
gcode: SQUARE_CORNER_VELOCITY={square_corenr_velocity/60}
{% else %}
{ action_raise_error("M566: At least X or Y must be defined.") }
{% endif %}
================================================
FILE: klipper_macros/M568.cfg
================================================
[gcode_macro M568]
description: Pnnn Tnnn Rnnn Snnn An Nnnn Mnnn
Set tool temperature.
P= Tool number, optional. If this parameter is not provided, the current tool is used.
T= Alternative to P.
R= Standby temperature(s), optional
S= Active temperature(s), optional
A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature(s).
N = Time in seconds to wait between changing heater state to standby and setting heater target temperature to standby temperature when standby temperature is lower than tool temperature.
Use for example 0.1 to change immediately to standby temperature.
O = Time in seconds to wait from docking tool to shutting off the heater, optional.
Use for example 86400 to wait 24h if you want to disable shutdown timer.
gcode:
# RESPOND MSG="M568: Seting new temperature: {rawparams}"
{% set newparameters = "" %} # Parameters to be passed to subroutines in new format.
# P= Tool number
{% if params.P is defined %}
{% set newparameters = newparameters ~ " TOOL=" ~ params.P %}
{% elif params.T is defined %}
{% set newparameters = newparameters ~ " TOOL=" ~ params.T %}
{% endif %}
# R= Standby temperature
{% if params.R is defined %}
{% set newparameters = newparameters ~ " STDB_TMP="~params.R %} # Set heater_standby_temp to new parameters.
{% endif %}
# S= Active temperature
{% if params.S is defined %}
{% set newparameters = newparameters ~ " ACTV_TMP="~params.S %} # Set heater_active_temp to new parameters.
{% endif %}
# N = Time in seconds to wait from docking tool to putting the heater in standy
{% if params.N is defined %}
{% set newparameters = newparameters ~ " STDB_TIMEOUT="~params.N %} # Set idle_to_standby_time to new parameters.
{% endif %}
# M = Time in seconds to wait from docking tool to shuting off the heater
{% if params.O is defined %}
{% set newparameters = newparameters ~ " SHTDWN_TIMEOUT="~params.O %} # Set idle_to_powerdown_time to new parameters.
{% endif %}
# A = Heater State, optional: 0 = off, 1 = standby temperature(s), 2 = active temperature
{% if params.A is defined %}
{% set newparameters = newparameters ~ " CHNG_STATE="~params.A %} # Set idle_to_powerdown_time to new parameters.
{% endif %}
# {action_respond_info("M568: Running: KTCC_SET_TOOL_TEMPERATURE"~newparameters)}
KTCC_SET_TOOL_TEMPERATURE{newparameters}
================================================
FILE: klipper_macros/readme.md
================================================
# Required and Optional G-code macros
The required macros change how Klipper uses those commands to make use of the toolchanger. They are all backwards compatible. This macros are highly recommended to be included.
The optional macros are to add more commands for higher compatibility with for example RRF G-code.
> [!NOTE]
> You can add the whole directory to the printer.cfg by adding the relative path to the macros directory for example:
```
[include toolchanger/g-code_macros/*.cfg]
```
<br>
##    Required macros
| Command | Description | Parameters |
| ------- | ----------- | ---------- |
| `M104` | Set tool temperature. If Tool number is not provided, current tool is used. If no S parameter is provided it will dump current temperature settings for the tool.| `P[0..n]` Tool number, optional <br> `T[0..n]` Alternative to P. <br>`S...` Active temperature to set. |
| `M106` | Set fan speed. If Tool number is not provided, current tool is used. If no S parameter is provided, set full fan speed. | `P[0..n]` Tool number, optional <br> `T[0..n]` Alternative to P. <br>`S[0-1]` or `S[2-255]` Fan speed 0-1 or 2-255 |
| `M107` | Turn off fan. If Tool number is not provided, current tool is used| `P[0..n]` Tool number, optional <br> `T[0..n]` Alternative to P |
| `M109` | Waits temperature with a tolerance defaulting to +//1. Optional temperature can be defined when tool is defined, setting the tool as active with specified temperature. If heater is defined it will wait for that heater. Optional tolerance can be specified. Only waits if target temperature is >40*C | `H[0..n]` Heater number, optional <br>`T[0..n]` Tool number <br>`P[0..n]` Alternative to T <br>`W[-50]` Tolerance in degC |
<br>
##    Optional macros
| Command | Description | Parameters |
| ------- | ----------- | ---------- |
| `G10` | Alias to M568 | |
| `M116` | Alias to M109 | |
| `M568` |Set tool temperature. If Tool number is not provided, current tool is used | `P[0..n]` Tool number, optional <br> `T[0..n]` Alternative to P. <br>`S...` Set active temperature, optional <br>`R...` Set standby temperature, optional <br>`A...` Set Heater state, optional<br> (0= off), (1 = standby temperature), (2 = active temperature) <br>`N...` Standby timeout is the time to linger at Active temp. after setting the heater to standby. Could be used for a tool with long heatup times and is only put in standby short periods of thme throughout a print and should stay at active temperature longer time. <br>`O...` Timer from Standby to off. Used for example so a tool used only on first few layers shuts down after 30 minutes of inactivity and won't stay at 175*C standby for the rest of a 72h print. |
| `M204` | Set acceleration to either S or lowest of supplied P and T. | `S...` Acceleration, optional<br> `P...` Print acceleration, RRF compatible<br> `T...` Travel acceleration, RRF compatible |
| `M566` | Set Square Corner Velocity in RRF style. Only the lower of required X or Y will be used| `X...` X axis<br> `Y...` Y axis |
================================================
FILE: ktcclog.py
================================================
# KTCC - Klipper Tool Changer Code
# Log and statistics module
#
# Copyright (C) 2023 Andrei Ignat <andrei@ignat.se>
#
# Based on and inspired by ERCF-Software-V3 Copyright (C) 2021 moggieuk#6538 (discord)
#
# This file may be distributed under the terms of the GNU GPLv3 license.
#
# To try to keep terms apart:
# Mount: Tool is selected and loaded for use, be it a physical or a virtual on physical.
# Unmopunt: Tool is unselected and unloaded, be it a physical or a virtual on physical.
# Pickup: Tool is physically picked up and attached to the toolchanger head.
# Droppoff: Tool is physically parked and dropped of the toolchanger head.
# ToolLock: Toollock is engaged.
# ToolUnLock: Toollock is disengaged.
import logging, logging.handlers, threading, queue, time
import math, os.path, copy
# Forward all messages through a queue (polled by background thread)
class KtccQueueHandler(logging.Handler):
def __init__(self, queue):
logging.Handler.__init__(self)
self.queue = queue
def emit(self, record):
try:
self.format(record)
record.msg = record.message
record.args = None
record.exc_info = None
self.queue.put_nowait(record)
except Exception:
self.handleError(record)
# Poll log queue on background thread and log each message to logfile
class KtccQueueListener(logging.handlers.TimedRotatingFileHandler):
def __init__(self, filename):
logging.handlers.TimedRotatingFileHandler.__init__(
self, filename, when='midnight', backupCount=5)
self.bg_queue = queue.Queue()
self.bg_thread = threading.Thread(target=self._bg_thread)
self.bg_thread.start()
def _bg_thread(self):
while True:
record = self.bg_queue.get(True)
if record is None:
break
self.handle(record)
def stop(self):
self.bg_queue.put_nowait(None)
self.bg_thread.join()
# Class to improve formatting of multi-line KTCC messages
class KtccMultiLineFormatter(logging.Formatter):
def format(self, record):
indent = ' ' * 9
lines = super(KtccMultiLineFormatter, self).format(record)
return lines.replace('\n', '\n' + indent)
class KtccLog:
TOOL_UNKNOWN = -2
TOOL_UNLOCKED = -1
EMPTY_TOOL_STATS = {'toolmounts_completed': 0, 'toolunmounts_completed': 0, 'toolmounts_started': 0, 'toolunmounts_started': 0, 'time_selected': 0, 'time_heater_active': 0, 'time_heater_standby': 0, 'tracked_start_time_selected':0, 'tracked_start_time_active':0, 'tracked_start_time_standby':0, 'total_time_spent_unmounting':0, 'total_time_spent_mounting':0}
KTCC_TOOL_STATISTICS_PREFIX = "ktcc_statistics_tool"
def __init__(self, config):
self.config = config
self.gcode = config.get_printer().lookup_object('gcode')
self.printer = config.get_printer()
self.reactor = self.printer.get_reactor()
self.printer.register_event_handler('klippy:connect', self.handle_connect)
self.printer.register_event_handler("klippy:disconnect", self.handle_disconnect)
self.printer.register_event_handler("klippy:ready", self.handle_ready)
# Logging
self.log_level = config.getint('log_level', 1, minval=0, maxval=3)
self.logfile_level = config.getint('logfile_level', 3, minval=-1, maxval=4)
self.log_statistics = config.getint('log_statistics', 0, minval=0, maxval=1)
self.log_visual = config.getint('log_visual', 1, minval=0, maxval=2)
# Logging
self.queue_listener = None
self.ktcc_logger = None
# Save to file
self.changes_to_save = False
self.save_delay = 10
self.save_active = True
# Register commands
handlers = [
'KTCC_LOG_TRACE', 'KTCC_LOG_DEBUG', 'KTCC_LOG_INFO', 'KTCC_LOG_ALWAYS',
'KTCC_SET_LOG_LEVEL', 'KTCC_DUMP_STATS', 'KTCC_RESET_STATS',
'KTCC_INIT_PRINT_STATS', 'KTCC_DUMP_PRINT_STATS']
for cmd in handlers:
func = getattr(self, 'cmd_' + cmd)
desc = getattr(self, 'cmd_' + cmd + '_help', None)
self.gcode.register_command(cmd, func, False, desc)
def handle_ready(self):
self.always('KlipperToolChangerCode Ready')
# Wraping G28 and wait for temperature so we don't try sending gcode commands to save state while the gcode is blocked.
# Need to do it outermost so that any G28 macros are used too.
# When inside a G28 the parser won't run any SAVE_VARIABLE resulting in Klipper
try:
self.toolhead = self.printer.lookup_object('toolhead')
self.prev_G28 = self.gcode.register_command("G28", None)
self.gcode.register_command("G28", self.cmd_KTCC_G28, desc = self.cmd_KTCC_G28_help)
except Exception as e:
logging.exception('KTCC Warning: Error trying to wrap G28 macro: %s' % str(e))
cmd_KTCC_G28_help = "Homing axes."
def cmd_KTCC_G28(self, gcmd):
# self.trace("Starting G28")
self.save_active = False # Don't try to use SAVE_VARIABLE commands.
self.prev_G28(gcmd)
self.save_active = True # Resume to use SAVE_VARIABLE commands.
# self.trace("Ending G28")
def _save_changes_timer_event(self, eventtime):
try:
if self.save_active and self.changes_to_save:
self.changes_to_save = False
self.trace("Saving state in logs.")
self._persist_swap_statistics()
self._persist_tool_statistics()
except Exception as e:
self.debug("_save_changes_timer_event:Exception: %s" % (str(e)))
logging.exception("_save_changes_timer_event:Exception: %s" % (str(e)))
nextwake = eventtime + self.save_delay
return nextwake
def handle_connect(self):
# Load saved variables
self.variables = self.printer.lookup_object('save_variables').allVariables
# Setup background file based logging before logging any messages
if self.logfile_level >= 0:
logfile_path = self.printer.start_args['log_file']
dirname = os.path.dirname(logfile_path)
if dirname == None:
ktcc_log = '/tmp/ktcc.log'
else:
ktcc_log = dirname + '/ktcc.log'
self.debug("ktcc_log=%s" % ktcc_log)
self.queue_listener = KtccQueueListener(ktcc_log)
self.queue_listener.setFormatter(KtccMultiLineFormatter('%(asctime)s %(message)s', datefmt='%I:%M:%S'))
queue_handler = KtccQueueHandler(self.queue_listener.bg_queue)
self.ktcc_logger = logging.getLogger('ktcc')
self.ktcc_logger.setLevel(logging.INFO)
self.ktcc_logger.addHandler(queue_handler)
# Load saved values
self._load_persisted_state()
# Init persihabele statistics
self._reset_print_statistics()
# Set up timer to save values when needed
self.timer_save = self.reactor.register_timer(
self._save_changes_timer_event, self.reactor.monotonic() + (self.save_delay))
def handle_disconnect(self):
self.always('KTCC Shutdown')
self.reactor.update_timer(self.timer_save, self.reactor.NEVER)
if self.queue_listener != None:
self.queue_listener.stop()
def _load_persisted_state(self):
swap_stats = self.variables.get("ktcc_statistics_swaps", {})
try:
if swap_stats is None or swap_stats == {}:
raise Exception("Couldn't find any saved statistics.")
# self.trace("Loading statistics for KTCC: %s" % str(swap_stats))
# self.total_mounts = swap_stats['total_mounts'] or 0
self.total_time_spent_mounting = swap_stats['total_time_spent_mounting'] or 0
self.total_time_spent_unmounting = swap_stats['total_time_spent_unmounting'] or 0
self.total_toollocks = swap_stats['total_toollocks'] or 0
self.total_toolunlocks = swap_stats['total_toolunlocks'] or 0
self.total_toolmounts = swap_stats['total_toolmounts'] or 0
self.total_toolunmounts = swap_stats['total_toolunmounts'] or 0
except Exception:
# Initializing statistics
self._reset_statistics()
self.tool_statistics = {}
for tool in self.printer.lookup_objects('tool'):
try:
toolname=str(tool[0])
toolname=toolname[toolname.rindex(' ')+1:]
self.tool_statistics[toolname] = self.variables.get("%s%s" % (self.KTCC_TOOL_STATISTICS_PREFIX, toolname), self.EMPTY_TOOL_STATS.copy())
self.tool_statistics[toolname]["tracked_start_time_selected"] = 0
self.tool_statistics[toolname]["tracked_start_time_active"] = 0
self.tool_statistics[toolname]["tracked_start_time_standby"] = 0
self.tool_statistics[toolname]["tracked_unmount_start_time"] = 0
self.tool_statistics[toolname]["tracked_mount_start_time"] = 0
except Exception as err:
self.debug("Unexpected error in toolstast: %s" % err)
def _reset_print_statistics(self):
# Init persihabele statistics
self.print_time_spent_mounting = self.total_time_spent_mounting
self.print_time_spent_unmounting = self.total_time_spent_unmounting
self.print_toollocks = self.total_toollocks
self.print_toolunlocks = self.total_toolunlocks
self.print_toolmounts = self.total_toolmounts
self.print_toolunmounts = self.total_toolunmounts
self.print_tool_statistics = copy.deepcopy(self.tool_statistics)
####################################
# LOGGING FUNCTIONS #
####################################
def get_status(self, eventtime):
return {'encoder_pos': "?"}
def always(self, message):
if self.ktcc_logger:
self.ktcc_logger.info(message)
self.gcode.respond_info(message)
def info(self, message):
if self.ktcc_logger and self.logfile_level > 0:
self.ktcc_logger.info(message)
if self.log_level > 0:
self.gcode.respond_info(message)
def debug(self, message):
message = "- DEBUG: %s" % message
if self.ktcc_logger and self.logfile_level > 1:
self.ktcc_logger.info(message)
if self.log_level > 1:
self.gcode.respond_info(message)
def trace(self, message):
message = "- - TRACE: %s" % message
if self.ktcc_logger and self.logfile_level > 2:
self.ktcc_logger.info(message)
if self.log_level > 2:
self.gcode.respond_info(message)
# Fun visual display of KTCC state
def _display_visual_state(self):
if self.log_visual > 0 and not self.calibrating:
self.always(self._state_to_human_string())
def _log_level_to_human_string(self, level):
log = "OFF"
if level > 2: log = "TRACE"
elif level > 1: log = "DEBUG"
elif level > 0: log = "INFO"
elif level > -1: log = "ESSENTIAL MESSAGES"
return log
def _visual_log_level_to_human_string(self, level):
log = "OFF"
if level > 1: log = "SHORT"
elif level > 0: log = "LONG"
return log
####################################
# STATISTICS FUNCTIONS #
####################################
def _reset_statistics(self):
self.debug("Reseting KTCC statistics.")
# self.total_mounts = 0
self.total_time_spent_mounting = 0
self.total_time_spent_unmounting = 0
self.tracked_mount_start_time = 0
# self.tracked_unmount_start_time = 0
self.pause_start_time = 0
self.total_toollocks = 0
self.total_toolunlocks = 0
self.total_toolmounts = 0
self.total_toolunmounts = 0
self.tool_statistics = {}
for tool in self.printer.lookup_objects('tool'):
try:
toolname=str(tool[0])
toolname=toolname[toolname.rindex(' ')+1:]
self.tool_statistics[toolname] = self.EMPTY_TOOL_STATS.copy()
self.tool_statistics[toolname]["tracked_start_time_selected"] = 0
self.tool_statistics[toolname]["tracked_start_time_active"] = 0
self.tool_statistics[toolname]["tracked_start_time_standby"] = 0
self.tool_statistics[toolname]["tracked_unmount_start_time"] = 0
self.tool_statistics[toolname]["tracked_mount_start_time"] = 0
except Exception as err:
self.debug("Unexpected error in toolstast: %s" % err)
def track_mount_start(self, tool_id):
self.trace("track_mount_start: Running for Tool: %s." % (tool_id))
self._set_tool_statistics(tool_id, 'tracked_mount_start_time', time.time())
def track_mount_end(self, tool_id):
self.trace("track_mount_end: Running for Tool: %s." % (tool_id))
start_time = self.tool_statistics[str(tool_id)]['tracked_mount_start_time']
if start_time is not None and start_time != 0:
# self.trace("track_mount_end: start_time is not None for Tool: %s." % (tool_id))
time_spent = time.time() - start_time
self.increase_tool_statistics(tool_id, 'total_time_spent_mounting', time_spent)
self.total_time_spent_mounting += time_spent
self._set_tool_statistics(tool_id, 'tracked_mount_start_time', 0)
self.changes_to_save = True
def track_unmount_start(self, tool_id):
self.trace("track_unmount_start: Running for Tool: %s." % (tool_id))
self._set_tool_statistics(tool_id, 'tracked_unmount_start_time', time.time())
self.increase_tool_statistics(tool_id, 'toolunmounts_started')
def track_unmount_end(self, tool_id):
self.trace("track_unmount_end: Running for Tool: %s." % (tool_id))
start_time = self.tool_statistics[str(tool_id)]['tracked_unmount_start_time']
if start_time is not None and start_time != 0:
# self.trace("track_unmount_end: start_time is not None for Tool: %s." % (tool_id))
time_spent = time.time() - start_time
self.increase_tool_statistics(tool_id, 'total_time_spent_unmounting', time_spent)
self.total_time_spent_unmounting += time_spent
self._set_tool_statistics(tool_id, 'tracked_unmount_start_time', 0)
self.increase_tool_statistics(tool_id, 'toolunmounts_completed')
self.increase_statistics('total_toolunmounts')
self.changes_to_save = True
def increase_statistics(self, key, count=1):
try:
self.trace("increase_statistics: Running. Provided to record tool stats while key: %s and count: %s" % (str(key), str(count)))
if key == 'total_toolmounts':
self.total_toolmounts += int(count)
elif key == 'total_toolunmounts':
self.total_toolunmounts += int(count)
elif key == 'total_toollocks':
self.total_toollocks += int(count)
elif key == 'total_toolunlocks':
self.total_toolunlocks += int(count)
self.changes_to_save = True
except Exception as e:
self.debug("Exception whilst tracking tool stats: %s" % str(e))
self.debug("increase_statistics: Error while increasing stats while key: %s and count: %s" % (str(key), str(count)))
def track_selected_tool_start(self, tool_id):
self.trace("track_selected_tool_start: Running for Tool: %s." % (tool_id))
self._set_tool_statistics(tool_id, 'tracked_start_time_selected', time.time())
self.increase_statistics('total_toolmounts')
self.increase_tool_statistics(tool_id, 'toolmounts_completed')
def track_selected_tool_end(self, tool_id):
self.trace("track_selected_tool_end: Running for Tool: %s." % (tool_id))
self._set_tool_statistics_time_diff(tool_id, 'time_selected', 'tracked_start_time_selected')
self.changes_to_save = True
def track_active_heater_start(self, tool_id):
self.trace("track_active_heater_start: Running for Tool: %s." % (tool_id))
self._set_tool_statistics(tool_id, 'tracked_start_time_active', time.time())
def track_active_heater_end(self, tool_id):
self.trace("track_active_heater_end: Running for Tool: %s." % (tool_id))
self._set_tool_statistics_time_diff(tool_id, 'time_heater_active', 'tracked_start_time_active')
self.changes_to_save = True
def track_standby_heater_start(self, tool_id):
self.trace("track_standby_heater_start: Running for Tool: %s." % (tool_id))
self._set_tool_statistics(tool_id, 'tracked_start_time_standby', time.time())
def track_standby_heater_end(self, tool_id):
self.trace("track_standby_heater_end: Running for Tool: %s." % (tool_id))
self._set_tool_statistics_time_diff(tool_id, 'time_heater_standby', 'tracked_start_time_standby')
self.changes_to_save = True
def _seconds_to_human_string(self, seconds):
result = ""
hours = int(math.floor(seconds / 3600.))
if hours >= 1:
result += "%d hours " % hours
minutes = int(math.floor(seconds / 60.) % 60)
if hours >= 1 or minutes >= 1:
result += "%d minutes " % minutes
result += "%d seconds" % int((math.floor(seconds) % 60))
return result
def _swap_statistics_to_human_string(self):
msg = "KTCC Statistics:"
# msg += "\n%d swaps completed" % self.total_mounts
msg += "\n%s spent mounting tools" % self._seconds_to_human_string(self.total_time_spent_mounting)
msg += "\n%s spent unmounting tools" % self._seconds_to_human_string(self.total_time_spent_unmounting)
msg += "\n%d tool locks completed" % self.total_toollocks
msg += "\n%d tool unlocks completed" % self.total_toolunlocks
msg += "\n%d tool mounts completed" % self.total_toolmounts
msg += "\n%d tool unmounts completed" % self.total_toolunmounts
return msg
def _swap_print_statistics_to_human_string(self):
msg = "KTCC Statistics for this print:"
# msg += "\n%d swaps completed" % self.total_mounts
msg += "\n%s spent mounting tools" % self._seconds_to_human_string(self.total_time_spent_mounting-self.print_time_spent_mounting)
msg += "\n%s spent unmounting tools" % self._seconds_to_human_string(self.total_time_spent_unmounting-self.print_time_spent_unmounting)
msg += "\n%d tool locks completed" % (self.total_toollocks-self.print_toollocks)
msg += "\n%d tool unlocks completed" % (self.total_toolunlocks-self.print_toolunlocks)
msg += "\n%d tool mounts completed" % (self.total_toolmounts-self.print_toolmounts)
msg += "\n%d tool unmounts completed" % (self.total_toolunmounts-self.print_toolunmounts)
return msg
def _division(self, dividend, divisor):
try:
return dividend/divisor
except ZeroDivisionError:
return 0
def _dump_statistics(self, report=False):
if self.log_statistics or report:
msg = "ToolChanger Statistics:\n"
msg += self._swap_statistics_to_human_string()
msg += "\n------------\n"
msg += "Tool Statistics:\n"
# First convert to int so we get right order.
res = {int(k):v for k,v in self.tool_statistics.items()}
for tid in res:
tool_id= str(tid)
msg += "Tool#%s:\n" % (tool_id)
msg += "Completed %d out of %d mounts in %s. Average of %s per toolmount.\n" % (self.tool_statistics[tool_id]['toolmounts_completed'], self.tool_statistics[tool_id]['toolmounts_started'], self._seconds_to_human_string(self.tool_statistics[tool_id]['total_time_spent_mounting']), self._seconds_to_human_string(self._division(self.tool_statistics[tool_id]['total_time_spent_mounting'], self.tool_statistics[tool_id]['toolmounts_completed'])))
msg += "Completed %d out of %d unmounts in %s. Average of %s per toolunmount.\n" % (self.tool_statistics[tool_id]['toolunmounts_completed'], self.tool_statistics[tool_id]['toolunmounts_started'], self._seconds_to_human_string(self.tool_statistics[tool_id]['total_time_spent_unmounting']), self._seconds_to_human_string(self._division(self.tool_statistics[tool_id]['total_time_spent_unmounting'], self.tool_statistics[tool_id]['toolunmounts_completed'])))
msg += "%s spent selected." % self._seconds_to_human_string(self.tool_statistics[tool_id]['time_selected'])
tool = self.printer.lookup_object("tool " + str(tool_id))
if tool.is_virtual != True or tool.name==tool.physical_parent_id:
if tool.extruder is not None:
msg += " %s with active heater and %s with standby heater." % (self._seconds_to_human_string(self.tool_statistics[tool_id]['time_heater_active']), self._seconds_to_human_string(self.tool_statistics[tool_id]['time_heater_standby']))
msg += "\n------------\n"
self.always(msg)
def _dump_print_statistics(self, report=False):
if self.log_statistics or report:
msg = "ToolChanger Statistics for this print:\n"
msg += self._swap_print_statistics_to_human_string()
msg += "\n------------\n"
msg += "Tool Statistics for this print:\n"
# First convert to int so we get right order.
res = {int(k):v for k,v in self.tool_statistics.items()}
for tid in res:
tool_id= str(tid)
ts = self.tool_statistics[tool_id]
pts = self.print_tool_statistics[tool_id]
msg += "Tool#%s:\n" % (tool_id)
msg += "Completed %d out of %d mounts in %s. Average of %s per toolmount.\n" % ((ts['toolmounts_completed']-pts['toolmounts_completed']), (ts['toolmounts_started']-pts['toolmounts_started']), self._seconds_to_human_string(ts['total_time_spent_mounting']-pts['total_time_spent_mounting']), self._seconds_to_human_string(self._division((ts['total_time_spent_mounting']-pts['total_time_spent_mounting']), (ts['toolmounts_completed']-ts['toolmounts_completed']))))
msg += "Completed %d out of %d unmounts in %s. Average of %s per toolunmount.\n" % (ts['toolunmounts_completed']-pts['toolunmounts_completed'], ts['toolunmounts_started']-pts['toolunmounts_started'], self._seconds_to_human_string(ts['total_time_spent_unmounting']-pts['total_time_spent_unmounting']), self._seconds_to_human_string(self._division(ts['total_time_spent_unmounting']-pts['total_time_spent_unmounting'], ts['toolunmounts_completed']-pts['toolunmounts_completed'])))
msg += "%s spent selected. %s with active heater and %s with standby heater.\n" % (self._seconds_to_human_string(ts['time_selected']-pts['time_selected']), self._seconds_to_human_string(ts['time_heater_active']-pts['time_heater_active']), self._seconds_to_human_string(ts['time_heater_standby']-pts['time_heater_standby']))
msg += "------------\n"
self.always(msg)
def _persist_swap_statistics(self):
swap_stats = {
# 'total_mounts': self.total_mounts,
'total_time_spent_mounting': round(self.total_time_spent_mounting, 1),
'total_time_spent_unmounting': round(self.total_time_spent_unmounting, 1),
'total_toolunlocks': self.total_toolunlocks,
'total_toollocks': self.total_toollocks,
'total_toolmounts': self.total_toolmounts,
'total_toolunmounts': self.total_toolunmounts
}
self.toolhead.wait_moves()
self.gcode.run_script_from_command("SAVE_VARIABLE VARIABLE=%s VALUE=\"%s\"" % ("ktcc_statistics_swaps", swap_stats))
def _persist_tool_statistics(self):
for tool in self.tool_statistics:
try:
self.toolhead.wait_moves()
self.gcode.run_script_from_command("SAVE_VARIABLE VARIABLE=%s%s VALUE=\"%s\"" % (self.KTCC_TOOL_STATISTICS_PREFIX, tool, self.tool_statistics[tool]))
except Exception as err:
self.debug("Unexpected error in _persist_tool_statistics: %s" % err)
def increase_tool_statistics(self, tool_id, key, count=1):
try:
self.trace("increase_tool_statistics: Running for Tool: %s. Provided to record tool stats while key: %s and count: %s" % (tool_id, str(key), str(count)))
# if self.tool_statistics.get(str(tool_id)) is not None:
if str(tool_id) in self.tool_statistics:
if self.tool_statistics[str(tool_id)][key] is None:
self.tool_statistics[str(tool_id)][key]=0
# self.trace("increase_tool_statistics: Before running for Tool: %s. Key: %s is: %s" % (tool_id, str(key), str(self.tool_statistics[str(tool_id)][key])))
if isinstance(count, float):
self.tool_statistics[str(tool_id)][key] = round(self.tool_statistics[str(tool_id)][key] + count, 3)
else:
self.tool_statistics[str(tool_id)][key] += count
# self.trace("increase_tool_statistics: After running for Tool: %s. Key: %s is: %s" % (tool_id, str(key), str(self.tool_statistics[str(tool_id)][key])))
else:
self.debug("increase_tool_statistics: Unknown tool provided to record tool stats: %s" % tool_id)
# self.debug(str(self.tool_statistics))
except Exception as e:
self.debug("Exception whilst tracking tool stats: %s" % str(e))
self.debug("increase_tool_statistics: Error while tool: %s provided to record tool stats while key: %s and count: %s" % (tool_id, str(key), str(count)))
# self.trace("increase_tool_statistics: Tool: %s provided to record tool stats while key: %s and count: %s" % (tool_id, str(key), str(count)))
def _set_tool_statistics(self, tool_id, key, value):
self.trace("_set_tool_statistics:Running for Tool: %s provided to record tool stats while key: %s and value: %s" % (tool_id, str(key), str(value)))
try:
if str(tool_id) in self.tool_statistics:
self.tool_statistics[str(tool_id)][key] = value
else:
self.debug("_set_tool_statistics: Unknown tool: %s provided to record tool stats while key: %s and value: %s" % (tool_id, str(key), str(value)))
except Exception as e:
self.debug("Exception whilst tracking tool stats: %s" % str(e))
self.debug("_set_tool_statistics: Error while tool: %s provided to record tool stats while key: %s and value: %s" % (tool_id, str(key), str(value)))
# self.trace("_set_tool_statistics: Tool: %s provided to record tool stats while key: %s and value: %s" % (tool_id, str(key), str(value)))
def _set_tool_statistics_time_diff(self, tool_id, final_time_key, start_time_key):
try:
if str(tool_id) in self.tool_statistics:
tool_stat= self.tool_statistics[str(tool_id)]
if tool_stat[start_time_key] is not None and tool_stat[start_time_key] != 0:
# self.trace("_set_tool_statistics_time_diff: Tool: %s value before running: final_time_key: %s=%s, start_time_key: %s=%s." % (tool_id, final_time_key, str(tool_stat[final_time_key]), start_time_key, str(tool_stat[start_time_key])))
if tool_stat[final_time_key] is not None and tool_stat[final_time_key] != 0:
tool_stat[final_time_key] += time.time() - tool_stat[start_time_key]
else:
tool_stat[final_time_key] = time.time() - tool_stat[start_time_key]
tool_stat[start_time_key] = 0
else:
self.debug("_set_tool_statistics_time_diff: Unknown tool: %s provided to record tool stats while final_time_key: %s and start_time_key: %s" % (tool_id, str(final_time_key), str(start_time_key)))
except Exception as e:
self.debug("Exception whilst tracking tool stats: %s" % str(e))
self.debug("_set_tool_statistics_time_diff: Error while tool: %s provided to record tool stats while final_time_key: %s and start_time_key: %s" % (tool_id, str(final_time_key), str(start_time_key)))
# self.trace("_set_tool_statistics_time_diff: Tool: %s value after running: final_time_key: %s=%s, start_time_key: %s=%s." % (tool_id, final_time_key, str(tool_stat[final_time_key]), start_time_key, str(tool_stat[start_time_key])))
### LOGGING AND STATISTICS FUNCTIONS GCODE FUNCTIONS
cmd_KTCC_RESET_STATS_help = "Reset the KTCC statistics"
def cmd_KTCC_RESET_STATS(self, gcmd):
param = gcmd.get('SURE', "no")
if param.lower() == "yes":
self._reset_statistics()
self._reset_print_statistics()
self.changes_to_save = True
self._dump_statistics(True)
self.always("Statistics RESET.")
else:
message = "Are you sure you want to reset KTCC statistics?\n"
message += "If so, run with parameter SURE=YES:\n"
message += "KTCC_RESET_STATS SURE=YES"
self.gcode.respond_info(message)
cmd_KTCC_DUMP_STATS_help = "Dump the KTCC statistics"
def cmd_KTCC_DUMP_STATS(self, gcmd):
self._dump_statistics(True)
cmd_KTCC_INIT_PRINT_STATS_help = "Run at start of a print to initialize the KTCC print statistics"
def cmd_KTCC_INIT_PRINT_STATS(self, gcmd):
self._reset_print_statistics()
cmd_KTCC_DUMP_PRINT_STATS_help = "Run at end of a print to list statistics since last print reset."
def cmd_KTCC_DUMP_PRINT_STATS(self, gcmd):
self._dump_print_statistics(True)
cmd_KTCC_SET_LOG_LEVEL_help = "Set the log level for the KTCC"
def cmd_KTCC_SET_LOG_LEVEL(self, gcmd):
self.log_level = gcmd.get_int('LEVEL', self.log_level, minval=0, maxval=4)
self.logfile_level = gcmd.get_int('LOGFILE', self.logfile_level, minval=0, maxval=4)
self.log_visual = gcmd.get_int('VISUAL', self.log_visual, minval=0, maxval=2)
self.log_statistics = gcmd.get_int('STATISTICS', self.log_statistics, minval=0, maxval=1)
cmd_KTCC_LOG_ALWAYS_help = "Log allways MSG"
def cmd_KTCC_LOG_ALWAYS(self, gcmd):
msg = gcmd.get('MSG')
self.always(msg)
cmd_KTCC_LOG_INFO_help = "Log info MSG"
def cmd_KTCC_LOG_INFO(self, gcmd):
msg = gcmd.get('MSG')
self.info(msg)
cmd_KTCC_LOG_DEBUG_help = "Log debug MSG"
def cmd_KTCC_LOG_DEBUG(self, gcmd):
msg = gcmd.get('MSG')
self.debug(msg)
cmd_KTCC_LOG_TRACE_help = "Log trace MSG"
def cmd_KTCC_LOG_TRACE(self, gcmd):
msg = gcmd.get('MSG')
self.trace(msg)
# def _get_print_status(self):
# try:
# # If using virtual sdcard this is the most reliable method
# source = "print_stats"
# print_status = self.printer.lookup_object("print_stats").get_status(self.printer.get_reactor().monotonic())['state']
# except:
# # Otherwise we fallback to idle_timeout
# source = "idle_timeout"
# if self.printer.lookup_object("pause_resume").is_paused:
# print_status = "paused"
# else:
# idle_timeout = self.printer.lookup_object("idle_timeout").get_status(self.printer.get_reactor().monotonic())
# if idle_timeout["printing_time"] < 1.0:
# print_status = "standby"
# else:
# print_status = idle_timeout['state'].lower()
# finally:
# self.trace("Determined print status as: %s from %s" % (print_status, source))
# return print_status
# cmd_KTCC_STATUS_help = "Complete dump of current KTCC state and important configuration"
# def cmd_KTCC_STATUS(self, gcmd):
# config = gcmd.get_int('SHOWCONFIG', 0, minval=0, maxval=1)
# msg = "KTCC with %d gates" % (len(self.selector_offsets))
# msg += " is %s" % ("DISABLED" if not self.is_enabled else "PAUSED/LOCKED" if self.is_paused else "OPERATIONAL")
# msg += " with the servo in a %s position" % ("UP" if self.servo_state == self.SERVO_UP_STATE else "DOWN" if self.servo_state == self.SERVO_DOWN_STATE else "unknown")
# msg += ", Encoder reads %.2fmm" % self._counter.get_distance()
# msg += "\nSelector is %shomed" % ("" if self.is_homed else "NOT ")
# msg += ". Tool %s is selected " % self._selected_tool_string()
# msg += " on gate %s" % self._selected_gate_string()
# msg += ". Toolhead position saved pending resume" if self.saved_toolhead_position else ""
# msg += "\nFilament position: %s" % self._state_to_human_string()
# if config:
# msg += "\n\nConfiguration:\nFilament homes"
# if self._must_home_to_extruder():
# if self.homing_method == self.EXTRUDER_COLLISION:
# msg += " to EXTRUDER using COLLISION DETECTION (current %d%%)" % self.extruder_homing_current
# else:
# msg += " to EXTRUDER using STALLGUARD"
# if self._has_toolhead_sensor():
# msg += " and then"
# msg += " to TOOLHEAD SENSOR" if self._has_toolhead_sensor() else ""
# msg += " after a %.1fmm calibration reference length" % self._get_calibration_ref()
# if self.sync_load_length > 0 or self.sync_unload_length > 0:
# msg += "\nGear and Extruder steppers are synchronized during "
# load = False
# if self._has_toolhead_sensor() and self.sync_load_length > 0:
# msg += "load (up to %.1fmm)" % (self.toolhead_homing_max)
# load = True
# elif self.sync_load_length > 0:
# msg += "load (%.1fmm)" % (self.sync_load_length)
# load = True
# if self.sync_unload_length > 0:
# msg += " and " if load else ""
# msg += "unload (%.1fmm)" % (self.sync_unload_length)
# else:
# msg += "\nGear and Extruder steppers are not synchronized"
# msg += ". Tip forming current is %d%%" % self.extruder_form_tip_current
# msg += "\nSelector homing is %s - blocked gate detection and recovery %s possible" % (("sensorless", "may be") if self.sensorless_selector else ("microswitch", "is not"))
# msg += "\nClog detection is %s" % ("ENABLED" if self.enable_clog_detection else "DISABLED")
# msg += " and EndlessSpool is %s" % ("ENABLED" if self.enable_endless_spool else "DISABLED")
# p = self.persistence_level
# msg += ", %s state is persisted across restarts" % ("All" if p == 4 else "Gate status & TTG map & EndlessSpool groups" if p == 3 else "TTG map & EndlessSpool groups" if p == 2 else "EndlessSpool groups" if p == 1 else "No")
# msg += "\nLogging levels: Console %d(%s)" % (self.log_level, self._log_level_to_human_string(self.log_level))
# msg += ", Logfile %d(%s)" % (self.logfile_level, self._log_level_to_human_string(self.logfile_level))
# msg += ", Visual %d(%s)" % (self.log_visual, self._visual_log_level_to_human_string(self.log_visual))
# msg += ", Statistics %d(%s)" % (self.log_statistics, "ON" if self.log_statistics else "OFF")
# msg += "\n\nTool/gate mapping%s" % (" and EndlessSpool groups:" if self.enable_endless_spool else ":")
# msg += "\n%s" % self._tool_to_gate_map_to_human_string()
# msg += "\n\n%s" % self._swap_statistics_to_human_string()
# self._log_always(msg)
def load_config(config):
return KtccLog(config)
================================================
FILE: tool.py
================================================
# KTCC - Klipper Tool Changer Code
# Tool module, for each tool.
#
# Copyright (C) 2023 Andrei Ignat <andrei@ignat.se>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
# To try to keep terms apart:
# Mount: Tool is selected and loaded for use, be it a physical or a virtual on physical.
# Unmopunt: Tool is unselected and unloaded, be it a physical or a virtual on physical.
# Pickup: Tool is physically picked up and attached to the toolchanger head.
# Droppoff: Tool is physically parked and dropped of the toolchanger head.
# ToolLock: Toollock is engaged.
# ToolUnLock: Toollock is disengaged.
# KTCC exception error class
# class KTCCError(Exception):
# pass
# Each tool is getting an instance of this.
import logging
from .toollock import parse_restore_type
class Tool:
TOOL_UNKNOWN = -2
TOOL_UNLOCKED = -1
HEATER_STATE_ACTIVE = 2
HEATER_STATE_STANDBY = 1
HEATER_STATE_OFF = 0
def __init__(self, config = None):
self.name = None
self.toolgroup = None # defaults to 0. Check if tooltype is defined.
self.is_virtual = None
self.physical_parent_id = None # Parent tool is used as a Physical parent for all tools of this group. Only used if the tool i virtual. None gets remaped to -1.
self.extruder = None # Name of extruder connected to this tool. Defaults to None.
self.fan = None # Name of general fan configuration connected to this tool as a part fan. Defaults to "none".
self.meltzonelength = None # Length of the meltzone for retracting and inserting filament on toolchange. 18mm for e3d Revo
self.lazy_home_when_parking = None # (default: 0 - disabled) - When set to 1, will home unhomed XY axes if needed and will not move any axis if already homed and parked. 2 Will also home Z if not homed.
# Wipe. -1 = none, 1= Only load filament, 2= Wipe in front of carriage, 3= Pebble wiper, 4= First Silicone, then pebble. Defaults to None.
self.zone = None # Position of the parking zone in the format X, Y
self.park = None # Position to move to when fully parking the tool in the dock in the format X, Y
self.offset = None # Offset of the nozzle in the format X, Y, Z
self.pickup_gcode = None # The plain gcode string for pickup of the tool.
self.dropoff_gcode = None # The plain gcode string for droppoff of the tool.
self.virtual_toolload_gcode = None # The plain gcode string is to load for virtual tool having this tool as parent. This is for loading the virtual tool.
self.virtual_toolunload_gcode = None# The plain gcode string is to unload for virtual tool having this tool as parent. This is for unloading the virtual tool.
# self.timer_idle_to_standby = None
# self.timer_idle_to_powerdown = None
self.requires_pickup_for_virtual_load = None # May be needed for a filament swap to prevent ooze but not for a pen.
self.requires_pickup_for_virtual_unload = None # May be needed for a filament swap to prevent ooze but not for a pen. Used when forcing unload.
self.unload_virtual_at_dropoff = None # If it takes long time to unload/load it may be faster to leave it loaded and force unload at end of print.
self.virtual_loaded = -1 # The abstract tool loaded in the physical tool.
self.heater_state = 0 # 0 = off, 1 = standby temperature, 2 = active temperature. Placeholder.
self.heater_active_temp = 0 # Temperature to set when in active mode. Placeholder. Requred on Physical and virtual tool if any has extruder.
self.heater_standby_temp = 0 # Temperature to set when in standby mode. Placeholder. Requred on Physical and virtual tool if any has extruder.
self.idle_to_standby_time = None # Time in seconds from being parked to setting temperature to standby the temperature above. Use 0.1 to change imediatley to standby temperature. Requred on Physical tool
self.idle_to_powerdown_time = None # 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.
# Tool specific input shaper parameters. Initiated as Klipper standard.
self.shaper_freq_x = 0
self.shaper_freq_y = 0
self.shaper_type_x = "mzv"
self.shaper_type_y = "mzv"
self.shaper_damping_ratio_x = 0.1
self.shaper_damping_ratio_y = 0.1
self.config = config
# Under Consideration:
# HeatMultiplyerAtFullFanSpeed = 1 # Multiplier to be aplied to hotend temperature when fan is at maximum. Will be multiplied with fan speed. Ex. 1.1 at 205*C and fan speed of 40% will set temperature to 213*C
# If called without config then just return a dummy object.
if config is None:
return
# Load used objects.
self.printer = config.get_printer()
self.gcode = self.printer.lookup_object('gcode')
self.gcode_macro = self.printer.load_object(config, 'gcode_macro')
self.toollock = self.printer.lookup_object('toollock')
self.log = self.printer.lookup_object('ktcclog')
##### Name #####
try:
_, name = config.get_name().split(" ", 1)
self.name = int(name)
except ValueError:
raise config.error(
"Name of section '%s' contains illegal characters. Use only integer tool number."
% (config.get_name()))
##### ToolGroup #####
self.toolgroup = 'toolgroup ' + str(config.getint('tool_group'))
if config.has_section(self.toolgroup):
self.toolgroup = self.printer.lookup_object(self.toolgroup)
else:
raise config.error(
"ToolGroup of T'%s' is not defined. It must be configured before the tool."
% (config.get_name()))
tg_status = self.toolgroup.get_status()
##### Is Virtual #####
self.is_virtual = config.getboolean('is_virtual',
tg_status["is_virtual"])
##### Physical Parent #####
self.physical_parent_id = config.getint('physical_parent',
tg_status["physical_parent_id"])
if self.physical_parent_id is None:
self.physical_parent_id = self.TOOL_UNLOCKED
if self.physical_parent_id >= 0 and not self.physical_parent_id == self.name:
self.pp = self.printer.lookup_object("tool " + str(self.physical_parent_id))
else:
self.pp = Tool() # Initialize physical parent as a dummy object.
pp_status = self.pp.get_status()
# Used as sanity check for tools that are virtual with same physical as themselves.
if self.is_virtual and self.physical_parent_id == self.TOOL_UNLOCKED:
raise config.error(
"Section Tool '%s' cannot be virtual without a valid physical_parent. If Virtual and Physical then use itself as parent."
% (config.get_name()))
##### Extruder #####
self.extruder = config.get('extruder', pp_status['extruder'])
##### Fan #####
self.fan = config.get('fan', pp_status['fan'])
##### Meltzone Length #####
self.meltzonelength = self._get_config_parameter_with_inheritence('meltzonelength', 0)
##### Lazy Home when parking #####
self.lazy_home_when_parking = self._get_bool_config_parameter_with_inheritence('lazy_home_when_parking', False)
##### Coordinates #####
try:
self.zone = config.get('zone', pp_status['zone'])
if not isinstance(self.zone, list):
self.zone = str(self.zone).split(',')
self.park = config.get('park', pp_status['park'])
if not isinstance(self.park, list):
self.park = str(self.park).split(',')
self.offset = config.get('offset', pp_status['offset'])
if not isinstance(self.offset, list):
self.offset = str(self.offset).split(',')
# Remove any accidental blank spaces.
self.zone = [s.strip() for s in self.zone]
self.park = [s.strip() for s in self.park]
self.offset = [s.strip() for s in self.offset]
if len(self.zone) < 3:
raise config.error("zone Offset is malformed, must be a list of x,y,z If you want it blank, use 0,0,0")
if len(self.park) < 3:
raise config.error("park Offset is malformed, must be a list of x,y,z If you want it blank, use 0,0,0")
if len(self.offset) < 3:
raise config.error("offset Offset is malformed, must be a list of x,y,z. If you want it blank, use 0,0,0")
except Exception as e:
raise config.error(
"Coordinates of section '%s' is not well formated: %s"
% (config.get_name(), str(e)))
# Tool specific input shaper parameters. Initiated with Klipper standard values where not specified.
self.shaper_freq_x = config.get('shaper_freq_x', pp_status['shaper_freq_x'])
self.shaper_freq_y = config.get('shaper_freq_y', pp_status['shaper_freq_y'])
self.shaper_type_x = config.get('shaper_type_x', pp_status['shaper_type_x'])
self.shaper_type_y = config.get('shaper_type_y', pp_status['shaper_type_y'])
self.shaper_damping_ratio_x = config.get('shaper_damping_ratio_x', pp_status['shaper_damping_ratio_x'])
self.shaper_damping_ratio_y = config.get('shaper_damping_ratio_y', pp_status['shaper_damping_ratio_y'])
##### Standby settings (if the tool has an extruder) #####
if self.extruder is not None:
self.idle_to_standby_time = self.config.getfloat(
"idle_to_standby_time", self.pp.idle_to_standby_time)
if self.idle_to_standby_time is None:
self.idle_to_standby_time = self.toolgroup.idle_to_standby_time
self.idle_to_powerdown_time = self.config.getfloat(
"idle_to_powerdown_time", self.pp.idle_to_powerdown_time)
if self.idle_to_powerdown_time is None:
self.idle_to_powerdown_time = self.toolgroup.idle_to_powerdown_time
# For all virtual tools that are not also a physical parent, use physical parent's timer.
if self.physical_parent_id > self.TOOL_UNLOCKED and self.physical_parent_id != self.name:
self.timer_idle_to_standby = self.pp.get_timer_to_standby()
self.timer_idle_to_powerdown = self.pp.get_timer_to_powerdown()
else:
# Set up new timers if physical tool.
self.timer_idle_to_standby = ToolStandbyTempTimer(self.printer, self.name, ToolStandbyTempTimer.TIMER_TO_STANDBY)
self.timer_idle_to_powerdown = ToolStandbyTempTimer(self.printer, self.name, ToolStandbyTempTimer.TIMER_TO_SHUTDOWN)
##### G-Code ToolChange #####
self.pickup_gcode_template = self._get_gcode_template_with_inheritence('pickup_gcode')
self.dropoff_gcode_template = self._get_gcode_template_with_inheritence('dropoff_gcode')
##### G-Code VirtualToolChange #####
if self.is_virtual:
self.virtual_toolload_gcode_template = self._get_gcode_template_with_inheritence('virtual_toolload_gcode')
self.virtual_toolunload_gcode_template = self._get_gcode_template_with_inheritence('virtual_toolunload_gcode')
##### Parameters for VirtualToolChange #####
self.requires_pickup_for_virtual_load = self.config.getboolean(
"requires_pickup_for_virtual_load", self.pp.requires_pickup_for_virtual_load)
if self.requires_pickup_for_virtual_load is None:
self.requires_pickup_for_virtual_load = self.toolgroup.requires_pickup_for_virtual_load
self.requires_pickup_for_virtual_unload = self.config.getboolean(
"requires_pickup_for_virtual_unload", self.pp.requires_pickup_for_virtual_unload)
if self.requires_pickup_for_virtual_unload is None:
self.requires_pickup_for_virtual_unload = self.toolgroup.requires_pickup_for_virtual_unload
self.unload_virtual_at_dropoff = self.config.getboolean(
"unload_virtual_at_dropoff", self.pp.unload_virtual_at_dropoff)
if self.unload_virtual_at_dropoff is None:
self.unload_virtual_at_dropoff = self.toolgroup.unload_virtual_at_dropoff
logging.warn("T%s unload_virtual_at_dropoff: %s" % (str(self.name), str(self.requires_pickup_for_virtual_load)))
##### Register Tool select command #####
self.gcode.register_command("KTCC_T" + str(self.name), self.cmd_SelectTool, desc=self.cmd_SelectTool_help)
def _get_bool_config_parameter_with_inheritence(self, config_param, default = None):
tmp = self.config.getboolean(config_param, self.pp.get_config(config_param))
if tmp is None:
tmp = self.toolgroup.get_config(config_param, default)
return tmp
def _get_config_parameter_with_inheritence(self, config_param, default = None):
tmp = self.config.get(config_param, self.pp.get_config(config_param))
if tmp is None:
tmp = self.toolgroup.get_config(config_param, default)
return tmp
def _get_gcode_template_with_inheritence(self, config_param, optional = False):
temp_gcode = self.pp.get_config(config_param) # First try to get gcode parameter from eventual physical Parent.
if temp_gcode is None: # If didn't get any from physical parent,
temp_gcode = self.toolgroup.get_config(config_param) # try getting from toolgroup.
if optional and temp_gcode is None:
temp_gcode = ""
# gcode = self.get_config(config_param, temp_gcode) # Get from this config and fallback on previous.
template = self.gcode_macro.load_template(self.config, config_param, temp_gcode)
return template
def get_config(self, config_param, default = None):
if self.config is None: return None
return self.config.get(config_param, default)
cmd_SelectTool_help = "Select Tool"
def cmd_SelectTool(self, gcmd):
self.log.trace("KTCC T" + str(self.name) + " Selected.")
# Allow either one.
restore_mode = parse_restore_type(gcmd, 'R', None)
restore_mode = parse_restore_type(gcmd, 'RESTORE_POSITION_TYPE', restore_mode)
# Check if the requested tool has been remaped to another one.
tool_is_remaped = self.toollock.tool_is_remaped(int(self.name))
if tool_is_remaped > -1:
self.log.always("Tool %d is remaped to Tool %d" % (self.name, tool_is_remaped))
remaped_tool = self.printer.lookup_object('tool ' + str(tool_is_remaped))
remaped_tool.select_tool_actual(restore_mode)
return
else:
self.select_tool_actual(restore_mode)
# To avoid recursive remaping.
def select_tool_actual(self, restore_mode = None):
current_tool_id = int(self.toollock.get_status()['tool_current']) # int(self.toollock.get_tool_current())
self.log.trace("Current Tool is T" + str(current_tool_id) + ".")
self.log.trace("This tool is_virtual is " + str(self.is_virtual) + ".")
if current_tool_id == self.name: # If trying to select the already selected tool:
return # Exit
if current_tool_id < self.TOOL_UNLOCKED:
msg = "TOOL_PICKUP: Unknown tool already mounted Can't park it before selecting new tool."
self.log.always(msg)
raise self.printer.command_error(msg)
self.log.increase_tool_statistics(self.name, 'toolmounts_started')
if self.extruder is not None: # If the new tool to be selected has an extruder prepare warmup before actual tool change so all unload commands will be done while heating up.
self.set_heater(heater_state = self.HEATER_STATE_ACTIVE)
# If optional RESTORE_POSITION_TYPE parameter is passed then save current position.
# Otherwise do not change either the restore_axis_on_toolchange or saved_position.
# This makes it possible to call SAVE_POSITION or SAVE_CURRENT_POSITION before the actual T command.
if restore_mode is not None:
self.toollock.SaveCurrentPosition(restore_mode) # Sets restore_axis_on_toolchange and saves current position
# Drop any tools already mounted if not virtual on same.
if current_tool_id > self.TOOL_UNLOCKED: # If there is a current tool already selected and it's a known tool.
self.log.track_selected_tool_end(current_tool_id) # Log that the current tool is to be unmounted.
current_tool = self.printer.lookup_object('tool ' + str(current_tool_id))
# If the next tool is not another virtual tool on the same physical tool.
if int(self.physical_parent_id == self.TOOL_UNLOCKED or
self.physical_parent_id) != int(
current_tool.get_status()["physical_parent_id"]
):
self.log.info("Will Dropoff():%s" % str(current_tool_id))
current_tool.Dropoff()
current_tool_id = self.TOOL_UNLOCKED
else: # If it's another virtual tool on the same parent physical tool.
self.log.info("Dropoff: T" + str(current_tool_id) + "- Virtual - Running UnloadVirtual")
current_tool.UnloadVirtual()
# Now we asume tool has been dropped if needed be.
# Check if this is a virtual tool.
if not self.is_virtual:
self.log.trace("cmd_SelectTool: T%s - Not Virtual - Pickup" % str(self.name))
self.Pickup()
else:
if current_tool_id > self.TOOL_UNLOCKED: # If still has a selected tool: (This tool is a virtual tool with same physical tool as the last)
current_tool = self.printer.lookup_object('tool ' + str(current_tool_id))
self.log.trace("cmd_SelectTool: T" + str(self.name) + "- Virtual - Physical Tool is not Dropped - ")
if self.physical_parent_id > self.TOOL_UNLOCKED and self.physical_parent_id == current_tool.get_status()["physical_parent_id"]:
self.log.trace("cmd_SelectTool: T" + str(self.name) + "- Virtual - Same physical tool - Pickup")
self.LoadVirtual()
else:
msg = "cmd_SelectTool: T" + str(self.name) + "- Virtual - Not Same physical tool"
msg += "Shouldn't reach this because it is dropped in previous."
self.log.debug(msg)
raise Exception(msg)
else: # New Physical tool with a virtual tool.
pp = self.printer.lookup_object('tool ' + str(self.physical_parent_id))
pp_virtual_loaded = pp.get_status()["virtual_loaded"]
self.log.trace("cmd_SelectTool: T" + str(self.name) + "- Virtual - Picking upp physical tool")
self.Pickup()
# If the new physical tool already has another virtual tool loaded:
if pp_virtual_loaded > self.TOOL_UNLOCKED:
if pp_virtual_loaded != self.name:
self.log.info("cmd_SelectTool: T" + str(pp_virtual_loaded) + "- Virtual - Running UnloadVirtual")
uv= self.printer.lookup_object('tool ' + str(pp_virtual_loaded))
if uv.extruder is not None: # If the new tool to be selected has an extruder prepare warmup before actual tool change so all unload commands will be done while heating up.
curtime = self.printer.get_reactor().monotonic()
# heater = self.printer.lookup_object(self.extruder).get_heater()
uv.set_heater(heater_state = self.HEATER_STATE_ACTIVE)
# if int(self.heater_state) == self.HEATER_STATE_ACTIVE and int(self.heater_standby_temp) < int(heater.get_status(curtime)["temperature"]):
self.toollock._Temperature_wait_with_tolerance(curtime, self.extruder, 2)
uv.UnloadVirtual()
self.set_heater(heater_state = self.HEATER_STATE_ACTIVE)
self.log.trace("cmd_SelectTool: T" + str(self.name) + "- Virtual - Picked up physical tool and now Loading virtual tool.")
self.LoadVirtual()
self.toollock.SaveCurrentTool(self.name)
self.log.track_selected_tool_start(self.name)
def Pickup(self):
self.log.track_mount_start(self.name) # Log the time it takes for tool mount.
# Check if homed
if not self.toollock.PrinterIsHomedForToolchange():
raise self.printer.command_error("Tool.Pickup: Printer not homed and Lazy homing option for tool %s is: %s" % (str(self.name), str(self.lazy_home_when_parking)))
return None
# If has an extruder then activate that extruder.
if self.extruder is not None:
self.gcode.run_script_from_command(
"ACTIVATE_EXTRUDER extruder=%s" %
(self.extruder))
# Run the gcode for pickup.
try:
context = self.pickup_gcode_template.create_template_context()
context['myself'] = self.get_status()
context['toollock'] = self.toollock.get_status()
self.pickup_gcode_template.run_gcode_from_command(context)
except Exception as e:
raise Exception("Pickup gcode: Script running error: %s" % (str(e)))
# Restore fan if has a fan.
if self.fan is not None:
self.gcode.run_script_from_command(
"SET_FAN_SPEED FAN=" + self.fan + " SPEED=" + str(self.toollock.get_status()['saved_fan_speed']))
# Set Tool specific input shaper. -- Deprecated --
if self.shaper_freq_x != 0 or self.shaper_freq_y != 0:
self.log.always("shaper_freq will be deprecated. Use SET_INPUT_SHAPER inside the pickup gcode instead.")
cmd = ("SET_INPUT_SHAPER" +
" SHAPER_FREQ_X=" + str(self.shaper_freq_x) +
" SHAPER_FREQ_Y=" + str(self.shaper_freq_y) +
" DAMPING_RATIO_X=" + str(self.shaper_damping_ratio_x) +
" DAMPING_RATIO_Y=" + str(self.shaper_damping_ratio_y) +
" SHAPER_TYPE_X=" + str(self.shaper_type_x) +
" SHAPER_TYPE_Y=" + str(self.shaper_type_y) )
self.log.trace("Pickup_inpshaper: " + cmd)
self.gcode.run_script_from_command(cmd)
# Save current picked up tool and print on screen.
self.toollock.SaveCurrentTool(self.name)
if self.is_virtual:
self.log.always("Physical Tool for T%d picked up." % (self.name))
else:
self.log.always("T%d picked up." % (self.name))
self.log.track_mount_end(self.name) # Log number of toolchanges and the time it takes for tool mounting.
def Dropoff(self, force_virtual_unload = False):
self.log.always("Dropoff: T%s - Running." % str(self.name))
self.log.track_selected_tool_end(self.name) # Log that the current tool is to be unmounted.
# Check if homed
if not self.toollock.PrinterIsHomedForToolchange():
self.log.always("Tool.Dropoff: Printer not homed and Lazy homing option is: " + str(self.lazy_home_when_parking))
return None
# Turn off fan if has a fan.
if self.fan is not None:
self.gcode.run_script_from_command(
"SET_FAN_SPEED FAN=" + self.fan + " SPEED=0" )
# Check if this is a virtual tool.
self.log.trace("Dropoff: T" + str(self.name) + "- is_virtual: " + str(self.is_virtual))
if self.is_virtual:
# Only dropoff if it is required.
if self.unload_virtual_at_dropoff or force_virtual_unload:
self.log.debug("T%s: unload_virtual_at_dropoff: %s, force_virtual_unload: %s" % (str(self.name), str(self.unload_virtual_at_dropoff), str(force_virtual_unload)))
self.log.info("Dropoff: T" + str(self.name) + "- Virtual - Running UnloadVirtual")
self.UnloadVirtual()
self.log.track_unmount_start(self.name) # Log the time it takes for tool change.
# Run the gcode for dropoff.
try:
context = self.dropoff_gcode_template.create_template_context()
context['myself'] = self.get_status()
context['toollock'] = self.toollock.get_status()
self.dropoff_gcode_template.run_gcode_from_command(context)
except Exception as e:
raise Exception("Dropoff gcode: Script running error: %s" % (str(e)))
self.toollock.SaveCurrentTool(self.TOOL_UNLOCKED) # Dropoff successfull
self.log.track_unmount_end(self.name) # Log the time it takes for tool change.
def LoadVirtual(self):
self.log.info("Loading virtual tool: T%d." % self.name)
self.log.track_mount_start(self.name) # Log the time it takes for tool mount.
# Run the gcode for Virtual Load.
try:
context = self.virtual_toolload_gcode_template.create_template_context()
context['myself'] = self.get_status()
context['toollock'] = self.toollock.get_status()
self.virtual_toolload_gcode_template.run_gcode_from_command(context)
except Exception as e:
raise Exception("virtual_toolload_gcode: Script running error: %s" % (str(e)))
pp = self.printer.lookup_object('tool ' + str(self.physical_parent_id))
pp.set_virtual_loaded(int(self.name))
# Save current picked up tool and print on screen.
self.toollock.SaveCurrentTool(self.name)
self.log.trace("Virtual T%d Loaded" % (int(self.name)))
self.log.track_mount_end(self.name) # Log number of toolchanges and the time it takes for tool mounting.
def set_virtual_loaded(self, value = -1):
self.virtual_loaded = value
self.log.trace("Saved VirtualToolLoaded for T%s as: %s" % (str(self.name), str(value)))
def UnloadVirtual(self):
self.log.info("Unloading virtual tool: T%d." % self.name)
self.log.track_unmount_start(self.name) # Log the time it takes for tool unload.
# Run the gcode for Virtual Unload.
try:
context = self.virtual_toolunload_gcode_template.create_template_context()
context['myself'] = self.get_status()
context['toollock'] = self.toollock.get_status()
self.virtual_toolunload_gcode_template.run_gcode_from_command(context)
except Exception as e:
raise Exception("virtual_toolunload_gcode: Script running error:\n%s" % str(e))
pp = self.printer.lookup_object('tool ' + str(self.physical_parent_id))
pp.set_virtual_loaded(-1)
# Save current picked up tool and print on screen.
self.toollock.SaveCurrentTool(self.name)
self.log.trace("Virtual T%d Unloaded" % (int(self.name)))
self.log.track_unmount_end(self.name) # Log the time it takes for tool unload.
def set_offset(self, **kwargs):
for i in kwargs:
if i == "x_pos":
self.offset[0] = float(kwargs[i])
elif i == "x_adjust":
self.offset[0] = float(self.offset[0]) + float(kwargs[i])
elif i == "y_pos":
self.offset[1] = float(kwargs[i])
elif i == "y_adjust":
self.offset[1] = float(self.offset[1]) + float(kwargs[i])
elif i == "z_pos":
self.offset[2] = float(kwargs[i])
elif i == "z_adjust":
self.offset[2] = float(self.offset[2]) + float(kwargs[i])
self.log.always("T%d offset now set to: %f, %f, %f." % (int(self.name), float(self.offset[0]), float(self.offset[1]), float(self.offset[2])))
def _set_state(self, heater_state):
self.heater_state = heater_state
def set_heater(self, **kwargs):
if self.extruder is None:
self.log.debug("set_heater: T%d has no extruder! Nothing to do." % self.name )
return None
# self.log.info("T%d heater is at begingin %s." % (self.name, self.heater_state ))
heater = self.printer.lookup_object(self.extruder).get_heater()
curtime = self.printer.get_reactor().monotonic()
changing_timer = False
# self is always pointing to virtual tool but its timers and extruder are always pointing to the physical tool. When changing multiple virtual tools heaters the statistics can remain open when changing by timers of the parent if another one got in between.
# Therefore it's important for all heater statistics to only point to physical parent.
if self.is_virtual == True:
tool_for_tracking_heater = self.physical_parent_id
else:
tool_for_tracking_heater = self.name
# First set state if changed, so we set correct temps.
if "heater_state" in kwargs:
chng_state = kwargs["heater_state"]
for i in kwargs:
if i == "heater_active_temp":
self.heater_active_temp = kwargs[i]
if int(self.heater_state) == self.HEATER_STATE_ACTIVE:
heater.set_temp(self.heater_active_temp)
elif i == "heater_standby_temp":
self.heater_standby_temp = kwargs[i]
if int(self.heater_state) == self.HEATER_STATE_STANDBY:
heater.set_temp(self.heater_standby_temp)
elif i == "idle_to_standby_time":
self.idle_to_standby_time = kwargs[i]
changing_timer = True
elif i == "idle_to_powerdown_time":
self.idle_to_powerdown_time = kwargs[i]
changing_timer = True
# If already in standby and timers are counting down, i.e. have not triggered since set in standby, then reset the ones counting down.
if int(self.heater_state) == self.HEATER_STATE_STANDBY and changing_timer:
if self.timer_idle_to_powerdown.get_status()["counting_down"] == True:
self.timer_idle_to_powerdown.set_timer(self.idle_to_powerdown_time, self.name)
gitextract_03dvn_i_/ ├── LICENSE ├── README.md ├── assets/ │ └── q ├── config/ │ ├── SuperSlicer_Custom_Gcode.md │ ├── example_complex/ │ │ ├── readme.md │ │ ├── tool_macro.cfg │ │ └── tools.cfg │ ├── example_simple/ │ │ ├── readme.md │ │ └── tools.cfg │ ├── optional_macros/ │ │ ├── G10.cfg │ │ ├── M104.cfg │ │ ├── M106.cfg │ │ ├── M107.cfg │ │ ├── M109.cfg │ │ ├── M116.cfg │ │ ├── M204.cfg │ │ ├── M568.cfg │ │ └── readme.md │ └── readme.md ├── doc/ │ └── command_ref.md ├── install.sh ├── klipper_macros/ │ ├── G10.cfg │ ├── M104.cfg │ ├── M106.cfg │ ├── M107.cfg │ ├── M109.cfg │ ├── M116.cfg │ ├── M204.cfg │ ├── M566.cfg │ ├── M568.cfg │ └── readme.md ├── ktcclog.py ├── tool.py ├── toolgroup.py └── toollock.py
SYMBOL INDEX (137 symbols across 4 files)
FILE: ktcclog.py
class KtccQueueHandler (line 23) | class KtccQueueHandler(logging.Handler):
method __init__ (line 24) | def __init__(self, queue):
method emit (line 28) | def emit(self, record):
class KtccQueueListener (line 39) | class KtccQueueListener(logging.handlers.TimedRotatingFileHandler):
method __init__ (line 40) | def __init__(self, filename):
method _bg_thread (line 47) | def _bg_thread(self):
method stop (line 54) | def stop(self):
class KtccMultiLineFormatter (line 59) | class KtccMultiLineFormatter(logging.Formatter):
method format (line 60) | def format(self, record):
class KtccLog (line 65) | class KtccLog:
method __init__ (line 71) | def __init__(self, config):
method handle_ready (line 106) | def handle_ready(self):
method cmd_KTCC_G28 (line 121) | def cmd_KTCC_G28(self, gcmd):
method _save_changes_timer_event (line 128) | def _save_changes_timer_event(self, eventtime):
method handle_connect (line 142) | def handle_connect(self):
method handle_disconnect (line 172) | def handle_disconnect(self):
method _load_persisted_state (line 178) | def _load_persisted_state(self):
method _reset_print_statistics (line 210) | def _reset_print_statistics(self):
method get_status (line 223) | def get_status(self, eventtime):
method always (line 226) | def always(self, message):
method info (line 231) | def info(self, message):
method debug (line 237) | def debug(self, message):
method trace (line 244) | def trace(self, message):
method _display_visual_state (line 252) | def _display_visual_state(self):
method _log_level_to_human_string (line 256) | def _log_level_to_human_string(self, level):
method _visual_log_level_to_human_string (line 264) | def _visual_log_level_to_human_string(self, level):
method _reset_statistics (line 275) | def _reset_statistics(self):
method track_mount_start (line 304) | def track_mount_start(self, tool_id):
method track_mount_end (line 309) | def track_mount_end(self, tool_id):
method track_unmount_start (line 320) | def track_unmount_start(self, tool_id):
method track_unmount_end (line 325) | def track_unmount_end(self, tool_id):
method increase_statistics (line 339) | def increase_statistics(self, key, count=1):
method track_selected_tool_start (line 355) | def track_selected_tool_start(self, tool_id):
method track_selected_tool_end (line 361) | def track_selected_tool_end(self, tool_id):
method track_active_heater_start (line 366) | def track_active_heater_start(self, tool_id):
method track_active_heater_end (line 370) | def track_active_heater_end(self, tool_id):
method track_standby_heater_start (line 375) | def track_standby_heater_start(self, tool_id):
method track_standby_heater_end (line 379) | def track_standby_heater_end(self, tool_id):
method _seconds_to_human_string (line 384) | def _seconds_to_human_string(self, seconds):
method _swap_statistics_to_human_string (line 395) | def _swap_statistics_to_human_string(self):
method _swap_print_statistics_to_human_string (line 406) | def _swap_print_statistics_to_human_string(self):
method _division (line 417) | def _division(self, dividend, divisor):
method _dump_statistics (line 423) | def _dump_statistics(self, report=False):
method _dump_print_statistics (line 448) | def _dump_print_statistics(self, report=False):
method _persist_swap_statistics (line 471) | def _persist_swap_statistics(self):
method _persist_tool_statistics (line 484) | def _persist_tool_statistics(self):
method increase_tool_statistics (line 492) | def increase_tool_statistics(self, tool_id, key, count=1):
method _set_tool_statistics (line 513) | def _set_tool_statistics(self, tool_id, key, value):
method _set_tool_statistics_time_diff (line 525) | def _set_tool_statistics_time_diff(self, tool_id, final_time_key, star...
method cmd_KTCC_RESET_STATS (line 546) | def cmd_KTCC_RESET_STATS(self, gcmd):
method cmd_KTCC_DUMP_STATS (line 561) | def cmd_KTCC_DUMP_STATS(self, gcmd):
method cmd_KTCC_INIT_PRINT_STATS (line 565) | def cmd_KTCC_INIT_PRINT_STATS(self, gcmd):
method cmd_KTCC_DUMP_PRINT_STATS (line 569) | def cmd_KTCC_DUMP_PRINT_STATS(self, gcmd):
method cmd_KTCC_SET_LOG_LEVEL (line 573) | def cmd_KTCC_SET_LOG_LEVEL(self, gcmd):
method cmd_KTCC_LOG_ALWAYS (line 580) | def cmd_KTCC_LOG_ALWAYS(self, gcmd):
method cmd_KTCC_LOG_INFO (line 585) | def cmd_KTCC_LOG_INFO(self, gcmd):
method cmd_KTCC_LOG_DEBUG (line 590) | def cmd_KTCC_LOG_DEBUG(self, gcmd):
method cmd_KTCC_LOG_TRACE (line 595) | def cmd_KTCC_LOG_TRACE(self, gcmd):
function load_config (line 673) | def load_config(config):
FILE: tool.py
class Tool (line 24) | class Tool:
method __init__ (line 31) | def __init__(self, config = None):
method _get_bool_config_parameter_with_inheritence (line 232) | def _get_bool_config_parameter_with_inheritence(self, config_param, de...
method _get_config_parameter_with_inheritence (line 238) | def _get_config_parameter_with_inheritence(self, config_param, default...
method _get_gcode_template_with_inheritence (line 244) | def _get_gcode_template_with_inheritence(self, config_param, optional ...
method get_config (line 256) | def get_config(self, config_param, default = None):
method cmd_SelectTool (line 261) | def cmd_SelectTool(self, gcmd):
method select_tool_actual (line 280) | def select_tool_actual(self, restore_mode = None):
method Pickup (line 374) | def Pickup(self):
method Dropoff (line 424) | def Dropoff(self, force_virtual_unload = False):
method LoadVirtual (line 462) | def LoadVirtual(self):
method set_virtual_loaded (line 483) | def set_virtual_loaded(self, value = -1):
method UnloadVirtual (line 488) | def UnloadVirtual(self):
method set_offset (line 510) | def set_offset(self, **kwargs):
method _set_state (line 527) | def _set_state(self, heater_state):
method set_heater (line 531) | def set_heater(self, **kwargs):
method get_timer_to_standby (line 622) | def get_timer_to_standby(self):
method get_timer_to_powerdown (line 625) | def get_timer_to_powerdown(self):
method get_status (line 628) | def get_status(self, eventtime= None):
class ToolStandbyTempTimer (line 659) | class ToolStandbyTempTimer:
method __init__ (line 663) | def __init__(self, printer, tool_id, temp_type):
method _handle_ready (line 683) | def _handle_ready(self):
method _standby_tool_temp_timer_event (line 687) | def _standby_tool_temp_timer_event(self, eventtime):
method set_timer (line 740) | def set_timer(self, duration, actual_tool_calling):
method get_status (line 759) | def get_status(self, eventtime= None):
method _time_left (line 770) | def _time_left(self):
class MeanLayerTime (line 779) | class MeanLayerTime:
method __init__ (line 780) | def __init__(self, printer):
function load_config_prefix (line 791) | def load_config_prefix(config):
FILE: toolgroup.py
class ToolGroup (line 18) | class ToolGroup:
method __init__ (line 19) | def __init__(self, config):
method get_config (line 52) | def get_config(self, config_param, default = None):
method get_status (line 55) | def get_status(self, eventtime= None):
function load_config_prefix (line 69) | def load_config_prefix(config):
FILE: toollock.py
class ToolLock (line 17) | class ToolLock:
method __init__ (line 23) | def __init__(self, config):
method handle_ready (line 73) | def handle_ready(self):
method _bootup_tasks (line 79) | def _bootup_tasks(self, eventtime):
method Initialize_Tool_Lock (line 87) | def Initialize_Tool_Lock(self):
method cmd_TOOL_LOCK (line 111) | def cmd_TOOL_LOCK(self, gcmd = None):
method ToolLock (line 114) | def ToolLock(self, ignore_locked = False):
method cmd_KTCC_TOOL_DROPOFF_ALL (line 126) | def cmd_KTCC_TOOL_DROPOFF_ALL(self, gcmd = None):
method cmd_TOOL_UNLOCK (line 154) | def cmd_TOOL_UNLOCK(self, gcmd = None):
method PrinterIsHomedForToolchange (line 162) | def PrinterIsHomedForToolchange(self, lazy_home_when_parking =0):
method SaveCurrentTool (line 180) | def SaveCurrentTool(self, t):
method cmd_SAVE_CURRENT_TOOL (line 187) | def cmd_SAVE_CURRENT_TOOL(self, gcmd):
method cmd_SET_AND_SAVE_FAN_SPEED (line 193) | def cmd_SET_AND_SAVE_FAN_SPEED(self, gcmd):
method SetAndSaveFanSpeed (line 215) | def SetAndSaveFanSpeed(self, tool_id, fanspeed):
method cmd_TEMPERATURE_WAIT_WITH_TOLERANCE (line 242) | def cmd_TEMPERATURE_WAIT_WITH_TOLERANCE(self, gcmd):
method _Temperature_wait_with_tolerance (line 279) | def _Temperature_wait_with_tolerance(self, curtime, heater_name, toler...
method _get_tool_id_from_gcmd (line 292) | def _get_tool_id_from_gcmd(self, gcmd):
method cmd_SET_TOOL_TEMPERATURE (line 318) | def cmd_SET_TOOL_TEMPERATURE(self, gcmd):
method cmd_KTCC_SET_ALL_TOOL_HEATERS_OFF (line 362) | def cmd_KTCC_SET_ALL_TOOL_HEATERS_OFF(self, gcmd):
method set_all_tool_heaters_off (line 365) | def set_all_tool_heaters_off(self):
method cmd_KTCC_RESUME_ALL_TOOL_HEATERS (line 384) | def cmd_KTCC_RESUME_ALL_TOOL_HEATERS(self, gcmd):
method resume_all_tool_heaters (line 387) | def resume_all_tool_heaters(self):
method cmd_SET_TOOL_OFFSET (line 404) | def cmd_SET_TOOL_OFFSET(self, gcmd):
method cmd_SET_GLOBAL_OFFSET (line 434) | def cmd_SET_GLOBAL_OFFSET(self, gcmd):
method cmd_SET_PURGE_ON_TOOLCHANGE (line 458) | def cmd_SET_PURGE_ON_TOOLCHANGE(self, gcmd = None):
method SaveFanSpeed (line 466) | def SaveFanSpeed(self, fanspeed):
method cmd_SAVE_POSITION (line 473) | def cmd_SAVE_POSITION(self, gcmd):
method SavePosition (line 479) | def SavePosition(self, param_X = None, param_Y = None, param_Z = None):
method cmd_SAVE_CURRENT_POSITION (line 498) | def cmd_SAVE_CURRENT_POSITION(self, gcmd):
method SaveCurrentPosition (line 503) | def SaveCurrentPosition(self, restore_axis = None):
method cmd_RESTORE_POSITION (line 517) | def cmd_RESTORE_POSITION(self, gcmd):
method get_status (line 540) | def get_status(self, eventtime= None):
method cmd_KTCC_SET_GCODE_OFFSET_FOR_CURRENT_TOOL (line 558) | def cmd_KTCC_SET_GCODE_OFFSET_FOR_CURRENT_TOOL(self, gcmd):
method _set_tool_to_tool (line 579) | def _set_tool_to_tool(self, from_tool, to_tool):
method _tool_map_to_human_string (line 590) | def _tool_map_to_human_string(self):
method tool_is_remaped (line 598) | def tool_is_remaped(self, tool_to_check):
method _remap_tool (line 604) | def _remap_tool(self, tool, gate, available):
method _reset_tool_mapping (line 608) | def _reset_tool_mapping(self):
method cmd_KTCC_DISPLAY_TOOL_MAP (line 616) | def cmd_KTCC_DISPLAY_TOOL_MAP(self, gcmd):
method cmd_KTCC_REMAP_TOOL (line 621) | def cmd_KTCC_REMAP_TOOL(self, gcmd):
method cmd_KTCC_ENDSTOP_QUERY (line 640) | def cmd_KTCC_ENDSTOP_QUERY(self, gcmd):
method query_endstop (line 646) | def query_endstop(self, endstop_name, should_be_triggered=True, atempt...
function parse_restore_type (line 683) | def parse_restore_type(gcmd, arg_name, default = None):
function load_config (line 703) | def load_config(config):
Condensed preview — 35 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (257K chars).
[
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 11103,
"preview": "<p align=\"center\">\n <img src=\"assets/toolchanger.jpg?raw=true\" alt='A Toolchenager' width='40%'>\n <h1 align=\"center\">T"
},
{
"path": "assets/q",
"chars": 1,
"preview": "\n"
},
{
"path": "config/SuperSlicer_Custom_Gcode.md",
"chars": 2640,
"preview": "Here are the custom G-codes I use in SuperSlicer on my ToolChanger as an example.\n\nStart G-code:\n - I don't heat the too"
},
{
"path": "config/example_complex/readme.md",
"chars": 441,
"preview": "# More complex example\n\nThis are example files with macros to get you started.\n* It uses T0 as a physical tool having T"
},
{
"path": "config/example_complex/tool_macro.cfg",
"chars": 5881,
"preview": "[gcode_macro TOOL_LOCK_CHECK]\ndescription: Check so the tool is mounted by slightly advancing the lock again until hit e"
},
{
"path": "config/example_complex/tools.cfg",
"chars": 24502,
"preview": "# Config order: ToolGroups must come before tools that use them. Tool that are used as physical_parent must be configure"
},
{
"path": "config/example_simple/readme.md",
"chars": 197,
"preview": "# Simple examples\n\nThis are basic example file to get you started.\n\nthe files should be added to your printer.cfg like:\n"
},
{
"path": "config/example_simple/tools.cfg",
"chars": 6093,
"preview": "# Simple sample configuration for getting started with a ToolChanger with 2 tools.\n\n\n# Enables saving of variables betwe"
},
{
"path": "config/optional_macros/G10.cfg",
"chars": 87,
"preview": "[gcode_macro G10]\ndescription: See M568. Passtrough to M568.\ngcode:\n M568 {rawparams}\n"
},
{
"path": "config/optional_macros/M104.cfg",
"chars": 751,
"preview": "[gcode_macro M104]\nrename_existing: M104.1\ndescription: [T<index>] [S<temperature>]\n Set tool temperature.\n T= Tool nu"
},
{
"path": "config/optional_macros/M106.cfg",
"chars": 870,
"preview": "[gcode_macro M106]\nvariable_fan_speed: 0\ndescription: Snnn Pnnn\n Set fan speed. A KTCC tool must be configured for this"
},
{
"path": "config/optional_macros/M107.cfg",
"chars": 338,
"preview": "[gcode_macro M107]\ndescription: Pnnn\n Turn off fan.\n P = Tool (optional and defaults to the currently selected tool)\ng"
},
{
"path": "config/optional_macros/M109.cfg",
"chars": 1661,
"preview": "[gcode_macro M109]\nrename_existing: M109.1\ndescription: T<index> P<index> H<index> S<temperature> W<Tolerance>\n Waits f"
},
{
"path": "config/optional_macros/M116.cfg",
"chars": 530,
"preview": "[gcode_macro M116]\ndescription: T<index> P<index> H<index> S<temperature> W<Tolerance>\n Alias for M109.\n Waits for all"
},
{
"path": "config/optional_macros/M204.cfg",
"chars": 677,
"preview": "[gcode_macro M204]\nrename_existing: M204.1\ndescription: Snnn / Pnnn Tnnn\n Set acceleration either S or P and T must be "
},
{
"path": "config/optional_macros/M568.cfg",
"chars": 2521,
"preview": "[gcode_macro M568]\ndescription: Pnnn Tnnn Rnnn Snnn An Nnnn Mnnn\n Set tool temperature.\n P= Tool number, optional. If "
},
{
"path": "config/optional_macros/readme.md",
"chars": 3989,
"preview": "# Required and Optional G-code macros\n\nThe required macros change how Klipper uses those commands to make use of the too"
},
{
"path": "config/readme.md",
"chars": 6366,
"preview": "# Configuration reference\nThis document is a reference for options available in the Klipper config file when adding the "
},
{
"path": "doc/command_ref.md",
"chars": 9410,
"preview": "# KTCC - Command Reference\n\n ##    Bas"
},
{
"path": "install.sh",
"chars": 1249,
"preview": "#!/bin/bash\n# Constants\nEXTENSION_NAME=\"klipper_toolchanger\"\n\n# Force script to exit if an error occurs\nset -e\n\n# Find S"
},
{
"path": "klipper_macros/G10.cfg",
"chars": 91,
"preview": "[gcode_macro G10]\r\ndescription: See M568. Passtrough to M568.\r\ngcode:\r\n M568 {rawparams}\r\n"
},
{
"path": "klipper_macros/M104.cfg",
"chars": 773,
"preview": "[gcode_macro M104]\r\nrename_existing: M104.1\r\ndescription: [T<index>] [S<temperature>]\r\n Set tool temperature.\r\n T= Too"
},
{
"path": "klipper_macros/M106.cfg",
"chars": 893,
"preview": "[gcode_macro M106]\r\nvariable_fan_speed: 0\r\ndescription: Snnn Pnnn\r\n Set fan speed. A KTCC tool must be configured for t"
},
{
"path": "klipper_macros/M107.cfg",
"chars": 352,
"preview": "[gcode_macro M107]\r\ndescription: Pnnn\r\n Turn off fan.\r\n P = Tool (optional and defaults to the currently selected tool"
},
{
"path": "klipper_macros/M109.cfg",
"chars": 1702,
"preview": "[gcode_macro M109]\r\nrename_existing: M109.1\r\ndescription: T<index> P<index> H<index> S<temperature> W<Tolerance>\r\n Wait"
},
{
"path": "klipper_macros/M116.cfg",
"chars": 544,
"preview": "[gcode_macro M116]\r\ndescription: T<index> P<index> H<index> S<temperature> W<Tolerance>\r\n Alias for M109.\r\n Waits for "
},
{
"path": "klipper_macros/M204.cfg",
"chars": 700,
"preview": "[gcode_macro M204]\r\nrename_existing: M204.1\r\ndescription: Snnn / Pnnn Tnnn\r\n Set acceleration either S or P and T must "
},
{
"path": "klipper_macros/M566.cfg",
"chars": 743,
"preview": "[gcode_macro M566]\ndescription: Xnnn Ynnn\n Set Square Corner Velocity in RRF style.\n Only the lower of required X or Y"
},
{
"path": "klipper_macros/M568.cfg",
"chars": 2571,
"preview": "[gcode_macro M568]\r\ndescription: Pnnn Tnnn Rnnn Snnn An Nnnn Mnnn\r\n Set tool temperature.\r\n P= Tool number, optional. "
},
{
"path": "klipper_macros/readme.md",
"chars": 4024,
"preview": "# Required and Optional G-code macros\r\n\r\nThe required macros change how Klipper uses those commands to make use of the t"
},
{
"path": "ktcclog.py",
"chars": 36923,
"preview": "# KTCC - Klipper Tool Changer Code\r\n# Log and statistics module\r\n#\r\n# Copyright (C) 2023 Andrei Ignat <andrei@ignat.se>"
},
{
"path": "tool.py",
"chars": 44380,
"preview": "# KTCC - Klipper Tool Changer Code\r\n# Tool module, for each tool.\r\n#\r\n# Copyright (C) 2023 Andrei Ignat <andrei@ignat.s"
},
{
"path": "toolgroup.py",
"chars": 3796,
"preview": "# KTCC - Klipper Tool Changer Code\r\n# Toolgroup module, used to group Tools and derived from Tool.\r\n#\r\n# Copyright (C) 2"
},
{
"path": "toollock.py",
"chars": 34414,
"preview": "# KTCC - Klipper Tool Changer Code\r\n# Toollock and general Tool support\r\n#\r\n# Copyright (C) 2023 Andrei Ignat <andrei@i"
}
]
About this extraction
This page contains the full source code of the TypQxQ/Klipper_ToolChanger GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 35 files (240.6 KB), approximately 60.4k tokens, and a symbol index with 137 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.