Repository: vvuk/eddy-ng Branch: main Commit: 1ed056b15feb Files: 20 Total size: 258.4 KB Directory structure: gitextract_xnak314q/ ├── .beads/ │ └── issues.jsonl ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── .ruff.toml ├── LICENSE ├── README.md ├── __init__.py ├── eddy-ng/ │ ├── Kconfig │ ├── Makefile │ ├── printf.c │ ├── printf.h │ ├── printf_config.h │ ├── pyproject.toml │ └── sensor_ldc1612_ng.c ├── install.py ├── install.sh ├── klipper.patch ├── ldc1612_ng.py ├── probe_eddy_ng.py └── pyrightconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .beads/issues.jsonl ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: [vvuk] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: vvuk tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry polar: # Replace with a single Polar username buy_me_a_coffee: # Replace with a single Buy Me a Coffee username thanks_dev: # Replace with a single thanks.dev username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .gitignore ================================================ .idea/ .vscode/ .DS_Store *~ *.orig *.rej ================================================ FILE: .ruff.toml ================================================ line-length = 140 indent-width = 4 ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . ================================================ FILE: README.md ================================================ # eddy-ng > ***Note: October 2025 -- life has gotten quite busy lately, so I've been much slower to respond to issues and make updates. Apologies, will get back to it soon!*** eddy-ng improves the Eddy current probe support in Klipper to add accurate Z-offset setting by physically making contact with the build surface. These probes are very accurate, but suffer from drifts due to changes in conductivity in the target surface as well as changes in coil parameters as temperatures change. Instead of doing temperature compensation (which is guesswork at best), eddy-ng takes a more physical approach: 1. Calibration is performed at any temperature (cold). 2. Z-homing via the sensor happens using this calibration, regardless of current temperatures. This is a "coarse" Z-home -- it is not accurate enough for printing, but is sufficient for homing, gantry leveling, and other preparation. 3. A precise Z-offset is taken with a "tap" just before printing, with the bed at print temps and the nozzle warm (but not hot -- you don't want filament drooling or damage to your build plate). 4. At the same time as the tap, the difference between the actual height (now known after the tap) and what the sensor reads at that height is saved. This offset then gets taken into account when doing a bed mesh, because it indicates the delta (due to temperatures) between what height the sensor thinks it is vs. where it actually is. This is a standalone `eddy-ng` repository, intended to be integrated into your own Klipper installation. ## Support Questions? Come ask on the Sovol 3D Printers Discord at `https://discord.gg/Zg45rA52G7` in the eddy-ng forum. (Nothing Sovol-specific in `eddy-ng`, just where all this work started! You can also find the server via the Discover tab in Discord, then Sovol 3D Printers) You can also file issues in [this `eddy-ng` github repo](https://github.com/vvuk/eddy-ng/issues). ## Installation 1. Clone this repository: ``` cd ~ git clone https://github.com/vvuk/eddy-ng ``` 2. Run the install script: ``` cd ~/eddy-ng ./install.sh ``` (If your klipper isn't installed in `~/klipper`, provide the path as the first argument, i.e. `./install.sh ~/my-klipper`.) 3. Follow the rest of the full `eddy-ng` setup instructions that are [available in the wiki](https://github.com/vvuk/eddy-ng/wiki). ## Updating Run a `git pull` and then run `./install.sh` again: ``` cd ~/eddy-ng git pull ./install.sh ``` ================================================ FILE: __init__.py ================================================ from klippy.configfile import ConfigWrapper from .probe_eddy_ng import ProbeEddy def load_config_prefix(config: ConfigWrapper): return ProbeEddy(config) ================================================ FILE: eddy-ng/Kconfig ================================================ config WANT_EDDY_NG bool "Include eddy-ng ldc1612 support" config WANT_EDDY_NG_DEBUG bool "Enable verbose eddy-ng logging" depends on WANT_EDDY_NG ================================================ FILE: eddy-ng/Makefile ================================================ dirs-y += src/extras/eddy-ng src-$(CONFIG_WANT_EDDY_NG) += extras/eddy-ng/sensor_ldc1612_ng.c src-$(CONFIG_WANT_EDDY_NG_DEBUG) += extras/eddy-ng/printf.c ================================================ FILE: eddy-ng/printf.c ================================================ /////////////////////////////////////////////////////////////////////////////// // \author (c) Marco Paland (info@paland.com) // 2014-2019, PALANDesign Hannover, Germany // // \license The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on // embedded systems with a very limited resources. These routines are thread // safe and reentrant! // Use this instead of the bloated standard/newlib printf cause these use // malloc for printf (and may not be thread safe). // /////////////////////////////////////////////////////////////////////////////// #include #include #include "printf.h" // define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the // printf_config.h header file // default: undefined #ifdef PRINTF_INCLUDE_CONFIG_H #include "printf_config.h" #endif // 'ntoa' conversion buffer size, this must be big enough to hold one converted // numeric number including padded zeros (dynamically created on stack) // default: 32 byte #ifndef PRINTF_NTOA_BUFFER_SIZE #define PRINTF_NTOA_BUFFER_SIZE 32U #endif // 'ftoa' conversion buffer size, this must be big enough to hold one converted // float number including padded zeros (dynamically created on stack) // default: 32 byte #ifndef PRINTF_FTOA_BUFFER_SIZE #define PRINTF_FTOA_BUFFER_SIZE 32U #endif // support for the floating point type (%f) // default: activated #ifndef PRINTF_DISABLE_SUPPORT_FLOAT #define PRINTF_SUPPORT_FLOAT #endif // support for exponential floating point notation (%e/%g) // default: activated #ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL #define PRINTF_SUPPORT_EXPONENTIAL #endif // define the default floating point precision // default: 6 digits #ifndef PRINTF_DEFAULT_FLOAT_PRECISION #define PRINTF_DEFAULT_FLOAT_PRECISION 6U #endif // define the largest float suitable to print with %f // default: 1e9 #ifndef PRINTF_MAX_FLOAT #define PRINTF_MAX_FLOAT 1e9 #endif // support for the long long types (%llu or %p) // default: activated #ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG #define PRINTF_SUPPORT_LONG_LONG #endif // support for the ptrdiff_t type (%t) // ptrdiff_t is normally defined in as long or long long type // default: activated #ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T #define PRINTF_SUPPORT_PTRDIFF_T #endif /////////////////////////////////////////////////////////////////////////////// // internal flag definitions #define FLAGS_ZEROPAD (1U << 0U) #define FLAGS_LEFT (1U << 1U) #define FLAGS_PLUS (1U << 2U) #define FLAGS_SPACE (1U << 3U) #define FLAGS_HASH (1U << 4U) #define FLAGS_UPPERCASE (1U << 5U) #define FLAGS_CHAR (1U << 6U) #define FLAGS_SHORT (1U << 7U) #define FLAGS_LONG (1U << 8U) #define FLAGS_LONG_LONG (1U << 9U) #define FLAGS_PRECISION (1U << 10U) #define FLAGS_ADAPT_EXP (1U << 11U) // import float.h for DBL_MAX #if defined(PRINTF_SUPPORT_FLOAT) #include #endif // output function type typedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen); // wrapper (used as buffer) for output function type typedef struct { void (*fct)(char character, void* arg); void* arg; } out_fct_wrap_type; // internal buffer output static inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen) { if (idx < maxlen) { ((char*)buffer)[idx] = character; } } // internal null output static inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen) { (void)character; (void)buffer; (void)idx; (void)maxlen; } // internal _putchar wrapper static inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen) { (void)buffer; (void)idx; (void)maxlen; if (character) { _putchar(character); } } // internal output function wrapper static inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen) { (void)idx; (void)maxlen; if (character) { // buffer is the output fct pointer ((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg); } } // internal secure strlen // \return The length of the string (excluding the terminating 0) limited by 'maxsize' static inline unsigned int _strnlen_s(const char* str, size_t maxsize) { const char* s; for (s = str; *s && maxsize--; ++s); return (unsigned int)(s - str); } // internal test if char is a digit (0-9) // \return true if char is a digit static inline bool _is_digit(char ch) { return (ch >= '0') && (ch <= '9'); } // internal ASCII string to unsigned int conversion static unsigned int _atoi(const char** str) { unsigned int i = 0U; while (_is_digit(**str)) { i = i * 10U + (unsigned int)(*((*str)++) - '0'); } return i; } // output the specified string in reverse, taking care of any zero-padding static size_t _out_rev(out_fct_type out, char* buffer, size_t idx, size_t maxlen, const char* buf, size_t len, unsigned int width, unsigned int flags) { const size_t start_idx = idx; // pad spaces up to given width if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) { for (size_t i = len; i < width; i++) { out(' ', buffer, idx++, maxlen); } } // reverse string while (len) { out(buf[--len], buffer, idx++, maxlen); } // append pad spaces up to given width if (flags & FLAGS_LEFT) { while (idx - start_idx < width) { out(' ', buffer, idx++, maxlen); } } return idx; } // internal itoa format static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags) { // pad leading zeros if (!(flags & FLAGS_LEFT)) { if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { width--; } while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) { buf[len++] = '0'; } while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) { buf[len++] = '0'; } } // handle hash if (flags & FLAGS_HASH) { if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) { len--; if (len && (base == 16U)) { len--; } } if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { buf[len++] = 'x'; } else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { buf[len++] = 'X'; } else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) { buf[len++] = 'b'; } if (len < PRINTF_NTOA_BUFFER_SIZE) { buf[len++] = '0'; } } if (len < PRINTF_NTOA_BUFFER_SIZE) { if (negative) { buf[len++] = '-'; } else if (flags & FLAGS_PLUS) { buf[len++] = '+'; // ignore the space if the '+' exists } else if (flags & FLAGS_SPACE) { buf[len++] = ' '; } } return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); } // internal itoa for 'long' type static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, unsigned long base, unsigned int prec, unsigned int width, unsigned int flags) { char buf[PRINTF_NTOA_BUFFER_SIZE]; size_t len = 0U; // no hash for 0 values if (!value) { flags &= ~FLAGS_HASH; } // write if precision != 0 and value is != 0 if (!(flags & FLAGS_PRECISION) || value) { do { const char digit = (char)(value % base); buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; value /= base; } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); } return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); } // internal itoa for 'long long' type #if defined(PRINTF_SUPPORT_LONG_LONG) static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags) { char buf[PRINTF_NTOA_BUFFER_SIZE]; size_t len = 0U; // no hash for 0 values if (!value) { flags &= ~FLAGS_HASH; } // write if precision != 0 and value is != 0 if (!(flags & FLAGS_PRECISION) || value) { do { const char digit = (char)(value % base); buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; value /= base; } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); } return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); } #endif // PRINTF_SUPPORT_LONG_LONG #if defined(PRINTF_SUPPORT_FLOAT) #if defined(PRINTF_SUPPORT_EXPONENTIAL) // forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags); #endif // internal ftoa for fixed decimal floating point static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) { char buf[PRINTF_FTOA_BUFFER_SIZE]; size_t len = 0U; double diff = 0.0; // powers of 10 static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; // test for special values if (value != value) return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags); if (value < -DBL_MAX) return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags); if (value > DBL_MAX) return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags); // test for very large values // standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) { #if defined(PRINTF_SUPPORT_EXPONENTIAL) return _etoa(out, buffer, idx, maxlen, value, prec, width, flags); #else return 0U; #endif } // test for negative bool negative = false; if (value < 0) { negative = true; value = 0 - value; } // set default precision, if not set explicitly if (!(flags & FLAGS_PRECISION)) { prec = PRINTF_DEFAULT_FLOAT_PRECISION; } // limit precision to 9, cause a prec >= 10 can lead to overflow errors while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) { buf[len++] = '0'; prec--; } int whole = (int)value; double tmp = (value - whole) * pow10[prec]; unsigned long frac = (unsigned long)tmp; diff = tmp - frac; if (diff > 0.5) { ++frac; // handle rollover, e.g. case 0.99 with prec 1 is 1.0 if (frac >= pow10[prec]) { frac = 0; ++whole; } } else if (diff < 0.5) { } else if ((frac == 0U) || (frac & 1U)) { // if halfway, round up if odd OR if last digit is 0 ++frac; } if (prec == 0U) { diff = value - (double)whole; if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) { // exactly 0.5 and ODD, then round up // 1.5 -> 2, but 2.5 -> 2 ++whole; } } else { unsigned int count = prec; // now do fractional part, as an unsigned number while (len < PRINTF_FTOA_BUFFER_SIZE) { --count; buf[len++] = (char)(48U + (frac % 10U)); if (!(frac /= 10U)) { break; } } // add extra 0s while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) { buf[len++] = '0'; } if (len < PRINTF_FTOA_BUFFER_SIZE) { // add decimal buf[len++] = '.'; } } // do whole part, number is reversed while (len < PRINTF_FTOA_BUFFER_SIZE) { buf[len++] = (char)(48 + (whole % 10)); if (!(whole /= 10)) { break; } } // pad leading zeros if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) { if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { width--; } while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) { buf[len++] = '0'; } } if (len < PRINTF_FTOA_BUFFER_SIZE) { if (negative) { buf[len++] = '-'; } else if (flags & FLAGS_PLUS) { buf[len++] = '+'; // ignore the space if the '+' exists } else if (flags & FLAGS_SPACE) { buf[len++] = ' '; } } return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); } #if defined(PRINTF_SUPPORT_EXPONENTIAL) // internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) { // check for NaN and special values if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) { return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags); } // determine the sign const bool negative = value < 0; if (negative) { value = -value; } // default precision if (!(flags & FLAGS_PRECISION)) { prec = PRINTF_DEFAULT_FLOAT_PRECISION; } // determine the decimal exponent // based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c) union { uint64_t U; double F; } conv; conv.F = value; int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2 conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2) // now approximate log10 from the log2 integer part and an expansion of ln around 1.5 int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168); // now we want to compute 10^expval but we want to be sure it won't overflow exp2 = (int)(expval * 3.321928094887362 + 0.5); const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453; const double z2 = z * z; conv.U = (uint64_t)(exp2 + 1023) << 52U; // compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14))))); // correct for rounding errors if (value < conv.F) { expval--; conv.F /= 10; } // the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U; // in "%g" mode, "prec" is the number of *significant figures* not decimals if (flags & FLAGS_ADAPT_EXP) { // do we want to fall-back to "%f" mode? if ((value >= 1e-4) && (value < 1e6)) { if ((int)prec > expval) { prec = (unsigned)((int)prec - expval - 1); } else { prec = 0; } flags |= FLAGS_PRECISION; // make sure _ftoa respects precision // no characters in exponent minwidth = 0U; expval = 0; } else { // we use one sigfig for the whole part if ((prec > 0) && (flags & FLAGS_PRECISION)) { --prec; } } } // will everything fit? unsigned int fwidth = width; if (width > minwidth) { // we didn't fall-back so subtract the characters required for the exponent fwidth -= minwidth; } else { // not enough characters, so go back to default sizing fwidth = 0U; } if ((flags & FLAGS_LEFT) && minwidth) { // if we're padding on the right, DON'T pad the floating part fwidth = 0U; } // rescale the float value if (expval) { value /= conv.F; } // output the floating part const size_t start_idx = idx; idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP); // output the exponent part if (minwidth) { // output the exponential symbol out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen); // output the exponent value idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS); // might need to right-pad spaces if (flags & FLAGS_LEFT) { while (idx - start_idx < width) out(' ', buffer, idx++, maxlen); } } return idx; } #endif // PRINTF_SUPPORT_EXPONENTIAL #endif // PRINTF_SUPPORT_FLOAT // internal vsnprintf static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va) { unsigned int flags, width, precision, n; size_t idx = 0U; if (!buffer) { // use null output function out = _out_null; } while (*format) { // format specifier? %[flags][width][.precision][length] if (*format != '%') { // no out(*format, buffer, idx++, maxlen); format++; continue; } else { // yes, evaluate it format++; } // evaluate flags flags = 0U; do { switch (*format) { case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break; case '-': flags |= FLAGS_LEFT; format++; n = 1U; break; case '+': flags |= FLAGS_PLUS; format++; n = 1U; break; case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break; case '#': flags |= FLAGS_HASH; format++; n = 1U; break; default : n = 0U; break; } } while (n); // evaluate width field width = 0U; if (_is_digit(*format)) { width = _atoi(&format); } else if (*format == '*') { const int w = va_arg(va, int); if (w < 0) { flags |= FLAGS_LEFT; // reverse padding width = (unsigned int)-w; } else { width = (unsigned int)w; } format++; } // evaluate precision field precision = 0U; if (*format == '.') { flags |= FLAGS_PRECISION; format++; if (_is_digit(*format)) { precision = _atoi(&format); } else if (*format == '*') { const int prec = (int)va_arg(va, int); precision = prec > 0 ? (unsigned int)prec : 0U; format++; } } // evaluate length field switch (*format) { case 'l' : flags |= FLAGS_LONG; format++; if (*format == 'l') { flags |= FLAGS_LONG_LONG; format++; } break; case 'h' : flags |= FLAGS_SHORT; format++; if (*format == 'h') { flags |= FLAGS_CHAR; format++; } break; #if defined(PRINTF_SUPPORT_PTRDIFF_T) case 't' : flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); format++; break; #endif case 'j' : flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); format++; break; case 'z' : flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); format++; break; default : break; } // evaluate specifier switch (*format) { case 'd' : case 'i' : case 'u' : case 'x' : case 'X' : case 'o' : case 'b' : { // set the base unsigned int base; if (*format == 'x' || *format == 'X') { base = 16U; } else if (*format == 'o') { base = 8U; } else if (*format == 'b') { base = 2U; } else { base = 10U; flags &= ~FLAGS_HASH; // no hash for dec format } // uppercase if (*format == 'X') { flags |= FLAGS_UPPERCASE; } // no plus or space flag for u, x, X, o, b if ((*format != 'i') && (*format != 'd')) { flags &= ~(FLAGS_PLUS | FLAGS_SPACE); } // ignore '0' flag when precision is given if (flags & FLAGS_PRECISION) { flags &= ~FLAGS_ZEROPAD; } // convert the integer if ((*format == 'i') || (*format == 'd')) { // signed if (flags & FLAGS_LONG_LONG) { #if defined(PRINTF_SUPPORT_LONG_LONG) const long long value = va_arg(va, long long); idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); #endif } else if (flags & FLAGS_LONG) { const long value = va_arg(va, long); idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); } else { const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int); idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); } } else { // unsigned if (flags & FLAGS_LONG_LONG) { #if defined(PRINTF_SUPPORT_LONG_LONG) idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags); #endif } else if (flags & FLAGS_LONG) { idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags); } else { const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : va_arg(va, unsigned int); idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags); } } format++; break; } #if defined(PRINTF_SUPPORT_FLOAT) case 'f' : case 'F' : if (*format == 'F') flags |= FLAGS_UPPERCASE; idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); format++; break; #if defined(PRINTF_SUPPORT_EXPONENTIAL) case 'e': case 'E': case 'g': case 'G': if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP; if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE; idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); format++; break; #endif // PRINTF_SUPPORT_EXPONENTIAL #endif // PRINTF_SUPPORT_FLOAT case 'c' : { unsigned int l = 1U; // pre padding if (!(flags & FLAGS_LEFT)) { while (l++ < width) { out(' ', buffer, idx++, maxlen); } } // char output out((char)va_arg(va, int), buffer, idx++, maxlen); // post padding if (flags & FLAGS_LEFT) { while (l++ < width) { out(' ', buffer, idx++, maxlen); } } format++; break; } case 's' : { const char* p = va_arg(va, char*); unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1); // pre padding if (flags & FLAGS_PRECISION) { l = (l < precision ? l : precision); } if (!(flags & FLAGS_LEFT)) { while (l++ < width) { out(' ', buffer, idx++, maxlen); } } // string output while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) { out(*(p++), buffer, idx++, maxlen); } // post padding if (flags & FLAGS_LEFT) { while (l++ < width) { out(' ', buffer, idx++, maxlen); } } format++; break; } case 'p' : { width = sizeof(void*) * 2U; flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE; #if defined(PRINTF_SUPPORT_LONG_LONG) const bool is_ll = sizeof(uintptr_t) == sizeof(long long); if (is_ll) { idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags); } else { #endif idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags); #if defined(PRINTF_SUPPORT_LONG_LONG) } #endif format++; break; } case '%' : out('%', buffer, idx++, maxlen); format++; break; default : out(*format, buffer, idx++, maxlen); format++; break; } } // termination out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen); // return written chars without terminating \0 return (int)idx; } /////////////////////////////////////////////////////////////////////////////// int printf_(const char* format, ...) { va_list va; va_start(va, format); char buffer[1]; const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va); va_end(va); return ret; } int sprintf_(char* buffer, const char* format, ...) { va_list va; va_start(va, format); const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va); va_end(va); return ret; } int snprintf_(char* buffer, size_t count, const char* format, ...) { va_list va; va_start(va, format); const int ret = _vsnprintf(_out_buffer, buffer, count, format, va); va_end(va); return ret; } int vprintf_(const char* format, va_list va) { char buffer[1]; return _vsnprintf(_out_char, buffer, (size_t)-1, format, va); } int vsnprintf_(char* buffer, size_t count, const char* format, va_list va) { return _vsnprintf(_out_buffer, buffer, count, format, va); } int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...) { va_list va; va_start(va, format); const out_fct_wrap_type out_fct_wrap = { out, arg }; const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va); va_end(va); return ret; } ================================================ FILE: eddy-ng/printf.h ================================================ /////////////////////////////////////////////////////////////////////////////// // \author (c) Marco Paland (info@paland.com) // 2014-2019, PALANDesign Hannover, Germany // // \license The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // \brief Tiny printf, sprintf and snprintf implementation, optimized for speed on // embedded systems with a very limited resources. // Use this instead of bloated standard/newlib printf. // These routines are thread safe and reentrant. // /////////////////////////////////////////////////////////////////////////////// #ifndef _PRINTF_H_ #define _PRINTF_H_ #include #include #ifdef __cplusplus extern "C" { #endif /** * Output a character to a custom device like UART, used by the printf() function * This function is declared here only. You have to write your custom implementation somewhere * \param character Character to output */ void _putchar(char character); /** * Tiny printf implementation * You have to implement _putchar if you use printf() * To avoid conflicts with the regular printf() API it is overridden by macro defines * and internal underscore-appended functions like printf_() are used * \param format A string that specifies the format of the output * \return The number of characters that are written into the array, not counting the terminating null character */ #define printf printf_ int printf_(const char* format, ...); /** * Tiny sprintf implementation * Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD! * \param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output! * \param format A string that specifies the format of the output * \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character */ #define sprintf sprintf_ int sprintf_(char* buffer, const char* format, ...); /** * Tiny snprintf/vsnprintf implementation * \param buffer A pointer to the buffer where to store the formatted string * \param count The maximum number of characters to store in the buffer, including a terminating null character * \param format A string that specifies the format of the output * \param va A value identifying a variable arguments list * \return The number of characters that COULD have been written into the buffer, not counting the terminating * null character. A value equal or larger than count indicates truncation. Only when the returned value * is non-negative and less than count, the string has been completely written. */ #define snprintf snprintf_ #define vsnprintf vsnprintf_ int snprintf_(char* buffer, size_t count, const char* format, ...); int vsnprintf_(char* buffer, size_t count, const char* format, va_list va); /** * Tiny vprintf implementation * \param format A string that specifies the format of the output * \param va A value identifying a variable arguments list * \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character */ #define vprintf vprintf_ int vprintf_(const char* format, va_list va); /** * printf with output function * You may use this as dynamic alternative to printf() with its fixed _putchar() output * \param out An output function which takes one character and an argument pointer * \param arg An argument pointer for user data passed to output function * \param format A string that specifies the format of the output * \return The number of characters that are sent to the output function, not counting the terminating null character */ int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...); #ifdef __cplusplus } #endif #endif // _PRINTF_H_ ================================================ FILE: eddy-ng/printf_config.h ================================================ #ifndef PRINTF_CONFIG_H_ #define PRINTF_CONFIG_H_ #define PRINTF_DISABLE_SUPPORT_EXPONENTIAL #define PRINTF_DISABLE_SUPPORT_LONG_LONG #define PRINTF_DISABLE_SUPPORT_PTRDIFF_T #endif ================================================ FILE: eddy-ng/pyproject.toml ================================================ [project] name = "probe-eddy-ng" version = "0.1.0" description = "Add your description here" requires-python = ">=3.12" dependencies = [ "klippy>=0.0", "plotly>=6.0.1", "scipy>=1.15.2", ] [tool.pyright] executionEnvironments = [ { root = "~/proj/k/kalico", extraPaths = [ ] }, ] ================================================ FILE: eddy-ng/sensor_ldc1612_ng.c ================================================ // Support for eddy current sensor data from ldc1612 chip (v2) // // Copyright (C) 2023 Alan.Ma // Copyright (C) 2024 Kevin O'Connor // Copyright (C) 2025 Vladimir Vukicevic // // This file may be distributed under the terms of the GNU GPLv3 license. #include // memcpy #include #include "autoconf.h" #include "basecmd.h" // oid_alloc #include "board/irq.h" // irq_disable #include "board/misc.h" // timer_read_time #include "command.h" // DECL_COMMAND #include "i2ccmds.h" // i2cdev_oid_lookup #include "sched.h" // DECL_TASK #include "sensor_bulk.h" // sensor_bulk_report #include "trsync.h" // trsync_do_trigger #if !defined(LDC_DEBUG) #define LDC_DEBUG 0 #endif #if CONFIG_MACH_STM32F0 // For Cartographer #include "board/internal.h" #include "board/gpio.h" #define SUPPORT_CARTOGRAPHER 1 #else #define SUPPORT_CARTOGRAPHER 0 #endif #if LDC_DEBUG > 0 #include "printf.h" void dprint(const char *fmt, ...); #else #define dprint(...) do { } while (0) #endif enum { // There's a pending sample that needs to be read LDC_PENDING = 1<<0, // Use the intb pin to detect when a sample is ready // vs. just polling LDC_HAVE_INTB = 1<<1, }; // Number of bytes in each ldc1612 sample. Always 4. #define BYTES_PER_SAMPLE 4 // should match ldc1612_ng.py #define HOME_MODE_NONE 0 #define HOME_MODE_HOME 1 #define HOME_MODE_WMA 2 #define HOME_MODE_SOS 3 // should match probe_eddy.py #define REASON_ERROR_SENSOR 0 #define REASON_ERROR_PROBE_TOO_LOW 1 #define REASON_ERROR_TOO_EARLY 2 // should match ldc1612_ng.py #define PRODUCT_UNKNOWN 0 #define PRODUCT_BTT_EDDY 1 #define PRODUCT_CARTOGRAPHER 2 #define PRODUCT_MELLOW_FLY 3 #define PRODUCT_LDC1612_INTERNAL_CLK 4 // Chip registers #define REG_DATA0_MSB 0x00 #define REG_DATA0_LSB 0x01 #define REG_STATUS 0x18 // Error flags reported in samples: undeer range, over range, watchdog, amplitude #define SAMPLE_ERR(data) ((data) >> 28) #define SAMPLE_ERR_UR 0x8 #define SAMPLE_ERR_OR 0x4 #define SAMPLE_ERR_WD 0x2 #define SAMPLE_ERR_AE 0x1 // conversion under range #define STATUS_ERR_UR 0x2000 // conversion over range #define STATUS_ERR_OR 0x1000 // watchdog timeout #define STATUS_ERR_WD 0x0800 // amplitude high error #define STATUS_ERR_AHE 0x0400 // amplitude low error #define STATUS_ERR_ALE 0x0200 // Homing configuration #define FREQ_WINDOW_SIZE 16 #define WMA_D_WINDOW_SIZE 4 #define MAX_SOS_SECTIONS 4 struct sosfilter_sos { uint8_t num_sections; float sos[MAX_SOS_SECTIONS*6]; }; struct ldc1612_ng_homing_wma_tap { // the tap detection threshold: specifically, the total downward // change in the frequency derivative before we see a direction // reveral (the windowed moving average of the derivative of the wmd // to be exact) int32_t tap_threshold; // number of samples to ignore for detection (to avoid spikes before // we fill buffers) uint8_t init_sample_count; // frequencies are always positive, as is their average // the derivative however is signed uint32_t freq_buffer[FREQ_WINDOW_SIZE]; int32_t wma_d_buf[WMA_D_WINDOW_SIZE]; // current index in freq/deriv buffers uint8_t freq_i; uint8_t wma_d_i; uint32_t wma; // last computed weighted moving average int32_t wma_d_avg; // last computed wma derivative average // the wema_d_avg at the start int32_t tap_start_value; }; struct ldc1612_ng_homing_sos_tap { float state[MAX_SOS_SECTIONS*4]; float tap_threshold; float frequency_offset; float tap_start_value; float last_value; }; struct ldc1612_ng_homing { uint8_t mode; // frequency we must pass through to have a valid home/tap uint32_t safe_start_freq; // and it must happen after this time uint32_t safe_start_time; // the frequency to trigger on for homing, or // the second threshold before we start looking for a tap uint32_t homing_trigger_freq; // What time we fire with the trigger -- either the time homing // triggered, or the computed time for the tap (which will be // earlier than when the tap was detected). uint32_t trigger_time; // If it was a tap, the start of tap detection uint32_t tap_start_time; // Number of errors we've seen in a row uint8_t error_count; // Number we're allowed to see, from home setup uint8_t error_threshold; // The final error that caused an abort uint32_t error; union { struct ldc1612_ng_homing_wma_tap wma_tap; struct ldc1612_ng_homing_sos_tap sos_tap; }; }; struct ldc1612_ng { struct timer timer; struct i2cdev_s *i2c; struct sensor_bulk sb; struct gpio_in intb_pin; uint8_t product; float sensor_cvt; uint32_t rest_ticks; uint8_t flags; uint16_t last_status; uint32_t last_read_value; // Samples per second (configurable) uint32_t data_rate; // homing triggers struct trsync *ts; uint8_t success_reason; uint8_t other_reason_base; // active sosfilter struct sosfilter_sos sos_filter; // homing state struct ldc1612_ng_homing homing; #if SUPPORT_CARTOGRAPHER struct gpio_out led_gpio; #endif }; void command_config_ldc1612_ng(uint32_t *args); static void read_reg(struct ldc1612_ng* ld, uint8_t reg, uint8_t* res); static uint16_t read_reg_status(struct ldc1612_ng* ld); static uint_fast8_t ldc1612_ng_timer_event(struct timer* timer); static void ldc1612_ng_update(struct ldc1612_ng* ld, uint8_t oid); static void check_homing(struct ldc1612_ng* ld, uint32_t data, uint32_t time); static void check_wma_tap(struct ldc1612_ng* ld, uint32_t data, uint32_t time); static void check_sos_tap(struct ldc1612_ng* ld, uint32_t data, uint32_t time); // // Core sample timers and loop // static struct task_wake ldc1612_ng_wake; static int check_intb_asserted(struct ldc1612_ng *ld) { return !gpio_in_read(ld->intb_pin); } void ldc1612_ng_task(void) { if (!sched_check_wake(&ldc1612_ng_wake)) return; uint8_t oid; struct ldc1612_ng *ld; foreach_oid(oid, ld, command_config_ldc1612_ng) { uint_fast8_t flags = ld->flags; if (!(flags & LDC_PENDING)) continue; ldc1612_ng_update(ld, oid); } } DECL_TASK(ldc1612_ng_task); uint_fast8_t ldc1612_ng_timer_event(struct timer *timer) { struct ldc1612_ng *ld = container_of(timer, struct ldc1612_ng, timer); if (ld->flags & LDC_PENDING) ld->sb.possible_overflows++; if (!(ld->flags & LDC_HAVE_INTB) || check_intb_asserted(ld)) { ld->flags |= LDC_PENDING; sched_wake_task(&ldc1612_ng_wake); } // reschedule to run in rest_ticks ld->timer.waketime += ld->rest_ticks; return SF_RESCHEDULE; } // Read a register on the ldc1612 void read_reg(struct ldc1612_ng *ld, uint8_t reg, uint8_t *res) { int ret = i2c_dev_read(ld->i2c, sizeof(reg), ®, 2, res); i2c_shutdown_on_err(ret); } // Read the status register on the ldc1612 uint16_t read_reg_status(struct ldc1612_ng *ld) { uint8_t data_status[2]; read_reg(ld, REG_STATUS, data_status); ld->last_status = (data_status[0] << 8) | data_status[1]; return ld->last_status; } // Notify trsync of event static void notify_trigger(struct ldc1612_ng *ld, uint32_t time, uint8_t reason) { ld->homing.mode = 0; trsync_do_trigger(ld->ts, reason); dprint("ZZZ notify_trigger: %u at %u", reason, time); } void ldc1612_ng_shutdown(void) { // make sure we stop measurements on shutdown so we don't // spam host on startup uint8_t oid; struct ldc1612_ng *ld; foreach_oid(oid, ld, command_config_ldc1612_ng) { sched_del_timer(&ld->timer); ld->flags &= ~LDC_PENDING; ld->rest_ticks = 0; } } DECL_SHUTDOWN(ldc1612_ng_shutdown); static void config_ldc1612_ng(uint32_t oid, uint32_t i2c_oid, uint8_t product, int32_t intb_pin) { dprint("EDDYng cfg o=%u i=%u b=%d", oid, i2c_oid, intb_pin); struct ldc1612_ng *ld = oid_alloc(oid, command_config_ldc1612_ng, sizeof(*ld)); ld->timer.func = ldc1612_ng_timer_event; ld->i2c = i2cdev_oid_lookup(i2c_oid); if (intb_pin != -1) { ld->intb_pin = gpio_in_setup(intb_pin, 1); ld->flags = LDC_HAVE_INTB; } ld->product = product; switch (product) { case PRODUCT_UNKNOWN: case PRODUCT_BTT_EDDY: ld->sensor_cvt = 12000000.0f / (float)(1<<28); break; case PRODUCT_MELLOW_FLY: ld->sensor_cvt = 40000000.0f / (float)(1<<28); break; #if SUPPORT_CARTOGRAPHER case PRODUCT_CARTOGRAPHER: ld->sensor_cvt = 24000000.0f / (float)(1<<28); // This enables the ldc1612 (CS?) gpio_out_setup(GPIO('A', 15), 0); // The Cartographer hardware uses a timer in the STM32F0 // to generate a 24MHz reference clock for the ldc1612. // Uses a new _with_max setup here because otherwise we // can't actually get to 24MHz from 48MHz. This could be // configured from the python side but that requires // adding a bunch of new commands. gpio_pwm_setup_with_max(GPIO('B', 4), 1, 1, 2); // There's a LED -- do something with it in the future, // showing homing progress ld->led_gpio = gpio_out_setup(GPIO('B', 5), 1); gpio_out_write(ld->led_gpio, 1); // There's also a temp sensor on A4, but we can // pull that out on the python side. break; #endif case PRODUCT_LDC1612_INTERNAL_CLK: ld->sensor_cvt = 43400000.0f / (float)(1<<28); break; default: shutdown("ldc1612_ng: unknown product"); } } void command_config_ldc1612_ng(uint32_t *args) { uint32_t oid = args[0]; uint32_t i2c_oid = args[1]; uint8_t product = args[2]; config_ldc1612_ng(oid, i2c_oid, product, -1); } DECL_COMMAND(command_config_ldc1612_ng, "config_ldc1612_ng oid=%c i2c_oid=%c product=%i"); void command_config_ldc1612_ng_with_intb(uint32_t *args) { uint32_t oid = args[0]; uint32_t i2c_oid = args[1]; uint8_t product = args[2]; uint32_t intb_pin = args[3]; config_ldc1612_ng(oid, i2c_oid, product, intb_pin); } DECL_COMMAND(command_config_ldc1612_ng_with_intb, "config_ldc1612_ng_with_intb oid=%c i2c_oid=%c product=%i intb_pin=%c"); void command_query_ldc1612_ng_latched_status(uint32_t *args) { struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng); uint32_t status = ld->last_status; uint32_t lastval = ld->last_read_value; // If we're not actively running, then read the status and // value directly if (ld->rest_ticks == 0) { status = read_reg_status(ld); uint8_t d[4]; read_reg(ld, REG_DATA0_MSB, &d[0]); read_reg(ld, REG_DATA0_LSB, &d[2]); lastval = ((uint32_t)d[0] << 24) | ((uint32_t)d[1] << 16) | ((uint32_t)d[2] << 8) | ((uint32_t)d[3]); } sendf("ldc1612_ng_latched_status oid=%c status=%u lastval=%u" , args[0], status, lastval); } DECL_COMMAND(command_query_ldc1612_ng_latched_status, "query_ldc1612_ng_latched_status_v2 oid=%c"); // ^ this command name is also used as an API version of sorts void command_ldc1612_ng_start_stop(uint32_t *args) { struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng); sched_del_timer(&ld->timer); ld->flags &= ~LDC_PENDING; ld->rest_ticks = args[1]; if (ld->rest_ticks == 0) { // End measurements dprint("ZZZ stop"); return; } dprint("ZZZ start"); // Start new measurements query sensor_bulk_reset(&ld->sb); irq_disable(); ld->timer.waketime = timer_read_time() + ld->rest_ticks; sched_add_timer(&ld->timer); irq_enable(); } DECL_COMMAND(command_ldc1612_ng_start_stop, "ldc1612_ng_start_stop oid=%c rest_ticks=%u"); void command_ldc1612_ng_query_bulk_status(uint32_t *args) { struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng); if (ld->flags & LDC_HAVE_INTB) { // Check if a sample is pending in the chip via the intb line irq_disable(); uint32_t time = timer_read_time(); int p = check_intb_asserted(ld); irq_enable(); sensor_bulk_status(&ld->sb, args[0], time, 0, p ? BYTES_PER_SAMPLE : 0); } else { // Query sensor to see if a sample is pending uint32_t time1 = timer_read_time(); uint16_t status = read_reg_status(ld); uint32_t time2 = timer_read_time(); uint32_t fifo = status & 0x08 ? BYTES_PER_SAMPLE : 0; sensor_bulk_status(&ld->sb, args[0], time1, time2-time1, fifo); } } DECL_COMMAND(command_ldc1612_ng_query_bulk_status, "ldc1612_ng_query_bulk_status oid=%c"); #if defined(LDC_DEBUG) && LDC_DEBUG > 0 void dprint(const char *fmt, ...) { char buf[60]; va_list args; va_start(args, fmt); int len = vsnprintf(buf, sizeof(buf)-1, fmt, args); va_end(args); sendf("debug_print m=%*s", len, buf); } #endif // // Set up and start homing. This assumes the sensor has been started; // it will error otherwise. // void command_ldc1612_ng_setup_home(uint32_t *args) { struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng); struct ldc1612_ng_homing *lh = &ld->homing; uint32_t trsync_oid = args[1]; uint8_t trigger_reason = args[2]; uint8_t other_reason_base = args[3]; uint32_t trigger_freq = args[4]; uint32_t start_freq = args[5]; uint32_t start_time = args[6]; uint8_t mode = args[7]; int32_t tap_threshold = args[8]; uint8_t err_max = args[9]; if (trigger_freq == 0 || trsync_oid == 0) { dprint("ZZZ resetting homing/tapping"); ld->ts = NULL; lh->mode = 0; return; } if (ld->rest_ticks == 0) { notify_trigger(ld, 0, other_reason_base); dprint("ZZZ sensor not started!"); return; } if (lh->mode > 0) { notify_trigger(ld, 0, other_reason_base); dprint("ZZZ homing already set up!"); return; } // Clear the homing state before setting up memset(lh, 0, sizeof(*lh)); lh->safe_start_freq = start_freq; lh->safe_start_time = start_time; lh->homing_trigger_freq = trigger_freq; lh->error_threshold = err_max; ld->ts = trsync_oid_lookup(trsync_oid); ld->success_reason = trigger_reason; ld->other_reason_base = other_reason_base; lh->mode = mode; switch (mode) { case HOME_MODE_HOME: dprint("ZZZ setup home sf=%u tf=%u", start_freq, trigger_freq); break; case HOME_MODE_WMA: lh->wma_tap.tap_threshold = tap_threshold >> 16; lh->wma_tap.init_sample_count = FREQ_WINDOW_SIZE * 2; dprint("ZZZ setup wma sf=%u tf=%u tap=%u", start_freq, trigger_freq, tap_threshold); break; case HOME_MODE_SOS: lh->sos_tap.tap_threshold = tap_threshold / 65536.0f; dprint("ZZZ setup sos sf=%u tf=%u tap=%f", start_freq, trigger_freq, lh->sos_tap.tap_threshold); break; default: shutdown("bad homing mode"); } } DECL_COMMAND(command_ldc1612_ng_setup_home, "ldc1612_ng_setup_home oid=%c" " trsync_oid=%c trigger_reason=%c other_reason_base=%c" " trigger_freq=%u start_freq=%u start_time=%u" " mode=%c tap_threshold=%i err_max=%c"); // // Once homing has finished, call this to clear the homing state and // retrieve the tap end time and tap final threshold amount. // void command_ldc1612_ng_finish_home(uint32_t *args) { struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng); struct ldc1612_ng_homing *lh = &ld->homing; uint32_t trigger_time = lh->trigger_time; // note: same as homing_clock in parent struct uint32_t tap_start_time = lh->tap_start_time; uint32_t error = lh->error; ld->ts = NULL; lh->mode = 0; sendf("ldc1612_ng_finish_home_reply oid=%c trigger_clock=%u tap_start_clock=%u error=%u" , args[0], trigger_time, tap_start_time, error); dprint("ZZZ finish tap_s=%u trig_t=%u", tap_start_time, trigger_time); } DECL_COMMAND(command_ldc1612_ng_finish_home, "ldc1612_ng_finish_home oid=%c"); // Read a value from the chip if one is ready, put it in the bulk data buffer, // and do any processing if we're homing. void ldc1612_ng_update(struct ldc1612_ng *ld, uint8_t oid) { uint16_t status = read_reg_status(ld); irq_disable(); ld->flags &= ~LDC_PENDING; irq_enable(); if (!(status & 0x08)) // UNREADCONV1 return; uint32_t time = timer_read_time(); // Read coil0 frequency uint8_t *d = &ld->sb.data[ld->sb.data_count]; read_reg(ld, REG_DATA0_MSB, &d[0]); read_reg(ld, REG_DATA0_LSB, &d[2]); ld->sb.data_count += BYTES_PER_SAMPLE; uint32_t data = ((uint32_t)d[0] << 24) | ((uint32_t)d[1] << 16) | ((uint32_t)d[2] << 8) | ((uint32_t)d[3]); ld->last_read_value = data; switch (ld->homing.mode) { case HOME_MODE_HOME: check_homing(ld, data, time); break; case HOME_MODE_WMA: check_wma_tap(ld, data, time); break; case HOME_MODE_SOS: check_sos_tap(ld, data, time); break; } // Flush local buffer if needed if (ld->sb.data_count + BYTES_PER_SAMPLE > ARRAY_SIZE(ld->sb.data)) sensor_bulk_report(&ld->sb, oid); } static inline uint32_t windowed_moving_average_u32(uint32_t* buf, uint8_t buf_size, uint8_t start_i) { // TODO: We can avoid 64-bit integers here by just offseting // the input numbers to ensure that we can always add buf_size values // without overflow into an uint32_t. For frequencies, it should be safe // to subtract the safe_start_freq and just deal with offsets above that, // because ultimately we only care about the derivative. // But this 64-bit math is here for now to keep the logic simple // during development. uint64_t wma_sum = 0; for (uint8_t i = 0; i < buf_size; i++) { uint8_t j = (start_i + i) % buf_size; wma_sum += buf[j] * (i+1); } uint32_t freq_weight_sum = (buf_size * (buf_size + 1)) / 2; return (uint32_t)(wma_sum / freq_weight_sum); } static inline int32_t simple_average_i32(int32_t* buf, uint8_t buf_size) { // This assumes that the sum can fit in an i32. int32_t sum = 0; for (uint8_t i = 0; i < buf_size; i++) { sum += buf[i]; } return sum / buf_size; } static float sosfilter(float value, struct sosfilter_sos* filter, float* state) { const uint8_t num_sections = filter->num_sections; const float* sos = filter->sos; for (int k = 0; k < num_sections; k++) { float w1 = state[2*k]; float w2 = state[2*k+1]; float b0 = *sos++; //sos[6*k]; float b1 = *sos++; //sos[6*k+1]; float b2 = *sos++; //sos[6*k+2]; sos++; // a0 unused float a1 = *sos++; //sos[6*k+4]; float a2 = *sos++; //sos[6*k+5]; float w0 = value - a1 * w1 - a2 * w2; value = b0 * w0 + b1 * w1 + b2 * w2; state[2*k] = w0; state[2*k+1] = w1; } return value; } // Check whether the sample has error bits set, and decide what to do // if it does bool check_error(struct ldc1612_ng* ld, uint32_t data, uint32_t time) { struct ldc1612_ng_homing *lh = &ld->homing; if (!SAMPLE_ERR(data)) { lh->error_count = 0; return true; } uint8_t is_tap = lh->mode > 0; // Ignore amplitude too high errors for homing, // because this is generally the probe being very // far from the build plate. if (!is_tap && (ld->last_status & STATUS_ERR_AHE) != 0) { lh->error_count = 0; return false; } lh->error_count++; dprint("ZZZ err=%u t=%u s=%u cnt=%u", data, time, ld->last_status, lh->error_count); if (lh->error_count <= lh->error_threshold) return false; lh->error = data; // Sensor reports an issue - cancel homing notify_trigger(ld, 0, ld->other_reason_base + REASON_ERROR_SENSOR); return false; } // Check whether we've passed the safety thresholds in order for the // operation to proceed bool check_safe_start(struct ldc1612_ng* ld, uint32_t data, uint32_t time) { struct ldc1612_ng_homing *lh = &ld->homing; uint8_t is_tap = lh->mode > 0; if (lh->safe_start_freq == 0) return true; // We need to pass through this frequency threshold to be a valid dive. // We just use the simple data value here. if (data < lh->safe_start_freq) return false; // And we need to do it _after_ this time, to make sure we didn't // start below the threshold if (lh->safe_start_time != 0 && timer_is_before(time, lh->safe_start_time)) { dprint("ZZZ EARLY! time=%u < %u", time, lh->safe_start_time); notify_trigger(ld, 0, ld->other_reason_base + REASON_ERROR_TOO_EARLY); return false; } if (is_tap && lh->homing_trigger_freq != 0) { // If we're tapping, then make the homing trigger freq a second thershold. // These would typically be set to something like the 3.0mm freq for the first, // then the 2.0mm homing freq. lh->safe_start_freq = lh->homing_trigger_freq; lh->homing_trigger_freq = 0; return false; } dprint("ZZZ safe start"); // Ok, we've passed all the safety thresholds. Values from this point on // will be considered for homing/tapping lh->safe_start_freq = 0; return true; } // // Basic homing (simple threshold) // void check_homing(struct ldc1612_ng* ld, uint32_t data, uint32_t time) { struct ldc1612_ng_homing *lh = &ld->homing; if (!check_error(ld, data, time)) return; if (!check_safe_start(ld, data, time)) return; if (data > lh->homing_trigger_freq) { notify_trigger(ld, time, ld->success_reason); lh->trigger_time = time; dprint("ZZZ home t=%u f=%u", time, data); } } // // Tap detection using a windowed moving average of the frequency derivative // void check_wma_tap(struct ldc1612_ng* ld, uint32_t data, uint32_t time) { struct ldc1612_ng_homing *lh = &ld->homing; struct ldc1612_ng_homing_wma_tap *wma_tap = &lh->wma_tap; if (!check_error(ld, data, time)) return; if (!check_safe_start(ld, data, time)) return; // // Update the sensor averages and derivatives // // We use a windowed moving average for the frequencies. This seems to give a // better signal after staring at a jupyter notebook with plotly plots // for far too long. Because the values are always increasing as we probe, // WMA undershoots the true value by by a bit but it does a great job of // smoothing out the noise in the sensor. // // Because the sensor is always going to be used at the same ranges, // we could calibrate a fixed offset to apply to the frequency values (by // calculating the average offset between the true centered average vs. // the WMA to get a more accurate number. // // However, the actual frequency value itself is only used for coarse homing; // and because we're not doing any temperature calibration coarse homing // is never going to be super accurate anyway. // // Tap detection is done by looking at the derivative of this value only. // // TODO: the below can absolutely be made more efficient, but I'm // keeping it simple while things are dialed in. // Helpers to clean up the adds/mods/etc. to make the below more readable #define NEXT_FREQ_I(i) (((i) + 1) % FREQ_WINDOW_SIZE) #define NEXT_WMA_D_I(i) (((i) + 1) % WMA_D_WINDOW_SIZE) wma_tap->freq_buffer[wma_tap->freq_i] = data; wma_tap->freq_i = NEXT_FREQ_I(wma_tap->freq_i); uint32_t wma = windowed_moving_average_u32(wma_tap->freq_buffer, FREQ_WINDOW_SIZE, wma_tap->freq_i); int32_t wma_d = wma - wma_tap->wma; // A simple average of wma_d to smooth it out a bit. Without this, // we'll see some small spikes which will reset the accumulator; // I think this is due to the drip move. wma_tap->wma_d_buf[wma_tap->wma_d_i] = wma_d; wma_tap->wma_d_i = NEXT_WMA_D_I(wma_tap->wma_d_i); int32_t wma_d_avg = simple_average_i32(wma_tap->wma_d_buf, WMA_D_WINDOW_SIZE); int32_t last_wma_d_avg = wma_tap->wma_d_avg; wma_tap->wma = wma; wma_tap->wma_d_avg = wma_d_avg; if (wma_tap->init_sample_count) { wma_tap->init_sample_count--; return; } // The core tap threshold computation. If the derivative is // increasing, keep resetting the tap start until we hit a peak. if (wma_d_avg > last_wma_d_avg) { // derivative is increasing; reset the accumulator, // and reset the tap time lh->tap_start_time = time; wma_tap->tap_start_value = wma_d_avg; return; } if (wma_tap->tap_start_value - wma_d_avg >= wma_tap->tap_threshold) { // Note: we notify with the time the tap started, not the current time notify_trigger(ld, lh->tap_start_time, ld->success_reason); lh->trigger_time = time; dprint("ZZZ tap t=%u n=%u l=%u (f=%u)", lh->tap_start_time, time, wma_tap->tap_start_value - wma_d_avg, data); } } void check_sos_tap(struct ldc1612_ng* ld, uint32_t data, uint32_t time) { struct ldc1612_ng_homing *lh = &ld->homing; struct ldc1612_ng_homing_sos_tap *sos_tap = &lh->sos_tap; if (!check_error(ld, data, time)) return; float freq = data * ld->sensor_cvt; // We need to offset the frequencies by the first // one we feed to the filter so we don't get a crazy // response at the start. // if we haven't even hit the safe_start_freq if (lh->homing_trigger_freq != 0) { sos_tap->frequency_offset = freq; if (check_safe_start(ld, data, time)) shutdown("bug"); // this should never return true in here return; } float val = sosfilter(freq - sos_tap->frequency_offset, &ld->sos_filter, sos_tap->state); //dprint("%f,%f", freq, val); // this is the second threshold; but we want to feed the filter values // before this to avoid the initial impulse response if (!check_safe_start(ld, data, time)) return; // Note: == is explicitly excluded below. We don't want to // overwrite the "start" time (so >= won't work), and // it can't make a difference to the last diff check if (val < sos_tap->last_value) { float diff = sos_tap->tap_start_value - val; if (diff >= sos_tap->tap_threshold) { lh->trigger_time = time; notify_trigger(ld, time, ld->success_reason); dprint("ZZZ tap st=%u tt=%u l=%f (f=%f)", lh->tap_start_time, time, sos_tap->tap_start_value - val, freq); return; } } else if (val > sos_tap->last_value) { // This keeps getting updated even on the rise, so that // the values are correct for the start of the tap (i.e. the peak) // once we realize the value is falling. sos_tap->tap_start_value = val; lh->tap_start_time = time; } sos_tap->last_value = val; } void command_ldc1612_ng_set_sos_section(uint32_t *args) { struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng); uint8_t section = args[1]; uint8_t values_len = args[2]; if (values_len == 0) { // reset filter ld->sos_filter.num_sections = 0; return; } uint8_t* data = command_decode_ptr(args[3]); if (values_len != 4*6) { shutdown("ldc1612_ng: wrong sos section length"); } // these commands need to come in order of increasing section ld->sos_filter.num_sections = section + 1; memcpy(&ld->sos_filter.sos[section*6], data, values_len); } DECL_COMMAND(command_ldc1612_ng_set_sos_section, "ldc1612_ng_set_sos_section oid=%c section=%c values=%*s"); ================================================ FILE: install.py ================================================ #!/usr/bin/env python3 import os import sys import argparse import shutil from pathlib import Path IS_MAC = os.path.isdir("/System/Library") SED_IN_PLACE_ARG = "-i ''" if IS_MAC else "-i" FILES_TO_COPY = { "eddy-ng/sensor_ldc1612_ng.c": "src", "probe_eddy_ng.py": "klippy/extras", "ldc1612_ng.py": "klippy/extras" } def get_script_dir(): return os.path.dirname(os.path.realpath(__file__)) def uninstall_klipper(target_dir: str): for src_file, dest_dir in FILES_TO_COPY.items(): dest_path = os.path.join(target_dir, dest_dir) dest_file = os.path.join(dest_path, os.path.basename(src_file)) if os.path.islink(dest_file) or os.path.isfile(dest_file): print(f"Removing {dest_file}") os.remove(dest_file) else: print(f"File {dest_file} does not exist. Skipping.") print("Unpatching src/Makefile...") makefile_path = os.path.join(target_dir, "src/Makefile") os.system(f"sed {SED_IN_PLACE_ARG} 's, sensor_ldc1612_ng.c,,' '{makefile_path}'") print("Unpatching klippy/extras/bed-mesh.py...") bed_mesh_path = os.path.join(target_dir, "klippy/extras/bed_mesh.py") os.system( f"sed {SED_IN_PLACE_ARG} 's,\"eddy\" in probe_name #eddy-ng,probe_name.startswith(\"probe_eddy_current\"),' '{bed_mesh_path}'" ) return def install_kalico(target_dir: str, uninstall: bool, copy: bool): if not uninstall: print("Congrats, you're running Kalico!") print("================================") python_module_path = os.path.join(target_dir, "klippy/plugins/probe_eddy_ng") firmware_module_path = os.path.join(target_dir, "src/extras/eddy-ng") old_module_path = os.path.join(target_dir, "klippy/extras/probe_eddy_ng.py") if os.path.islink(old_module_path) or os.path.isfile(old_module_path): print("Uninstalling old installation...") uninstall_klipper(target_dir) if os.path.exists(python_module_path) or os.path.islink(python_module_path): if not os.path.islink(python_module_path): print(f"{python_module_path} exists, but is not a symlink. Please remove it and try again.") sys.exit(1) os.unlink(python_module_path) if os.path.exists(firmware_module_path) or os.path.islink(firmware_module_path): if not os.path.islink(firmware_module_path): print(f"{firmware_module_path} exists, but is not a symlink. Please remove it and try again.") sys.exit(1) os.unlink(firmware_module_path) if uninstall: print("Removed firmware and plugin module links.") sys.exit(0) if copy: shutil.copytree(get_script_dir(), python_module_path) shutil.copytree(os.path.join(get_script_dir(), "eddy-ng"), firmware_module_path) else: os.symlink(get_script_dir(), python_module_path) os.symlink(os.path.join(get_script_dir(), "eddy-ng"), firmware_module_path) print("Installed links to firmware and plugin modules.") print("When rebuilding firmware, make sure to select eddy-ng") print("from the firmware extras in menuconfig.") print("(There's no need to run install again after eddy-ng updates.)") def install_klipper(target_dir: str, uninstall: bool, copy: bool): if uninstall: print("Uninstalling files...") uninstall_klipper(target_dir) return print("Installing files...") for src_file, dest_dir in FILES_TO_COPY.items(): src_path = os.path.join(get_script_dir(), src_file) dest_path = os.path.join(target_dir, dest_dir) dest_file = os.path.join(dest_path, os.path.basename(src_file)) if copy: print(f"Copying {src_file} to {dest_dir}/") shutil.copyfile(src_file, dest_file) else: link_path = os.path.relpath(os.path.realpath(src_path), dest_path) print(f"Linking {link_path} to {dest_dir}/") if os.path.islink(dest_file) or os.path.exists(dest_file): os.remove(dest_file) os.symlink(link_path, dest_file) print("Patching src/Makefile...") makefile_path = os.path.join(target_dir, "src/Makefile") os.system(f"sed {SED_IN_PLACE_ARG} 's,sensor_ldc1612.c$,sensor_ldc1612.c sensor_ldc1612_ng.c,' '{makefile_path}'") print("Patching klippy/extras/bed-mesh.py...") bed_mesh_path = os.path.join(target_dir, "klippy/extras/bed_mesh.py") os.system( f"sed {SED_IN_PLACE_ARG} 's,probe_name.startswith(\"probe_eddy_current\"),\"eddy\" in probe_name #eddy-ng,' '{bed_mesh_path}'" ) def main(): parser = argparse.ArgumentParser(description="Install or uninstall components.") parser.add_argument("-u", "--uninstall", action="store_true", help="Uninstall files") parser.add_argument("--copy", action="store_true", help="Copy files instead of linking") parser.add_argument("target_dir", nargs="?", help="Target directory") args = parser.parse_args() uninstall = args.uninstall copy = args.copy target_dir = args.target_dir # If no target directory provided, try defaults if not target_dir: home_dir = str(Path.home()) if os.path.isdir(os.path.join(home_dir, "klipper")): target_dir = os.path.join(home_dir, "klipper") elif os.path.isdir(os.path.join(home_dir, "kalico")): target_dir = os.path.join(home_dir, "kalico") else: print("Error: No target directory provided and no default directories found.") parser.print_help() sys.exit(1) if not os.path.isdir(target_dir): print(f"Error: Target directory '{target_dir}' does not exist.") sys.exit(1) if os.path.exists(os.path.join(target_dir, "klippy/extras/danger_options.py")): install_kalico(target_dir, uninstall, copy) else: install_klipper(target_dir, uninstall, copy) if __name__ == "__main__": main() ================================================ FILE: install.sh ================================================ #!/bin/bash exec python3 install.py $* ================================================ FILE: klipper.patch ================================================ diff --git src/Makefile src/Makefile index cfedc56f7..422e0179e 100644 --- a/src/Makefile +++ b/src/Makefile @@ -20,6 +20,6 @@ src-$(CONFIG_WANT_LIS2DW) += sensor_lis2dw.c src-$(CONFIG_WANT_MPU9250) += sensor_mpu9250.c src-$(CONFIG_WANT_HX71X) += sensor_hx71x.c src-$(CONFIG_WANT_ADS1220) += sensor_ads1220.c -src-$(CONFIG_WANT_LDC1612) += sensor_ldc1612.c +src-$(CONFIG_WANT_LDC1612) += sensor_ldc1612.c sensor_ldc1612_ng.c src-$(CONFIG_WANT_SENSOR_ANGLE) += sensor_angle.c src-$(CONFIG_NEED_SENSOR_BULK) += sensor_bulk.c ================================================ FILE: ldc1612_ng.py ================================================ # Support for reading frequency samples from ldc1612 (v2) # # Copyright (C) 2020-2024 Kevin O'Connor # Copyright (C) 2025 Vladimir Vukicevic # # This file may be distributed under the terms of the GNU GPLv3 license. import math import logging import struct from dataclasses import dataclass from typing import List, Optional try: from klippy.extras import bus, bulk_sensor from klippy.printer import Printer IS_KALICO = True except ImportError: from . import bus, bulk_sensor from klippy import Printer IS_KALICO = False MIN_MSG_TIME = 0.100 BATCH_UPDATES = 0.100 LDC1612_ADDR = 0x2A # TODO: configure these as part of calibration DEGLITCH_1_0MHZ = 0x01 DEGLITCH_3_3MHZ = 0x04 DEGLITCH_10MHZ = 0x05 DEGLITCH_33MHZ = 0x07 LDC1612_MANUF_ID = 0x5449 LDC1612_DEV_ID = 0x3055 REG_RCOUNT0 = 0x08 REG_OFFSET0 = 0x0C REG_SETTLECOUNT0 = 0x10 REG_CLOCK_DIVIDERS0 = 0x14 REG_ERROR_CONFIG = 0x19 REG_CONFIG = 0x1A REG_MUX_CONFIG = 0x1B REG_DRIVE_CURRENT0 = 0x1E REG_MANUFACTURER_ID = 0x7E REG_DEVICE_ID = 0x7F # Device product (match sensor_ldc1612_ng.c) PRODUCT_UNKNOWN = 0 PRODUCT_BTT_EDDY = 1 PRODUCT_CARTOGRAPHER = 2 PRODUCT_MELLOW_FLY = 3 PRODUCT_LDC1612_INTERNAL_CLK = 4 HOME_MODE_NONE = 0 HOME_MODE_HOME = 1 HOME_MODE_WMA = 2 HOME_MODE_SOS = 3 @dataclass class LDC1612_ng_value: status: int freqval: int freq: float @dataclass class LDC1612_ng_homing_result: trigger_time: float tap_start_time: float error: int # Interface class to LDC1612 mcu support class LDC1612_ng: def __init__(self, config): self.printer: Printer = config.get_printer() self._name = config.get_name().split()[-1] self._verbose = config.getboolean("debug", False) device_choices = { "ldc1612": PRODUCT_UNKNOWN, "btt_eddy": PRODUCT_BTT_EDDY, "cartographer": PRODUCT_CARTOGRAPHER, "mellow_fly": PRODUCT_MELLOW_FLY, "ldc1612_internal_clk": PRODUCT_LDC1612_INTERNAL_CLK, } self._device_product = config.getchoice("sensor_type", device_choices, PRODUCT_UNKNOWN) # Fin0 = Fsensor0 / FIN_DIVIDER0 # Fref0 = Fclk / FREF_DIVIDER0 if self._device_product == PRODUCT_CARTOGRAPHER: self._ldc_freq_clk = 24_000_000 self._ldc_fin_divider = 1 self._ldc_fref_divider = 1 self._ldc_settle_time = 0.0001706 self._default_drive_current = 26 elif self._device_product == PRODUCT_MELLOW_FLY: self._ldc_freq_clk = 40_000_000 self._ldc_fin_divider = 1 self._ldc_fref_divider = 2 self._ldc_settle_time = 0.00125 self._default_drive_current = 15 elif self._device_product == PRODUCT_LDC1612_INTERNAL_CLK: # A generic setup that usees internal LDC1612 clock # using LDC1612 internal typical clock frequency 43.4MHz self._ldc_freq_clk = 43_400_000 self._ldc_fin_divider = 1 self._ldc_fref_divider = 1 self._ldc_settle_time = 0.00125 self._default_drive_current = 15 else: # Generic/BTT Eddy using external 12MHz clock source self._ldc_freq_clk = 12_000_000 self._ldc_settle_time = 0.005 self._ldc_fin_divider = 1 self._ldc_fref_divider = 1 self._default_drive_current = 15 self._ldc_freq_ref = round(self._ldc_freq_clk / self._ldc_fref_divider) drive_current: int = config.getint("reg_drive_current", 0, minval=0, maxval=31) saved_drive_current: int = config.getint("saved_reg_drive_current", 0, minval=0, maxval=31) if drive_current == 0: drive_current = saved_drive_current if drive_current == 0: drive_current = self._default_drive_current self._drive_current = drive_current self._deglitch: str = config.get("ldc_deglitch", "default").lower() self._data_rate: int = config.getint("samples_per_second", 250, minval=50) self._ldc_settle_time = min(self._ldc_settle_time, 1.0 / self._data_rate) # Setup mcu sensor_ldc1612 bulk query code self._i2c = bus.MCU_I2C_from_config(config, default_addr=LDC1612_ADDR, default_speed=400000) self._mcu = mcu = self._i2c.get_mcu() self._oid = oid = mcu.create_oid() logging.info(f"LDC1612ng {self._name} oid: {oid} i2c_oid {self._i2c.get_oid()}") # params ending in "_pin" are magic and are a %s on this side, but %c on # the native side. There doesn't seem to be a way to pass "no pin". So we # need two separate config commands. if config.get("intb_pin", None) is not None: ppins = config.get_printer().lookup_object("pins") pin_params = ppins.lookup_pin(config.get("intb_pin")) if pin_params["chip"] != mcu: raise config.error("ldc1612 intb_pin must be on same mcu") mcu.add_config_cmd( "config_ldc1612_ng_with_intb oid=%d i2c_oid=%d product=%i intb_pin=%s" % ( oid, self._i2c.get_oid(), self._device_product, pin_params["pin"], ) ) else: mcu.add_config_cmd("config_ldc1612_ng oid=%d i2c_oid=%d product=%i" % (oid, self._i2c.get_oid(), self._device_product)) # Make sure the sensor is stopped on restart mcu.add_config_cmd( "ldc1612_ng_start_stop oid=%d rest_ticks=0" % (oid,), on_restart=True, ) mcu.register_config_callback(self._build_config) self._start_count = 0 self._chip_initialized = False # Bulk sample message reading chip_smooth = self._data_rate * BATCH_UPDATES * 2 self._ffreader = bulk_sensor.FixedFreqReader(mcu, chip_smooth, ">I") # Process messages in batches self._batch_bulk = bulk_sensor.BatchBulkHelper( self.printer, self._process_batch, self._start_measurements, self._finish_measurements, BATCH_UPDATES, ) hdr = ("time", "frequency", "z") self._batch_bulk.add_mux_endpoint("ldc1612_ng/dump_ldc1612", "sensor", self._name, {"header": hdr}) gcode = self.printer.lookup_object("gcode") gcode.register_mux_command( "LDC_NG_CALIBRATE_DRIVE_CURRENT", "CHIP", self._name, self.cmd_LDC_CALIBRATE, desc=self.cmd_LDC_CALIBRATE_help, ) gcode.register_mux_command( "LDC_NG_SET_DRIVE_CURRENT", "CHIP", self._name, self.cmd_LDC_SET_DC, desc=self.cmd_LDC_SET_DC_help, ) cmd_LDC_SET_DC_help = "Set LDC1612 DRIVE_CURRENT register (idrive value only)" def cmd_LDC_SET_DC(self, gcmd): drive_cur = gcmd.get_int("VAL", minval=0, maxval=31) self.set_drive_current(drive_cur) cmd_LDC_CALIBRATE_help = "Calibrate LDC1612 DRIVE_CURRENT register" def cmd_LDC_CALIBRATE(self, gcmd): is_in_progress = True def handle_batch(msg): return is_in_progress self.add_bulk_sensor_data_client(handle_batch) toolhead = self.printer.lookup_object("toolhead") toolhead.dwell(0.100) toolhead.wait_moves() old_config = self.read_reg(REG_CONFIG) if (self._device_product == PRODUCT_LDC1612_INTERNAL_CLK): self.set_reg(REG_CONFIG, 0x001) else: self.set_reg(REG_CONFIG, 0x001 | (1 << 9)) toolhead.wait_moves() toolhead.dwell(0.100) toolhead.wait_moves() reg_drive_current0 = self.read_reg(REG_DRIVE_CURRENT0) self.set_reg(REG_CONFIG, old_config) is_in_progress = False # Report found value to user drive_cur = (reg_drive_current0 >> 6) & 0x1F gcmd.respond_info( f"{self._name}: Estimated reg_drive_current: {drive_cur}\n" "Add this to your config as either reg_drive_current or tap_drive_current\n" "then restart." ) def _build_config(self): cmdqueue = self._i2c.get_command_queue() self._ldc1612_ng_start_stop_cmd = self._mcu.lookup_command("ldc1612_ng_start_stop oid=%c rest_ticks=%u", cq=cmdqueue) self._ffreader.setup_query_command("ldc1612_ng_query_bulk_status oid=%c", oid=self._oid, cq=cmdqueue) self._ldc1612_ng_latched_status_cmd = self._mcu.lookup_query_command( "query_ldc1612_ng_latched_status_v2 oid=%c", "ldc1612_ng_latched_status oid=%c status=%u lastval=%u", oid=self._oid, cq=cmdqueue, ) self._ldc1612_ng_setup_home_cmd = self._mcu.lookup_command( "ldc1612_ng_setup_home oid=%c" " trsync_oid=%c trigger_reason=%c other_reason_base=%c" " trigger_freq=%u start_freq=%u start_time=%u mode=%c tap_threshold=%i" " err_max=%c", cq=cmdqueue, ) self._ldc1612_ng_finish_home_cmd = self._mcu.lookup_query_command( "ldc1612_ng_finish_home oid=%c", "ldc1612_ng_finish_home_reply oid=%c trigger_clock=%u tap_start_clock=%u error=%u", oid=self._oid, cq=cmdqueue, ) self._ldc1612_ng_set_sos_section = self._mcu.lookup_command( "ldc1612_ng_set_sos_section oid=%c section=%c values=%*s", cq=cmdqueue, ) if hasattr(self._mcu, "register_serial_response"): # infuriating: these used to be able to be registered for optional # things (that the firmware never sends) #self._mcu.register_serial_response(self._handle_debug_print, "debug_print m=%*s") pass else: self._mcu.register_response(self._handle_debug_print, "debug_print") def _handle_debug_print(self, params): logging.info(params["m"]) def _clock32_to_print_time(self, clock) -> float: return self._mcu.clock_to_print_time(self._mcu.clock32_to_clock64(clock)) def get_mcu(self): return self._i2c.get_mcu() def read_reg(self, reg): params = self._i2c.i2c_read([reg], 2) response = bytearray(params["response"]) return (response[0] << 8) | response[1] def set_reg(self, reg, val, minclock=0): self._i2c.i2c_write([reg, (val >> 8) & 0xFF, val & 0xFF], minclock=minclock) def add_bulk_sensor_data_client(self, cb): self._batch_bulk.add_client(cb) def latched_status(self): response = self._ldc1612_ng_latched_status_cmd.send([self._oid]) return response["status"] def latched_status_str(self): s = self.latched_status() return self.status_to_str(s) def status_to_str(self, s: int): status_bits = [ "0", "1", "2", "UNREADCONV1", "4", "5", "DRDY", "7", "ERR_ZC", "ERR_ALE", "ERR_AHE", "ERR_WD", "ERR_OR", "ERR_UR", "14", "ERR_CH1", ] flags = [] for bit, flag in enumerate(status_bits): if s & (1 << bit): flags.append(flag) return " ".join(flags) def data_error_to_str(self, d: int): err_bits = [ "Under-range Error", "Over-range Error", "Watchdog Error", "Amplitude Error", ] d = d >> 12 # shift out the data bits errors = [] for bit, err in enumerate(err_bits): if d & (1 << bit): errors.append(err) return " ".join(errors) def read_one_value(self): self._init_chip() # the status command also returns the last value res = self._ldc1612_ng_latched_status_cmd.send([self._oid]) status = res["status"] lastval = res["lastval"] freq = self.from_ldc_freqval(lastval) if lastval <= 0x0FFFFFFF else 0.0 return LDC1612_ng_value( status=status, freqval=lastval, freq=freq, ) def to_ldc_freqval(self, freq): return int(freq * (1 << 28) / float(self._ldc_freq_ref) + 0.5) def from_ldc_freqval(self, val, ignore_err=False): if val > 0x0FFFFFFF and not ignore_err: raise self.printer.command_error(f"LDC1612 frequency value has error bits: {hex(val)}") return round(val * (float(self._ldc_freq_ref) / (1 << 28)), 3) # # Homing # def setup_home( self, trsync_oid: int, hit_reason: int, other_reason_base: int, trigger_freq: float, start_freq: float, start_time: float, mode: str = "home", tap_threshold: Optional[float] = None, max_errors: int = 0, ): MODES = { "home": HOME_MODE_HOME, "wma": HOME_MODE_WMA, "sos": HOME_MODE_SOS, } mode_val = MODES.get(mode.lower(), None) if mode_val is None: raise self.printer.command_error(f"Invalid mode: {mode}") t_freqvl = self.to_ldc_freqval(trigger_freq) s_freqval = self.to_ldc_freqval(start_freq) start_time_mcu = self._mcu.print_time_to_clock(start_time) if start_time > 0 else 0 tap_threshold_val = int(tap_threshold * 65536.0) if tap_threshold is not None else 0 if self._verbose: logging.info( f"LDC1612_ng setup_home: {mode} trigger: {trigger_freq:.2f} ({t_freqvl}) " f"safe: {start_freq:.2f} ({s_freqval}) @ {start_time:.2f} ({start_time_mcu}) " f"trsync: {trsync_oid} {hit_reason} {other_reason_base} TAP: {tap_threshold} ({tap_threshold_val:x})" ) self._ldc1612_ng_setup_home_cmd.send( [ self._oid, trsync_oid, hit_reason, other_reason_base, t_freqvl, s_freqval, start_time_mcu, mode_val, tap_threshold_val, max_errors, ] ) def _convert_clock(self, c): if c == 0: return 0 return self._clock32_to_print_time(c) def finish_home(self): # "ldc1612_finish_home2_reply oid=%c homing=%c trigger_clock=%u tap_start_clock=%u", reply = self._ldc1612_ng_finish_home_cmd.send([self._oid]) trigger_clock = reply["trigger_clock"] tap_start_clock = reply["tap_start_clock"] error = reply["error"] trigger_time = self._convert_clock(trigger_clock) tap_start_time = self._convert_clock(tap_start_clock) return LDC1612_ng_homing_result(trigger_time, tap_start_time, error) def set_sos_section(self, sect_num: int, sect_vals: List[float]): # pack sect_vals into a byte array using struct.pack sect_bytes = [b for b in struct.pack("<6f", *sect_vals)] self._ldc1612_ng_set_sos_section.send([self._oid, sect_num, sect_bytes]) # The value that freqvals are multiplied by to get a float frequency def freqval_conversion_value(self): return float(self._ldc_freq_ref) / (1 << 28) def _verify_chip(self): # In case of miswiring, testing LDC1612 device ID prevents treating # noise or wrong signal as a correctly initialized device manuf_id = self.read_reg(REG_MANUFACTURER_ID) dev_id = self.read_reg(REG_DEVICE_ID) if manuf_id != LDC1612_MANUF_ID or dev_id != LDC1612_DEV_ID: raise self.printer.command_error( "Invalid ldc1612 id (got %x,%x vs %x,%x).\n" "This is generally indicative of connection problems\n" "(e.g. faulty wiring) or a faulty ldc1612 chip." % (manuf_id, dev_id, LDC1612_MANUF_ID, LDC1612_DEV_ID) ) def _init_chip(self): if self._chip_initialized: return self._verify_chip() # TODO: have a max_frequency and pick the best deglitch for it if self._deglitch == "1mhz": deglitch = DEGLITCH_1_0MHZ elif self._deglitch == "3.3mhz": deglitch = DEGLITCH_3_3MHZ elif self._deglitch == "10mhz" or self._deglitch == "default": deglitch = DEGLITCH_10MHZ elif self._deglitch == "33mhz": deglitch = DEGLITCH_33MHZ else: raise self.printer.error(f"Invalid {self._name} deglitch value: {self._deglitch}") # This is the TI-recommended register configuration order # Setup chip in requested query rate rcount0 = self._ldc_freq_ref / (16.0 * (self._data_rate - 4)) self.set_reg(REG_RCOUNT0, int(rcount0 + 0.5)) self.set_reg(REG_OFFSET0, 0) self.set_reg( REG_SETTLECOUNT0, int(self._ldc_settle_time * self._ldc_freq_ref / 16.0 + 0.5), ) self.set_reg( REG_CLOCK_DIVIDERS0, (self._ldc_fin_divider << 12) | (self._ldc_fref_divider), ) self.set_reg(REG_ERROR_CONFIG, 0b1111_1100_1111_1001) # report everything to STATUS and INTB except ZC self.set_reg(REG_MUX_CONFIG, 0x0208 | deglitch) if (self._device_product == PRODUCT_LDC1612_INTERNAL_CLK): # use internal oscillator # RP_OVERRIDE_EN | AUTO_AMP_DIS | reserved self.set_reg(REG_CONFIG, (1 << 12) | (1 << 10) | 0x001) else: # RP_OVERRIDE_EN | AUTO_AMP_DIS | REF_CLK_SRC=clkin | reserved self.set_reg(REG_CONFIG, (1 << 12) | (1 << 10) | (1 << 9) | 0x001) self.set_reg(REG_DRIVE_CURRENT0, self._drive_current << 11) self._chip_initialized = True def get_deglitch(self): return self.read_reg(REG_MUX_CONFIG) & ~0x0208 def set_deglitch(self, val: int): logging.info(f"LDC1612ng {self._name} deglitch set {val}") self.set_reg(REG_MUX_CONFIG, val | 0x0208) def get_drive_current(self) -> int: return self._drive_current def set_drive_current(self, cval: int, maxfreq: float = None): if cval < 0 or cval > 31: raise self.printer.command_error("Drive current must be between 0 and 31") if self._drive_current == cval: return if maxfreq is not None: if maxfreq < 1_000_000.0: self.set_deglitch(DEGLITCH_1_0MHZ) elif maxfreq < 3_300_000.0: self.set_deglitch(DEGLITCH_3_3MHZ) elif maxfreq < 10_000_000.0: self.set_deglitch(DEGLITCH_10MHZ) else: self.set_deglitch(DEGLITCH_33MHZ) logging.info(f"LDC1612ng {self._name} set drive current {cval}") self._drive_current = cval self.set_reg(REG_DRIVE_CURRENT0, cval << 11) # Start, stop, and process message batches def _start_measurements(self): self._init_chip() self._start_count += 1 if self._start_count > 1: logging.info("LDC1612 start count: %d", self._start_count) return # Start bulk reading rest_ticks = self._mcu.seconds_to_clock(0.5 / self._data_rate) self._ldc1612_ng_start_stop_cmd.send([self._oid, rest_ticks]) # logging.info("LDC1612 starting '%s' measurements", self._name) # Initialize clock tracking self._ffreader.note_start() def _finish_measurements(self): self._start_count -= 1 if self._start_count > 0: logging.info("LDC1612 stop, start count now: %d", self._start_count) return # Halt bulk reading self._ldc1612_ng_start_stop_cmd.send_wait_ack([self._oid, 0]) self._ffreader.note_end() # logging.info("LDC1612 finished '%s' measurements", self._name) def _process_batch(self, eventtime): samples = self._ffreader.pull_samples() count = 0 err_count = 0 last_err_kind = 0 for ptime, val in samples: if val > 0x0FFFFFFF: # high nibble indicates an error err_kind = (val >> 28) err_count += 1 if last_err_kind != err_kind: if self._verbose: logging.info(f"LDC1612 error: {hex(val)}") last_err_kind = err_kind else: # val is a raw value samples[count] = (ptime, val) count += 1 # remove the samples we didn't fill in because of errors del samples[count:] return { "data": samples, "errors": err_count, "overflows": self._ffreader.get_last_overflows(), } ================================================ FILE: probe_eddy_ng.py ================================================ # EDDY-ng # # Copyright (C) 2025 Vladimir Vukicevic # # Based on original probe_eddy_current code by: # Copyright (C) 2020-2024 Kevin O'Connor # # This file may be distributed under the terms of the GNU GPLv3 license. from __future__ import annotations import os import logging import math import bisect import re import traceback import pickle import base64 import time import numpy as np import numpy.polynomial as npp from itertools import combinations from functools import cmp_to_key from dataclasses import dataclass, field from typing import ( Any, Dict, List, Optional, Tuple, ClassVar, final, ) try: from klippy import mcu, pins, chelper from klippy.printer import Printer from klippy.configfile import ConfigWrapper from klippy.configfile import error as configerror from klippy.gcode import GCodeCommand from klippy.toolhead import ToolHead from klippy.extras import probe, manual_probe, bed_mesh from klippy.extras.homing import HomingMove IS_KALICO = True HAS_PROBE_RESULT_TYPE = False except ImportError: import mcu import pins import chelper from klippy import Printer from configfile import ConfigWrapper from configfile import error as configerror from gcode import GCodeCommand from toolhead import ToolHead from . import probe, manual_probe, bed_mesh from .homing import HomingMove IS_KALICO = False HAS_PROBE_RESULT_TYPE = hasattr(manual_probe, "ProbeResult") from . import ldc1612_ng try: import plotly # noqa except ImportError: plotly = None try: import scipy # noqa except ImportError: scipy = None # In this file, a couple of conventions are used (for sanity). # Variables are named according to: # - "height" is always a physical height as detected by the probe in mm # - "z" is always a z axis position (which may or may not match height) # - "freq" is always a frequency value (float) # - "freqval" is always an encoded frequency value, as communicated to/from the sensor (int) # There are three distinct operations/phases. Homing Z via the virtual # endstop is the only operation that can happen while Z is not homed: # # 1. Homing Z using a virtual probe endstop. This is largely handled by # ProbeEddyEndstopWrapper. It sets up the sensor to trigger when a certain # frequency is crossed, and then lets a HomingMove continue that moves the # toolhead down. When that frequency is hit, it triggers, and Klipper stops # the toolhead from moving down. The time point when it triggers is set as # the z=trigger_height (which is home_trigger_height in the configurable # params). Z should be accurate enough at this point. This operation can be run # when the bed/toolhead are cold or hot. # # Once Z is homed, two additional operations become available: # # 2. Probing at either a single point or multiple points. This is used for # Quad Gantry Leveling, Bed Mesh, and other similar operations. This is # largely handled by the ProbeEddyScannigProbe class -- one is returned # from the ProbeEddy `probe` object when `start_probe_session` is called. # For Eddy probes, there is no reason to move the toolhead up and down at # each probe point: the measured distance between the sensor and the build # plate can be read directly. This class starts gathering sample data when # the session starts and records the times when there's a sample that we # care about, along with the toolhead position, whenever a caller calls # `run_probe`. If this is a `rapid_scan` scan, then a callback is attached # to the current motion so that we can save the movement's time and position # without actually waiting for it. If it's in normal mode, then the toolhead # will pause at each position. In both cases, the results are obtained by # calling `pull_probed_results`, which returns an array of results at each # point that `run_probe` was called for, in order. # # PROBE_STATIC HOME_Z=1 can be used to set the toolhead's Z position # based on the current height reading from the probe while the toolhead is # static, leading to a more accurate result than a regular homing operation # (which involves movement). # # 3. A "tap" to fine-tune the Z offset. This should be run with the bed at print # temperature and soaked for a bit. The nozzle should also be warm but not so # hot that filament risks oozing out. The nozzle also must be clean. 150C # is a good temperature to both clean and tap at. # # This operation will identify the exact position of the Z axis # when the nozzle touches the bed, which means that a precise Z offset # can be set. # # The eddy current response and readings depend on temperature of both the target # (bed) and the sensor (coil). EddyNG does not do any temperature compensation. Instead # it relies on the "tap" operation to get an accurate reference point for z=0 regardless # of temperatures. Empirically, small offsets from a reference point can still be read # accurately from the sensor, even if the absolute value is incorrect at temperature. # For example, taking sensor readings at Z=2 when perfectly homed via tap may read as # 1.9 due to temperatures, which is not correct. However, raising the toolhead to Z=2.1 # will raise the sensor reading to 2.0; likewise, lowering the toolhead to Z=1.9 will # lower the sensor reading to 1.8. # # Care in macros should be taken to not invalidate the Z offset set after a tap # by relying on absolute sensor readings. # @dataclass class ProbeEddyParams: # The speed at which to perform normal homing operations probe_speed: float = 5.0 # The speed at which to lift the toolhead during probing operations lift_speed: float = 10.0 # The speed at which to move in the xy plane (typically only for calibration) move_speed: float = 50.0 # The height at which the virtual endstop should trigger. A value # between 1.0 and 3.0 is recommended, with 2.0 or 2.5 being good # choices. home_trigger_height: float = 2.0 # The amount higher the probe needs to detect the toolhead is at in order to # allow homing to begin. For example, if the trigger height is 2.0, and the # start offset is 1.5, then homing will abort if the sensor detects the # toolhead is below 3.5mm off the print bed. home_trigger_safe_start_offset: float = 1.0 # The amount of time that must elapse from the start of probing until the # safe start position is crossed. This is to make sure there are some values # that are above the safe position before it's crossed, to ensure that homing # doesn't begin with the toolhead too low. home_trigger_safe_time_offset: float = 0.100 # The maximum z value to calibrate from. 15.0 is fine as a default, calibrating # at higher values is not needed. Calibration will start with the first # valid height. calibration_z_max: float = 15.0 # The "drive current" for the LDC1612 sensor. This value is typically # sensor specific and depends on the coil design and the operating distance. # A good starting value for BTT Eddy is 15. A good value can be obtained # by placing the toolhead ~10mm above the bed and running LDC_NG_CALIBRATE_ # DRIVE_CURRENT. reg_drive_current: int = 0 # The drive current to use for tap operations. If not set, the `reg_drive_current` # value will be used. Tapping involves reading values much closer to the print # bed than basic homing, and may require a different, typically higher, # drive current. For example, BTT Eddy performs best with this value at 16. # Note that the sensor needs to be calibrated for both drive currents separately. # Pass the DRIVE_CURRENT argument to EDDY_NG_CALIBRATE. tap_drive_current: int = 0 # The Z position at which to start a tap-home operation. This height may # need to be fine-tuned to ensure that the sensor can provide readings across the # entire tap range (i.e. from this value down to tap_target_z), which in turn # will depend on the tap_drive_current. When the tap_drive_current is # increased, the sensor may not be able to read values at higher heights. # For example, BTT Eddy typically cannot work with heights above 3.5mm with # a drive current of 16. # # Note that all of these values are in terms of offsets from the nozzle # to the toolhead. The actual sensor coil is mounted higher -- but must be placed # between 2.5 and 3mm above the nozzle, ideally around 2.75mm. If there are # amplitude errors, try raising or lowering the sensor coil slightly. tap_start_z: float = 3.0 # The target Z position for a tap operation. This is the lowest position that # the toolhead may travel to in case of a failed tap. Do not set this very low, # as it will cause your toolhead to try to push through your build plate in # the case of a failed tap. A value like -0.250 is no worse than moving the # nozzle down one or two notches too far when doing manual Z adjustment. tap_target_z: float = -0.250 # the tap mode to use. 'wma' is a derivative of weighted moving average, # 'butter' is a butterworth filter tap_mode: str = "butter" # The threshold at which to detect a tap. This value is raw sensor value # specific. A good value can be obtained by running [....] and examining # the graph. See [calibration docs coming soon]. # # The meaning of this depends on tap_mode, and the value will be different # if a different tap_mode is used. You can experiment to arrive at this # value. Typically, a lower value will make tap detection more sensitive, # but might lead to false positives (too early detections). A higher value # may cause the detection to wait too long or miss a tap entirely. # You can pass a THRESHOLD parameter to the TAP command to experiment to # find a good value. # # You may also need to use different thresholds for different build plates. # Note that the default value of this threshold depends on the tap_mode. tap_threshold: float = 250.0 # The speed at which a tap operation should be performed at. This shouldn't # be much slower than 3.0, but you can experiment with lower or higher values. # Don't go too high though, because Klipper needs some small amount of time # to react to a tap trigger, and the toolhead will still be moving at this # speed even past the tap point. So, consider any speed you'd feel comfortable # triggering a toolhead move to tap_target_z at. tap_speed: float = 3.0 # A static additional amount to add to the computed tap Z offset. Use this if # the computed tap is a bit too high or too low for your taste. Positive # values will raise the toolhead, negative values will lower it. tap_adjust_z: float = 0.0 # The number of times to do a tap, averaging the results. tap_samples: int = 3 # The maximum number of tap samples. tap_max_samples: int = 5 # The maximum standard deviation for any 3 samples to be considered valid. tap_samples_stddev: float = 0.020 # Use the median value instead of the mean tap_use_median: bool = False # Where in the time range of tap detection start to the time the threshold # is crossed should the tap be placed. 0.0 places it at the earliest start # of tap detection; 1.0 places it at the point where the threshold is hit. # A value between 0.2-0.5 generally results in more consistent tap position detection, # but you may want to adjust this for your configuration. This is a number # in the range of 0.0 to 1.0. tap_time_position: float = 0.3 # When probing multiple points (not rapid scan), how long to sample for at each probe point, # after a scan_sample_time_delay delay. The total dwell time at each probe point is # scan_sample_time + scan_sample_time_delay. scan_sample_time: float = 0.100 # When probing multiple points (not rapid scan), how long to delay at each probe point # before the scan_sample_time kicks in. scan_sample_time_delay: float = 0.050 # number of points to save for calibration calibration_points: int = 150 # configuration for butterworth filter tap_butter_lowcut: float = 5.0 tap_butter_highcut: float = 25.0 tap_butter_order: int = 2 # Probe position relative to toolhead x_offset: float = 0.0 y_offset: float = 0.0 # remove some safety checks, largely for testing/development allow_unsafe: bool = False # whether to write the tap plot for the last tap write_tap_plot: bool = False # whether to write the tap plot for every tap write_every_tap_plot: bool = False # maximum number of errors to allow in a row on the sensor max_errors: int = 0 # whether to print lots of verbose debug info to the log debug: bool = True tap_trigger_safe_start_height: float = 1.5 _warning_msgs: List[str] = field(default_factory=list) @staticmethod def str_to_floatlist(s): if s is None: return None try: return [float(v) for v in re.split(r"\s*,\s*|\s+", s)] except: raise configerror(f"Can't parse '{s}' as list of floats") def is_default_butter_config(self): return self.tap_butter_lowcut == 5.0 and self.tap_butter_highcut == 25.0 and self.tap_butter_order == 2 def load_from_config(self, config: ConfigWrapper): mode_choices = ["wma", "butter"] self.probe_speed = config.getfloat("probe_speed", self.probe_speed, above=0.0) self.lift_speed = config.getfloat("lift_speed", self.lift_speed, above=0.0) self.move_speed = config.getfloat("move_speed", self.move_speed, above=0.0) self.home_trigger_height = config.getfloat("home_trigger_height", self.home_trigger_height, minval=1.0) self.home_trigger_safe_start_offset = config.getfloat( "home_trigger_safe_start_offset", self.home_trigger_safe_start_offset, minval=0.5, ) self.calibration_z_max = config.getfloat("calibration_z_max", self.calibration_z_max, above=0.0) self.reg_drive_current = config.getint("reg_drive_current", 0, minval=0, maxval=31) self.tap_drive_current = config.getint("tap_drive_current", 0, minval=0, maxval=31) self.tap_start_z = config.getfloat("tap_start_z", self.tap_start_z, above=0.0) self.tap_target_z = config.getfloat("tap_target_z", self.tap_target_z) self.tap_speed = config.getfloat("tap_speed", self.tap_speed, above=0.0) self.tap_adjust_z = config.getfloat("tap_adjust_z", self.tap_adjust_z) self.calibration_points = config.getint("calibration_points", self.calibration_points) self.tap_mode = config.getchoice("tap_mode", mode_choices, self.tap_mode) default_tap_threshold = 1000.0 # for wma if self.tap_mode == "butter": default_tap_threshold = 250.0 self.tap_threshold = config.getfloat("tap_threshold", default_tap_threshold) self.scan_sample_time = config.getfloat("scan_sample_time", self.scan_sample_time, above=0.0) self.scan_sample_time_delay = config.getfloat("scan_sample_time_delay", self.scan_sample_time_delay, minval=0.0) # for 'butter' self.tap_butter_lowcut = config.getfloat("tap_butter_lowcut", self.tap_butter_lowcut, above=0.0) self.tap_butter_highcut = config.getfloat( "tap_butter_highcut", self.tap_butter_highcut, above=self.tap_butter_lowcut, ) self.tap_butter_order = config.getint("tap_butter_order", self.tap_butter_order, minval=1) self.tap_samples = config.getint("tap_samples", self.tap_samples, minval=1) self.tap_max_samples = config.getint("tap_max_samples", self.tap_max_samples, minval=self.tap_samples) self.tap_samples_stddev = config.getfloat("tap_samples_stddev", self.tap_samples_stddev, above=0.0) self.tap_use_median = config.getboolean("tap_use_median", self.tap_use_median) self.tap_trigger_safe_start_height = config.getfloat( "tap_trigger_safe_start_height", -1.0, above=0.0, ) self.tap_time_position = config.getfloat("tap_time_position", self.tap_time_position, minval=0.0, maxval=1.0) if self.tap_trigger_safe_start_height == -1.0: # sentinel self.tap_trigger_safe_start_height = self.home_trigger_height / 2.0 self.allow_unsafe = config.getboolean("allow_unsafe", self.allow_unsafe) self.write_tap_plot = config.getboolean("write_tap_plot", self.write_tap_plot) self.write_every_tap_plot = config.getboolean("write_every_tap_plot", self.write_every_tap_plot) self.debug = config.getboolean("debug", self.debug) self.max_errors = config.getint("max_errors", self.max_errors) self.x_offset = config.getfloat("x_offset", self.x_offset) self.y_offset = config.getfloat("y_offset", self.y_offset) self.validate(config) def validate(self, config: ConfigWrapper = None): printer = config.get_printer() req_cal_z_max = self.home_trigger_safe_start_offset + self.home_trigger_height + 1.0 if self.calibration_z_max < req_cal_z_max: raise printer.config_error( f"calibration_z_max must be at least home_trigger_safe_start_offset+home_trigger_height+1.0 ({self.home_trigger_safe_start_offset:.3f}+{self.home_trigger_height:.3f}+1.0={req_cal_z_max:.3f})" ) if self.x_offset == 0.0 and self.y_offset == 0.0 and not self.allow_unsafe: raise printer.config_error("ProbeEddy: x_offset and y_offset are both 0.0; is the sensor really mounted at the nozzle?") if self.home_trigger_height <= self.tap_trigger_safe_start_height: raise printer.config_error("ProbeEddy: home_trigger_height must be greater than tap_trigger_safe_start_height") need_scipy = False if self.tap_mode == "butter" and not self.is_default_butter_config(): need_scipy = True if need_scipy and not scipy: raise printer.config_error( "ProbeEddy: butter mode with custom filter parameters requires scipy, which is not available; please install scipy, use the defaults, or use wma mode" ) @dataclass class ProbeEddyProbeResult: samples: List[float] mean: float = 0.0 median: float = 0.0 min_value: float = 0.0 max_value: float = 0.0 tstart: float = 0.0 tend: float = 0.0 errors: int = 0 USE_MEAN_FOR_VALUE: ClassVar[bool] = False @property def valid(self): return len(self.samples) > 0 @property def value(self): return self.mean if self.USE_MEAN_FOR_VALUE else self.median @property def stddev(self): stddev_sum = np.sum([(s - self.value) ** 2.0 for s in self.samples]) return float((stddev_sum / len(self.samples)) ** 0.5) @classmethod def make(cls, times: List[float], heights: List[float], errors: int = 0) -> ProbeEddyProbeResult: h = np.array(heights) return ProbeEddyProbeResult( samples=h.tolist(), mean=float(np.mean(h)), median=float(np.median(h)), min_value=float(np.min(h)), max_value=float(np.max(h)), tstart=float(times[0]), tend=float(times[-1]), errors=errors ) def __format__(self, spec): if spec == "v": return f"{self.value:.3f}" if self.USE_MEAN_FOR_VALUE: value = f"{self.mean:.3f}" extra = f"med={self.median:.3f}" else: value = f"{self.median:.3f}" extra = f"avg={self.mean:.3f}" return f"{value} ({extra}, {self.min_value:.3f} to {self.max_value:.3f}, [{self.stddev:.3f}])" @final class ProbeEddy: def __init__(self, config: ConfigWrapper): logging.info("Hello from ProbeEddyNG") self._printer: Printer = config.get_printer() self._reactor = self._printer.get_reactor() self._gcode = self._printer.lookup_object("gcode") self._full_name = config.get_name() self._name = self._full_name.split()[-1] sensors = { "ldc1612": ldc1612_ng.LDC1612_ng, "btt_eddy": ldc1612_ng.LDC1612_ng, "cartographer": ldc1612_ng.LDC1612_ng, "mellow_fly": ldc1612_ng.LDC1612_ng, "ldc1612_internal_clk": ldc1612_ng.LDC1612_ng, } sensor_type = config.getchoice("sensor_type", {s: s for s in sensors}) self._sensor_type = sensor_type self._sensor = sensors[sensor_type](config) self._mcu = self._sensor.get_mcu() self._toolhead: ToolHead = None # filled in _handle_connect self._trapq = None self.params = ProbeEddyParams() self.params.load_from_config(config) # figure out if either of these comes from the autosave section # so we can sort out what we want to write out later on asfc = self._printer.lookup_object("configfile").autosave.fileconfig self._saved_reg_drive_current = asfc.getint(self._full_name, "reg_drive_current", fallback=None) self._saved_tap_drive_current = asfc.getint(self._full_name, "tap_drive_current", fallback=None) # in case there's legacy drive currents old_saved_reg_drive_current = asfc.getint(self._full_name, "saved_reg_drive_current", fallback=0) old_saved_tap_drive_current = asfc.getint(self._full_name, "saved_tap_drive_current", fallback=0) self._reg_drive_current = self.params.reg_drive_current or old_saved_reg_drive_current or self._sensor._drive_current self._tap_drive_current = self.params.tap_drive_current or old_saved_tap_drive_current or self._reg_drive_current # at what minimum physical height to start homing. It must be above the safe start position, # because we need to move from the start through the safe start position self._home_start_height = self.params.home_trigger_height + self.params.home_trigger_safe_start_offset + 1.0 # physical offsets between probe and nozzle self.offset = { "x": self.params.x_offset, "y": self.params.y_offset, } version = config.getint("calibration_version", default=-1) calibration_bad = False if version == -1: if config.get("calibrated_drive_currents", None) is not None: calibration_bad = True elif version != ProbeEddyFrequencyMap.calibration_version: calibration_bad = True calibrated_drive_currents = config.getintlist("calibrated_drive_currents", []) self._dc_to_fmap: Dict[int, ProbeEddyFrequencyMap] = {} if not calibration_bad: for dc in calibrated_drive_currents: fmap = ProbeEddyFrequencyMap(self) if fmap.load_from_config(config, dc): self._dc_to_fmap[dc] = fmap else: for dc in calibrated_drive_currents: # read so that there are no warnings about unknown fields _ = config.get(f"calibration_{dc}") self.params._warning_msgs.append("EDDYng calibration: calibration data invalid, please recalibrate") # Our virtual endstop wrapper -- used for homing. self._endstop_wrapper = ProbeEddyEndstopWrapper(self) # There can only be one active sampler at a time self._sampler: ProbeEddySampler = None self._last_sampler: ProbeEddySampler = None self.save_samples_path = None # The last tap Z value, in absolute axis terms. Used for status. self._last_tap_z = 0.0 # The last gcode offset applied after tap, either the tap # value, or 0.0 if HOME_Z=1 self._last_tap_gcode_adjustment = 0.0 # This class emulates "PrinterProbe". We use some existing helpers to implement # functionality like start_session self._printer.add_object("probe", self) self._bed_mesh_helper = BedMeshScanHelper(self, config) # TODO: get rid of this if hasattr(probe, "ProbeCommandHelper"): self._cmd_helper = probe.ProbeCommandHelper(config, self, self._endstop_wrapper.query_endstop) else: self._cmd_helper = None # when doing a scan, what's the offset between probe readings at the bed # scan height and the accurate bed height, based on the last tap. self._tap_offset = 0.0 self._last_probe_result = 0.0 # runtime configurable self._tap_adjust_z = self.params.tap_adjust_z # define our own commands self._dummy_gcode_cmd: GCodeCommand = self._gcode.create_gcode_command("", "", {}) self.define_commands(self._gcode) self._printer.register_event_handler("gcode:command_error", self._handle_command_error) self._printer.register_event_handler("klippy:connect", self._handle_connect) # patch bed_mesh because Klipper if not IS_KALICO: bed_mesh.ProbeManager.start_probe = bed_mesh_ProbeManager_start_probe_override def _log_error(self, msg): logging.error(f"{self._name}: {msg}") self._gcode.respond_raw(f"!! EDDYng: {msg}\n") def _log_warning(self, msg): logging.warning(f"{self._name}: {msg}") self._gcode.respond_raw(f"!! EDDYng: {msg}\n") def _log_msg(self, msg): logging.info(f"{self._name}: {msg}") self._gcode.respond_info(f"{msg}", log=False) def _log_info(self, msg): logging.info(f"{self._name}: {msg}") def _log_debug(self, msg): if self.params.debug: logging.info(f"{self._name}: {msg}") def define_commands(self, gcode): gcode.register_command("PROBE_EDDY_NG_STATUS", self.cmd_STATUS, self.cmd_STATUS_help) gcode.register_command( "PROBE_EDDY_NG_CALIBRATE", self.cmd_CALIBRATE, self.cmd_CALIBRATE_help, ) gcode.register_command( "PROBE_EDDY_NG_CALIBRATION_STATUS", self.cmd_CALIBRATION_STATUS, self.cmd_CALIBRATION_STATUS_help, ) gcode.register_command( "PROBE_EDDY_NG_SETUP", self.cmd_SETUP, self.cmd_SETUP_help, ) gcode.register_command( "PROBE_EDDY_NG_CLEAR_CALIBRATION", self.cmd_CLEAR_CALIBRATION, self.cmd_CLEAR_CALIBRATION_help, ) gcode.register_command("PROBE_EDDY_NG_PROBE", self.cmd_PROBE, self.cmd_PROBE_help) gcode.register_command( "PROBE_EDDY_NG_PROBE_STATIC", self.cmd_PROBE_STATIC, self.cmd_PROBE_STATIC_help, ) gcode.register_command( "PROBE_EDDY_NG_PROBE_ACCURACY", self.cmd_PROBE_ACCURACY, self.cmd_PROBE_ACCURACY_help, ) gcode.register_command("PROBE_EDDY_NG_TAP", self.cmd_TAP, self.cmd_TAP_help) gcode.register_command( "PROBE_EDDY_NG_SET_TAP_OFFSET", self.cmd_SET_TAP_OFFSET, "Set or clear the tap offset for the bed mesh scan and other probe operations", ) gcode.register_command( "PROBE_EDDY_NG_SET_TAP_ADJUST_Z", self.cmd_SET_TAP_ADJUST_Z, "Set the tap adjustment value", ) gcode.register_command( "PROBE_EDDY_NG_TEST_DRIVE_CURRENT", self.cmd_TEST_DRIVE_CURRENT, "Test a drive current.", ) gcode.register_command("Z_OFFSET_APPLY_PROBE", None) gcode.register_command( "Z_OFFSET_APPLY_PROBE", self.cmd_Z_OFFSET_APPLY_PROBE, "Apply the current G-Code Z offset to tap_adjust_z", ) # some handy aliases while I'm debugging things to save my fingers gcode.register_command( "PES", self.cmd_STATUS, self.cmd_STATUS_help + " (alias for PROBE_EDDY_NG_STATUS)", ) gcode.register_command( "PEP", self.cmd_PROBE, self.cmd_PROBE_help + " (alias for PROBE_EDDY_NG_PROBE)", ) gcode.register_command( "PEPS", self.cmd_PROBE_STATIC, self.cmd_PROBE_STATIC_help + " (alias for PROBE_EDDY_NG_PROBE_STATIC)", ) gcode.register_command( "PETAP", self.cmd_TAP, self.cmd_TAP_help + " (alias for PROBE_EDDY_NG_TAP)", ) gcode.register_command("EDDYNG_BED_MESH_EXPERIMENTAL", self.cmd_MESH, "") gcode.register_command("EDDYNG_START_STREAM_EXPERIMENTAL", self.cmd_START_STREAM, "") gcode.register_command("EDDYNG_STOP_STREAM_EXPERIMENTAL", self.cmd_STOP_STREAM, "") def _handle_command_error(self, gcmd=None): try: if self._sampler is not None: self._sampler.finish() except: logging.exception("EDDYng handle_command_error: sampler.finish() failed") def _handle_connect(self): self._toolhead = self._printer.lookup_object("toolhead") self._trapq = self._toolhead.get_trapq() for msg in self.params._warning_msgs: self._log_warning(msg) def _get_trapq_position(self, print_time: float) -> Tuple[Tuple[float, float, float], float]: ffi_main, ffi_lib = chelper.get_ffi() data = ffi_main.new("struct pull_move[1]") count = ffi_lib.trapq_extract_old(self._trapq, data, 1, 0.0, print_time) if not count: return None, None move = data[0] move_time = max(0.0, min(move.move_t, print_time - move.print_time)) dist = (move.start_v + 0.5 * move.accel * move_time) * move_time pos = ( move.start_x + move.x_r * dist, move.start_y + move.y_r * dist, move.start_z + move.z_r * dist, ) velocity = move.start_v + move.accel * move_time return pos, velocity def _get_trapq_height(self, print_time: float) -> float: th_pos, _ = self._get_trapq_position(print_time) if th_pos is None: return None return th_pos[2] def current_drive_current(self) -> int: return self._sensor.get_drive_current() def reset_drive_current(self, tap=False): dc = self._tap_drive_current if tap else self._reg_drive_current if dc == 0: raise self._printer.command_error(f"Unknown {'tap' if tap else 'homing'} drive current") self._sensor.set_drive_current(dc) def map_for_drive_current(self, dc: Optional[int] = None) -> ProbeEddyFrequencyMap: if dc is None: dc = self.current_drive_current() if dc not in self._dc_to_fmap: raise self._printer.command_error(f"Drive current {dc} not calibrated") return self._dc_to_fmap[dc] # helpers to forward to the map def height_to_freq(self, height: float, drive_current: Optional[int] = None) -> float: if drive_current is None: drive_current = self.current_drive_current() return self.map_for_drive_current(drive_current).height_to_freq(height) def freq_to_height(self, freq: float, drive_current: Optional[int] = None) -> float: if drive_current is None: drive_current = self.current_drive_current() return self.map_for_drive_current(drive_current).freq_to_height(freq) def calibrated(self, drive_current: Optional[int] = None) -> bool: if drive_current is None: drive_current = self.current_drive_current() return drive_current in self._dc_to_fmap and self._dc_to_fmap[drive_current].calibrated() def _print_time_now(self): return self._mcu.estimated_print_time(self._reactor.monotonic()) def _z_homed(self): curtime = self._reactor.monotonic() kin_status = self._printer.lookup_object("toolhead").get_kinematics().get_status(curtime) return "z" in kin_status["homed_axes"] def _xy_homed(self): curtime = self._reactor.monotonic() kin_status = self._printer.lookup_object("toolhead").get_kinematics().get_status(curtime) return "x" in kin_status["homed_axes"] and "y" in kin_status["homed_axes"] def _z_hop(self, by=5.0): if by < 0.0: raise self._printer.command_error("Z hop must be positive") toolhead: ToolHead = self._printer.lookup_object("toolhead") curpos = toolhead.get_position() curpos[2] = curpos[2] + by toolhead.manual_move(curpos, self.params.probe_speed) def _set_toolhead_position(self, pos, homing_axes): # klipper changed homing_axes to be a "xyz" string instead # of a tuple randomly on jan10 without support for the old # syntax func = self._toolhead.set_position kind = type(func.__defaults__[0]) if kind is str: # new homing_axes_str = "".join(["xyz"[axis] for axis in homing_axes]) return self._toolhead.set_position(pos, homing_axes=homing_axes_str) else: # old return self._toolhead.set_position(pos, homing_axes=homing_axes) def _z_not_homed(self): kin = self._toolhead.get_kinematics() # klipper got rid of this if hasattr(kin, "note_z_not_homed"): kin.note_z_not_homed() else: try: kin.clear_homing_state("z") except TypeError: raise self._printer.command_error( "clear_homing_state failed: please update Klipper, your klipper is from the brief 5 day window where this was broken" ) def save_config(self): configfile = self._printer.lookup_object("configfile") configfile.remove_section(self._full_name) configfile.set( self._full_name, "calibrated_drive_currents", str.join(", ", [str(dc) for dc in self._dc_to_fmap.keys()]), ) configfile.set( self._full_name, "calibration_version", str(ProbeEddyFrequencyMap.calibration_version), ) if self.params.reg_drive_current != self._reg_drive_current or self.params.reg_drive_current == self._saved_reg_drive_current: configfile.set(self._full_name, "reg_drive_current", str(self._reg_drive_current)) if self.params.tap_drive_current != self._tap_drive_current or self.params.tap_drive_current == self._saved_tap_drive_current: configfile.set(self._full_name, "tap_drive_current", str(self._tap_drive_current)) for _, fmap in self._dc_to_fmap.items(): fmap.save_calibration() self._log_msg("Calibration saved. Issue a SAVE_CONFIG to write the values to your config file and restart Klipper.") def start_sampler(self, *args, **kwargs) -> ProbeEddySampler: if self._sampler: raise self._printer.command_error("EDDYng: Already sampling! (This shouldn't happen; FIRMWARE_RESTART to fix)") self._sampler = ProbeEddySampler(self, *args, **kwargs) self._sampler.start() return self._sampler def sampler_is_active(self): return self._sampler is not None and self._sampler.active() # Called by samplers when they're finished def _sampler_finished(self, sampler: ProbeEddySampler, **kwargs): if self._sampler is not sampler: raise self._printer.command_error("EDDYng finishing sampler that's not active") self._last_sampler = sampler self._sampler = None if self.save_samples_path is not None: with open(self.save_samples_path, "w") as data_file: times = sampler.times raw_freqs = sampler.raw_freqs freqs = sampler.freqs heights = sampler.heights data_file.write("time,frequency,z,kin_z,kin_v,raw_f,trigger_time,tap_start_time\n") trigger_time = kwargs.get("trigger_time", "") tap_start_time = kwargs.get("tap_start_time", "") for i in range(len(times)): past_pos, past_v = self._get_trapq_position(times[i]) past_k_z = past_pos[2] if past_pos is not None else "" past_v = past_v if past_v is not None else "" data_file.write(f"{times[i]},{freqs[i]},{heights[i] if heights else ''},{past_k_z},{past_v},{raw_freqs[i]},{trigger_time},{tap_start_time}\n") logging.info(f"Wrote {len(times)} samples to {self.save_samples_path}") self.save_samples_path = None def cmd_MESH(self, gcmd: GCodeCommand): self._bed_mesh_helper.scan() cmd_STATUS_help = "Query the last raw coil value and status" def cmd_STATUS(self, gcmd: GCodeCommand): result = self._sensor.read_one_value() status = result.status freqval = result.freqval freq = result.freq height = -math.inf err = "" if freqval > 0x0FFFFFFF: height = -math.inf freq = 0.0 err = f"ERROR: {bin(freqval >> 28)} " elif freq <= 0.0: err += "(Zero frequency) " elif self.calibrated(): height = self.freq_to_height(freq) else: err += "(Not calibrated) " gcmd.respond_info( f"Last coil value: {freq:.2f} ({height:.3f}mm) raw: {hex(freqval)} {err}status: {hex(status)} {self._sensor.status_to_str(status)}" ) cmd_PROBE_ACCURACY_help = "Probe accuracy" def cmd_PROBE_ACCURACY(self, gcmd: GCodeCommand): if not self._z_homed(): raise self._printer.command_error("Must home Z before PROBE_ACCURACY") # How long to read at each sample time duration: float = gcmd.get_float("DURATION", 0.100, above=0.0) # whether to check +/- 1mm positions for accuracy start_z: float = gcmd.get_float("Z", 5.0) offsets: str = gcmd.get("OFFSETS", None) probe_speed = gcmd.get_float("SPEED", self.params.probe_speed, above=0.0) lift_speed = gcmd.get_float("LIFT_SPEED", self.params.lift_speed, above=0.0) probe_zs = [start_z] if offsets is not None: probe_zs.extend([float(v) + start_z for v in offsets.split(",")]) else: probe_zs.extend(np.arange(0.5, start_z, 0.5).tolist()) probe_zs.sort() probe_zs.reverse() # drive current to use old_drive_current = self.current_drive_current() drive_current: int = gcmd.get_int("DRIVE_CURRENT", old_drive_current, minval=0, maxval=31) if not self.calibrated(drive_current): raise self._printer.command_error(f"Drive current {drive_current} not calibrated") th = self._toolhead try: self._sensor.set_drive_current(drive_current) th.manual_move( [None, None, probe_zs[0] + 1.0], lift_speed, ) th.wait_moves() results = [] ranges = [] from_zs = [] stddev_sums = [] stddev_count = 0 for pz in probe_zs: th.manual_move([None, None, pz], probe_speed) th.dwell(0.050) th.wait_moves() result = self.probe_static_height(duration=duration) rangev = result.max_value - result.min_value from_z = result.value - pz stddev_sum = np.sum([(s - result.value) ** 2.0 for s in result.samples]) self._log_msg(f"Probe at z={pz:.3f} is {result}") stddev_sums.append(stddev_sum) stddev_count += len(result.samples) results.append(result) ranges.append(rangev) from_zs.append(from_z) if len(results) > 1: avg_range = np.mean(ranges) avg_from_z = np.mean(from_zs) stddev = (np.sum(stddev_sums) / stddev_count) ** 0.5 gcmd.respond_info(f"Probe spread: {avg_range:.3f}, z deviation: {avg_from_z:.3f}, stddev: {stddev:.3f}") finally: self._sensor.set_drive_current(old_drive_current) th.manual_move( [None, None, start_z], lift_speed, ) cmd_CLEAR_CALIBRATION_help = "Clear calibration for all drive currents" def cmd_CLEAR_CALIBRATION(self, gcmd: GCodeCommand): drive_current: int = gcmd.get_int("DRIVE_CURRENT", -1) if drive_current == -1: self._dc_to_fmap = {} gcmd.respond_info("Cleared calibration for all drive currents") else: if drive_current not in self._dc_to_fmap: raise self._printer.command_error(f"Drive current {drive_current} not calibrated") del self._dc_to_fmap[drive_current] gcmd.respond_info(f"Cleared calibration for drive current {drive_current}") self.save_config() cmd_CALIBRATION_STATUS_help = "Display information about EDDYng calibration" def cmd_CALIBRATION_STATUS(self, gcmd: GCodeCommand): for dc in self._dc_to_fmap: m = self._dc_to_fmap[dc] hmin, hmax = m.height_range fmin, fmax = m.freq_range fspread = m.freq_spread() self._log_msg( f"Drive current {dc}: {hmin:.3f} to {hmax:.3f} ({fmin:.1f} to {fmax:.1f}, {fspread:.2f}%; ftoh_high: {m._ftoh_high is not None})" ) def cmd_SET_TAP_OFFSET(self, gcmd: GCodeCommand): value = gcmd.get_float("VALUE", None) adjust = gcmd.get_float("ADJUST", None) tap_offset = self._tap_offset if value is not None: tap_offset = value if adjust is not None: tap_offset += adjust self._tap_offset = tap_offset gcmd.respond_info(f"Set tap offset: {tap_offset:.3f}") def cmd_SET_TAP_ADJUST_Z(self, gcmd: GCodeCommand): value = gcmd.get_float("VALUE", None) adjust = gcmd.get_float("ADJUST", None) tap_adjust_z = self._tap_adjust_z if value is not None: tap_adjust_z = value if adjust is not None: tap_adjust_z += adjust self._tap_adjust_z = tap_adjust_z if self.params.tap_adjust_z != self._tap_adjust_z: configfile = self._printer.lookup_object("configfile") configfile.set(self._full_name, "tap_adjust_z", str(float(self._tap_adjust_z))) gcmd.respond_info(f"Set tap_adjust_z: {tap_adjust_z:.3f} (SAVE_CONFIG to make it permanent)") def cmd_Z_OFFSET_APPLY_PROBE(self, gcmd: GCodeCommand): gcode_move = self._printer.lookup_object("gcode_move") offset = gcode_move.get_status()["homing_origin"].z offset += self.params.tap_adjust_z offset -= self._last_tap_gcode_adjustment configfile = self._printer.lookup_object("configfile") configfile.set(self._full_name, "tap_adjust_z", f"{offset:.3f}") self._log_msg( f"{self._name}: new tap_adjust_z: {offset:.3f}\n" "The SAVE_CONFIG command will update the printer config file\n" "with the above and restart the printer." ) def probe_static_height(self, duration: float = 0.100) -> ProbeEddyProbeResult: with self.start_sampler() as sampler: now = self._print_time_now() sampler.wait_for_sample_at_time(now + (duration + self._sensor._ldc_settle_time)) sampler.finish() if sampler.height_count == 0: return ProbeEddyProbeResult([]) etime = sampler.times[-1] stime = etime - duration first_idx = bisect.bisect_left(sampler.times, stime) if first_idx == len(sampler.times): raise self._printer.command_error(f"No samples in time range") errors = sampler.error_count return ProbeEddyProbeResult.make(sampler.times[first_idx:], sampler.heights[first_idx:], errors=errors) cmd_PROBE_help = "Probe the height using the eddy current sensor, moving the toolhead to the home trigger height, or Z if specified." def cmd_PROBE(self, gcmd: GCodeCommand): if not self._z_homed(): raise self._printer.command_error("Must home Z before PROBE") z: float = gcmd.get_float("Z", self.params.home_trigger_height) th = self._printer.lookup_object("toolhead") th_pos = th.get_position() if th_pos[2] < z: th.manual_move([None, None, z + 3.0], self.params.lift_speed) th.manual_move([None, None, z], self.params.probe_speed) th.dwell(0.100) th.wait_moves() self.cmd_PROBE_STATIC(gcmd) cmd_PROBE_STATIC_help = "Probe the current height using the eddy current sensor without moving the toolhead." def cmd_PROBE_STATIC(self, gcmd: GCodeCommand): old_drive_current = self.current_drive_current() drive_current: int = gcmd.get_int("DRIVE_CURRENT", old_drive_current, minval=0, maxval=31) duration: float = gcmd.get_float("DURATION", 0.100, above=0.0) save: bool = gcmd.get_int("SAVE", 0) == 1 home_z: bool = gcmd.get_int("HOME_Z", 0) == 1 if not self.calibrated(drive_current): raise self._printer.command_error(f"Drive current {drive_current} not calibrated") try: self._sensor.set_drive_current(drive_current) if save: self.save_samples_path = "/tmp/eddy-probe-static.csv" r = self.probe_static_height(duration) if self._cmd_helper is not None: self._cmd_helper.last_z_result = float(r.value) self._last_probe_result = float(r.value) if home_z: th = self._printer.lookup_object("toolhead") th_pos = th.get_position() th_pos[2] = r.value self._set_toolhead_position(th_pos, [2]) self._log_debug(f"Homed Z to {r}") else: self._log_msg(f"Probed {r}") finally: self._sensor.set_drive_current(old_drive_current) cmd_SETUP_help = "Setup" def cmd_SETUP(self, gcmd: GCodeCommand): if not self._xy_homed(): raise self._printer.command_error("X and Y must be homed before setup") if self._z_homed(): # z-hop so that manual probe helper doesn't complain if we're already # at the right place self._z_hop() # Now reset the axis so that we have a full range to calibrate with th = self._printer.lookup_object("toolhead") th_pos = th.get_position() # XXX This is proably not correct for some printers? zrange = th.get_kinematics().rails[2].get_range() th_pos[2] = zrange[1] - 20.0 self._set_toolhead_position(th_pos, [2]) manual_probe.ManualProbeHelper( self._printer, gcmd, lambda kin_pos: self.cmd_SETUP_next(gcmd, kin_pos), ) def cmd_SETUP_next(self, gcmd: GCodeCommand, kin_pos: Optional[List[float]]): if kin_pos is None: # User cancelled ManualProbeHelper self._z_not_homed() return debug = 1 if self.params.debug else 0 debug = gcmd.get_int("DEBUG", debug) == 1 # We just did a ManualProbeHelper, so we're going to zero the z-axis # to make the following code easier, so it can assume z=0 is actually real zero. th = self._printer.lookup_object("toolhead") th_pos = th.get_position() th_pos[2] = 0.0 self._set_toolhead_position(th_pos, [2]) # Note that the default is the default drive current drive_current: int = gcmd.get_int( "DRIVE_CURRENT", self._sensor._default_drive_current, minval=0, maxval=31, ) max_dc_increase = 0 if self._sensor_type == "ldc1612" or self._sensor_type == "btt_eddy" or self._sensor_type == "ldc1612_internal_clk": max_dc_increase = 5 max_dc_increase = gcmd.get_int("MAX_DC_INCREASE", max_dc_increase, minval=0, maxval=30) # lift up above cal_z_max, and then move over so the probe # is over the nozzle position th.manual_move( [None, None, self.params.calibration_z_max + 3.0], self.params.lift_speed, ) th.manual_move( [ th_pos[0] - self.offset["x"], th_pos[1] - self.offset["y"], None, ], self.params.move_speed, ) # This is going to automate setup. # The setup state machine looks like this: # 1. Finding homing drive current # 2. Finding tapping drive current FINDING_HOMING = 1 FINDING_TAP = 2 DONE = 3 start_drive_current = drive_current result_msg = None self._log_msg("setup: calibrating homing") state = FINDING_HOMING while state < DONE: mapping, fth_rms, htf_rms = self._create_mapping( self.params.calibration_z_max, 0.0, # z_target self.params.probe_speed, self.params.lift_speed, drive_current, report_errors=debug, write_debug_files=debug, ) homing_req_min = 0.5 homing_req_max = 5.0 tap_req_min = 0.025 tap_req_max = 3.0 ok_for_homing = mapping is not None ok_for_tap = mapping is not None if ok_for_homing and (mapping.height_range[0] > homing_req_min or mapping.height_range[1] < homing_req_max): ok_for_homing = False if ok_for_tap and (mapping.height_range[0] > tap_req_min or mapping.height_range[1] < tap_req_max): ok_for_tap = False if ok_for_homing or ok_for_tap: self._log_info(f"dc {drive_current} homing {ok_for_homing} tap {ok_for_tap}, {fth_rms} {htf_rms}") if mapping.freq_spread() < 0.30: self._log_warning( f"frequency spread {mapping.freq_spread()} is very low at drive current {drive_current}. (The sensor is probably mounted too high; the height includes any case thickness.)" ) ok_for_homing = ok_for_tap = False if fth_rms is None or fth_rms > 0.025: self._log_msg(f"calibration error rate is too high ({fth_rms}) at drive current {drive_current}.") ok_for_homing = ok_for_tap = False if state == FINDING_HOMING and ok_for_homing: self._dc_to_fmap[drive_current] = mapping self._reg_drive_current = drive_current self._log_msg(f"using {drive_current} for homing.") state = FINDING_TAP if state == FINDING_TAP and ok_for_tap: self._dc_to_fmap[drive_current] = mapping self._tap_drive_current = drive_current self._log_msg(f"using {drive_current} for tap.") state = DONE if state == DONE: result_msg = "Setup success. Please check whether homing works with G28 Z, then check if tap works with PROBE_EDDY_NG_TAP." break if drive_current - start_drive_current >= max_dc_increase: # we've failed completely if state == FINDING_HOMING: result_msg = "Failed to find homing drive current. (Have you checked the sensor height?)" elif state == FINDING_TAP: result_msg = "Failed to find tap drive current, but homing is set up. (Have you checked the sensor height?)" else: result_msg = "Unknown state?" break # increase DC and keep going drive_current += 1 if state == DONE: self._log_msg(result_msg) else: self._log_error(result_msg) if state > FINDING_HOMING: self.reset_drive_current() self.save_config() self._z_not_homed() cmd_CALIBRATE_help = ( "Calibrate the eddy current sensor. Specify DRIVE_CURRENT to calibrate for a different drive current " + "than the default. Specify START_Z to set a different calibration start point." ) def cmd_CALIBRATE(self, gcmd: GCodeCommand): if not self._xy_homed(): raise self._printer.command_error("X and Y must be homed before calibrating") if self._z_homed(): # z-hop so that manual probe helper doesn't complain if we're already # at the right place self._z_hop() # Now reset the axis so that we have a full range to calibrate with th = self._printer.lookup_object("toolhead") th_pos = th.get_position() # XXX This is proably not correct for some printers? zrange = th.get_kinematics().rails[2].get_range() th_pos[2] = zrange[1] - 20.0 self._set_toolhead_position(th_pos, [2]) manual_probe.ManualProbeHelper( self._printer, gcmd, lambda kin_pos: self.cmd_CALIBRATE_next(gcmd, kin_pos), ) def cmd_CALIBRATE_next(self, gcmd: GCodeCommand, kin_pos: Optional[List[float]]): th = self._printer.lookup_object("toolhead") if kin_pos is None: # User cancelled ManualProbeHelper self._z_not_homed() return old_drive_current = self.current_drive_current() drive_current: int = gcmd.get_int("DRIVE_CURRENT", old_drive_current, minval=0, maxval=31) cal_z_max: float = gcmd.get_float("START_Z", self.params.calibration_z_max, above=2.0) z_target: float = gcmd.get_float("TARGET_Z", 0.0) probe_speed: float = gcmd.get_float("SPEED", self.params.probe_speed, above=0.0) lift_speed: float = gcmd.get_float("LIFT_SPEED", self.params.lift_speed, above=0.0) # We just did a ManualProbeHelper, so we're going to zero the z-axis # to make the following code easier, so it can assume z=0 is actually real zero. # The Eddy sensor calibration is done to nozzle height (not sensor or trigger height). th_pos = th.get_position() th_pos[2] = 0.0 self._set_toolhead_position(th_pos, [2]) th.wait_moves() self._log_debug(f"calibrating from {kin_pos}, {th_pos}") # lift up above cal_z_max, and then move over so the probe # is over the nozzle position th.manual_move([None, None, cal_z_max + 3.0], lift_speed) th.manual_move( [ th_pos[0] - self.offset["x"], th_pos[1] - self.offset["y"], None, ], self.params.move_speed, ) mapping, fth_fit, htf_fit = self._create_mapping( cal_z_max, z_target, probe_speed, lift_speed, drive_current, report_errors=True, write_debug_files=True, ) if mapping is None or fth_fit is None or htf_fit is None: self._log_error("Calibration failed") return self._dc_to_fmap[drive_current] = mapping self.save_config() # reset the Z homing state after alibration self._z_not_homed() def _create_mapping( self, z_start: float, z_target: float, probe_speed: float, lift_speed: float, drive_current: int, report_errors: bool, write_debug_files: bool, ) -> Tuple[ProbeEddyFrequencyMap, float, float]: th = self._printer.lookup_object("toolhead") th_pos = th.get_position() # move to the start z of the mapping, going up first if we need to for backlash if th_pos[2] < z_start: th.manual_move([None, None, z_start + 3.0], lift_speed) th.manual_move([None, None, z_start], lift_speed) old_drive_current = self.current_drive_current() try: self._sensor.set_drive_current(drive_current) times, freqs, heights, vels = self._capture_samples_down_to(z_target, probe_speed) th.manual_move([None, None, z_start + 3.0], lift_speed) finally: self._sensor.set_drive_current(old_drive_current) if times is None: if report_errors: self._log_error(f"Drive current {drive_current}: No samples collected. This could be a hardware issue or an incorrect drive current.") else: self._log_warning(f"Drive current {drive_current}: Warning: no samples collected.") return None, None, None # and build a map mapping = ProbeEddyFrequencyMap(self) fth_fit, htf_fit = mapping.calibrate_from_values( drive_current, times, freqs, heights, vels, report_errors, write_debug_files, ) return mapping, fth_fit, htf_fit def _capture_samples_down_to(self, z_target: float, probe_speed: float) -> tuple[List[float], List[float], List[float], List[float]]: th = self._printer.lookup_object("toolhead") th.dwell(0.500) # give the sensor a bit to settle th.wait_moves() with self.start_sampler(calculate_heights=False) as sampler: first_sample_time = th.get_last_move_time() th.manual_move([None, None, z_target], probe_speed) last_sample_time = th.get_last_move_time() # Can't use wait_for_sample_at_time here, because the tail end of # samples might be errors so they won't be passed to the sampler. # Should fix that, but for now just wait an extra half second which # should be more than enough. # sampler.wait_for_sample_at_time(last_sample_time) th.dwell(0.500) th.wait_moves() sampler.finish() # the samples are a list of [print_time, freq, dummy_height] tuples if sampler.raw_count == 0: return None, None, None, None freqs = [] heights = [] times = [] vels = [] for i in range(sampler.raw_count): s_t = sampler.times[i] s_freq = sampler.freqs[i] s_pos, s_v = self._get_trapq_position(s_t) s_z = s_pos[2] if first_sample_time < s_t < last_sample_time and s_z >= z_target: times.append(s_t) freqs.append(s_freq) heights.append(s_z) vels.append(s_v) return times, freqs, heights, vels def cmd_TEST_DRIVE_CURRENT(self, gcmd: GCodeCommand): drive_current: int = gcmd.get_int("DRIVE_CURRENT", self._reg_drive_current, minval=1, maxval=31) z_start: float = gcmd.get_float("START_Z", self.params.calibration_z_max, above=2.0) z_end: float = gcmd.get_float("TARGET_Z", 0.0) debug: bool = gcmd.get_int("DEBUG", 0) == 1 self._log_msg(f"Testing Z={z_start:.3f} to Z={z_end:.3f}") mapping, fth, htf = self._create_mapping( z_start, z_end, self.params.probe_speed, self.params.lift_speed, drive_current, report_errors=False, write_debug_files=debug, ) if mapping is None or fth is None or htf is None: self._log_error(f"Test failed: drive current {drive_current} is not usable.") # # PrinterProbe interface # def get_offsets(self, *args, **kwargs): # the z offset is the trigger height, because the probe will trigger # at z=trigger_height (not at z=0) return ( self.offset["x"], self.offset["y"], self.params.home_trigger_height, ) def get_probe_params(self, gcmd=None): return { "probe_speed": self.params.probe_speed, "lift_speed": self.params.lift_speed, "sample_retract_dist": 0.0, } def start_probe_session(self, gcmd): session = ProbeEddyScanningProbe(self, gcmd) session._start_session() return session # method = gcmd.get('METHOD', 'automatic').lower() # if method in ('scan', 'rapid_scan'): # session = ProbeEddyScanningProbe(self, gcmd) # session._start_session() # return session # # return self._probe_session.start_probe_session(gcmd) def get_status(self, eventtime): if self._cmd_helper is not None: status = self._cmd_helper.get_status(eventtime) else: status = dict() status.update( { "name": self._full_name, "home_trigger_height": float(self.params.home_trigger_height), "tap_offset": float(self._tap_offset), "tap_adjust_z": float(self._tap_adjust_z), "last_probe_result": float(self._last_probe_result), "last_tap_z": float(self._last_tap_z), } ) return status # Old Probe interface, for Kalico def get_lift_speed(self, gcmd=None): if gcmd is not None: return gcmd.get_float("LIFT_SPEED", self.params.lift_speed, above=0.0) return self.params.lift_speed def multi_probe_begin(self): pass def multi_probe_end(self): pass # This is a mishmash of cmd_PROBE and cmd_PROBE_STATIC. This run_probe # is the old one, different than the scanning session run_probe. def run_probe(self, gcmd=None, *args: Any, **kwargs: Any): z = self.params.home_trigger_height duration = 0.100 if not self._z_homed(): raise self._printer.command_error("Must home Z before PROBE") if not self.calibrated(): raise self._printer.command_error("Eddy probe not calibrated!") th = self._printer.lookup_object("toolhead") th_pos = th.get_position() if th_pos[2] < z: th.manual_move([None, None, z + 3.0], self.params.lift_speed) th.manual_move([None, None, z], self.params.lift_speed) th.dwell(0.100) th.wait_moves() r = self.probe_static_height(duration) if not r.valid: raise self._printer.command_error("Probe captured no samples!") height = r.value height += self._tap_offset # At what Z position would the toolhead be at for the probe to read # _home_trigger_height? In other words, if the probe tells us # the height is 1.5 when the toolhead is at z=2.0, if the toolhead # was moved up to 2.5, then the probe should read 2.0. probe_z = z + (z - height) return [th_pos[0], th_pos[1], probe_z] # # Moving the sensor to the correct position # def _probe_to_start_position_unhomed(self, move_home=False): if not self._xy_homed(): raise self._printer.command_error("xy must be homed") if not self.sampler_is_active(): raise self._printer.command_error("probe_to_start_position_unhomed: no sampler active") if not self.calibrated(): raise self._printer.command_error("EDDYng not calibrated!") th = self._printer.lookup_object("toolhead") th_pos = th.get_position() # debug logging th_kin = th.get_kinematics() zlim = th_kin.limits[2] rail_range = th_kin.rails[2].get_range() self._log_debug( f"probe to start unhomed: before movement: Z pos {th_pos[2]:.3f}, " f"Z limits {zlim[0]:.2f}-{zlim[1]:.2f}, " f"rail range {rail_range[0]:.2f}-{rail_range[1]:.2f}" ) start_height_ok_factor = 0.100 # This is where we want to get to start_height = self._home_start_height # This is where the probe thinks we are now_height = self._sampler.get_height_now() # If we can't get a value at all for right now, for safety, just abort. if now_height is None: raise self._printer.command_error("Couldn't get any valid samples from sensor.") self._log_debug(f"probe_to_start_position_unhomed: now: {now_height} (start {start_height})") if abs(now_height - start_height) <= start_height_ok_factor: return th = self._printer.lookup_object("toolhead") th_pos = th.get_position() # If the sensor thinks we're too low we need to move back up before homing if now_height < start_height: move_up_by = min(start_height, start_height - now_height) # give ourselves some room to do so, homing typically doesn't move up, # and we should know that we have this room because the sensor tells us we're too low th_pos[2] = rail_range[1] - (move_up_by + 10.0) self._log_debug(f"probe_to_start_position_unhomed: resetting toolhead to z {th_pos[2]:.3f}") self._set_toolhead_position(th_pos, [2]) n_pos = th.get_position() zlim = th_kin.limits[2] rail_range = th_kin.rails[2].get_range() self._log_debug( f"after reset: Z pos {n_pos[2]:.3f}, Z limits {zlim[0]:.2f}-{zlim[1]:.2f}, rail range {rail_range[0]:.2f}-{rail_range[1]:.2f}" ) th_pos[2] += move_up_by self._log_debug(f"probe_to_start_position_unhomed: moving toolhead up by {move_up_by:.3f} to {th_pos[2]:.3f}") th.manual_move([None, None, th_pos[2]], self.params.probe_speed) # TODO: this should just be th.wait_moves() self._sampler.wait_for_sample_at_time(th.get_last_move_time()) def probe_to_start_position(self, z_pos=None): self._log_debug(f"probe_to_start_position (tt: {self.params.tap_threshold}, z-homed: {self._z_homed()})") # If we're not homed at all, rely on the sensor values to bring us to # a good place to start a diving probe from if not self._z_homed(): if z_pos is not None: raise self._printer.command_error("Can't probe_to_start_position with an explicit Z without homed Z") self._probe_to_start_position_unhomed() return th = self._printer.lookup_object("toolhead") th.wait_moves() th_pos = th.get_position() # Note home_trigger_height and not home_start_height: if we're homed, # we don't need to do another dive and we just want to move to # the right position for probing. if z_pos is not None: start_z = z_pos else: start_z = self.params.home_trigger_height # If we're below, move up a bit beyond and the back down # to compensate for backlash if th_pos[2] < start_z: self._log_debug(f"probe_to_start_position: moving toolhead from {th_pos[2]:.3f} to {(start_z + 1.0):.3f}") th_pos[2] = start_z + 1.0 th.manual_move(th_pos, self.params.lift_speed) self._log_debug(f"probe_to_start_position: moving toolhead from {th_pos[2]:.3f} to {start_z:.3f}") th_pos[2] = start_z th.manual_move(th_pos, self.params.probe_speed) th.wait_moves() # # Tap probe # cmd_TAP_help = "Calculate a z-offset by touching the build plate." def cmd_TAP(self, gcmd: GCodeCommand): drive_current = self._sensor.get_drive_current() try: self.cmd_TAP_next(gcmd) finally: self._sensor.set_drive_current(drive_current) @dataclass class TapResult: error: Optional[Exception] probe_z: float toolhead_z: float overshoot: float tap_time: float tap_start_time: float tap_end_time: float @dataclass class TapConfig: mode: str threshold: float sos: Optional[List[List[float]]] = None def do_one_tap( self, start_z: float, target_z: float, tap_speed: float, lift_speed: float, tapcfg: ProbeEddy.TapConfig, ) -> TapResult: self.probe_to_start_position(start_z) th = self._printer.lookup_object("toolhead") target_position = th.get_position() target_position[2] = target_z error = None try: # configure the endstop for tap (gets reset at the end of a tap sequence, # also in finally just in case self._endstop_wrapper.tap_config = tapcfg endstops = [(self._endstop_wrapper, "probe")] hmove = HomingMove(self._printer, endstops) try: probe_position = hmove.homing_move(target_position, tap_speed, probe_pos=True) # raise toolhead as soon as tap ends finish_z = th.get_position()[2] if finish_z < 1.0: th.manual_move([None, None, start_z], lift_speed) if hmove.check_no_movement() is not None: raise self._printer.command_error("Probe triggered prior to movement") probe_z = probe_position[2] self._log_debug(f"tap: probe_z: {probe_z:.3f} finish_z: {finish_z:.3f} moved up to {start_z:.3f}") if probe_z - target_z < 0.050: # we detected a tap but it was too close to our target z # to be trusted # TODO: use velocity to determine this return ProbeEddy.TapResult( error=Exception("Tap detected too close to target z"), toolhead_z=finish_z, probe_z=probe_z, overshoot=0.0, tap_time=0.0, tap_start_time=0.0, tap_end_time=0.0, ) except self._printer.command_error as err: if self._printer.is_shutdown(): raise self._printer.command_error("Probing failed due to printer shutdown") # in case of failure don't leave the toolhead in a bad spot (i.e. in bed) finish_z = th.get_position()[2] if finish_z < 1.0: th.manual_move([None, None, start_z], lift_speed) # If just sensor errors, let the caller handle it self._log_error(f"Tap failed with Z at {finish_z:.3f}: {err}") if "Sensor error" or "Probe completed movement" or "Probe triggered prior" in str(err): return ProbeEddy.TapResult( error=err, toolhead_z=finish_z, probe_z=0.0, overshoot=0.0, tap_time=0.0, tap_start_time=0.0, tap_end_time=0.0, ) else: raise finally: self._endstop_wrapper.tap_config = None # The toolhead ended at finish_z, but probe_z is the actual zero. # finish_z should be below or equal to probe_z because there will always be # a bit of overshoot due to trigger delay, and because we actually # fire the trigger later than when the tap starts (and the tap start # time is what's used to compute probe_position) if finish_z > probe_z: raise self._printer.command_error(f"Unexpected: finish_z {finish_z:.3f} is above probe_z {probe_z:.3f} after tap") # How much the toolhead overshot the real z=0 position. This is the amount # the toolhead is pushing into the build plate. overshoot = probe_z - finish_z tap_start_time = self._endstop_wrapper.last_tap_start_time tap_end_time = self._endstop_wrapper.last_trigger_time tap_time = tap_start_time + (tap_end_time - tap_start_time) * self.params.tap_time_position return ProbeEddy.TapResult( error=error, probe_z=probe_z, toolhead_z=finish_z, overshoot=overshoot, tap_time=tap_time, tap_start_time=tap_start_time, tap_end_time=tap_end_time, ) def _compute_butter_tap(self, sampler): if not scipy: return None, None trigger_freq = self.height_to_freq(self.params.home_trigger_height) s_f = np.asarray(sampler.freqs) first_one = np.argmax(s_f >= trigger_freq) s_t = np.asarray(sampler.times[first_one:]) s_f = np.asarray(sampler.freqs[first_one:]) lowcut = self.params.tap_butter_lowcut highcut = self.params.tap_butter_highcut order = self.params.tap_butter_order sos = scipy.signal.butter( order, [lowcut, highcut], btype="bandpass", fs=self._sensor._data_rate, output="sos", ) filtered = scipy.signal.sosfilt(sos, s_f - s_f[0]) return s_t, filtered def cmd_TAP_next(self, gcmd: Optional[GCodeCommand] = None): self._log_debug("\nEDDYng Tap begin") if gcmd is None: gcmd = self._dummy_gcode_cmd orig_drive_current: int = self._sensor.get_drive_current() tap_drive_current: int = gcmd.get_int( name="DRIVE_CURRENT", default=self._tap_drive_current, minval=1, maxval=31, ) tap_speed: float = gcmd.get_float("SPEED", self.params.tap_speed, above=0.0) lift_speed: float = gcmd.get_float("RETRACT_SPEED", self.params.lift_speed, above=0.0) tap_start_z: float = gcmd.get_float("START_Z", self.params.tap_start_z, above=2.0) target_z: float = gcmd.get_float("TARGET_Z", self.params.tap_target_z) tap_threshold: float = gcmd.get_float("THRESHOLD", None) # None so we have a sentinel value tap_threshold = gcmd.get_float("TT", tap_threshold) # alias for THRESHOLD tap_adjust_z = gcmd.get_float("ADJUST_Z", self._tap_adjust_z) do_retract = gcmd.get_int("RETRACT", 1) == 1 samples = gcmd.get_int("SAMPLES", self.params.tap_samples, minval=1) max_samples = gcmd.get_int("MAX_SAMPLES", self.params.tap_max_samples, minval=samples) samples_stddev = gcmd.get_float("SAMPLES_STDDEV", self.params.tap_samples_stddev, above=0.0) use_median: bool = gcmd.get_int("USE_MEDIAN", 1 if self.params.tap_use_median else 0) == 1 home_z: bool = gcmd.get_int("HOME_Z", 1) == 1 write_plot_arg: int = gcmd.get_int("PLOT", None) mode = gcmd.get("MODE", self.params.tap_mode).lower() if mode not in ("wma", "butter"): raise self._printer.command_error(f"Invalid mode: {mode}") # if the mode is different than the params, then require # specifying threshold if tap_threshold is None: if mode != self.params.tap_mode: raise self._printer.command_error( f"THRESHOLD required when mode ({mode}) is different than configured default ({self.params.tap_mode})" ) tap_threshold = self.params.tap_threshold if not self._z_homed(): raise self._printer.command_error("Z axis must be homed before tapping") write_tap_plot = self.params.write_tap_plot write_every_tap_plot = self.params.write_every_tap_plot and write_tap_plot if write_plot_arg is not None: write_tap_plot = write_plot_arg > 0 write_every_tap_plot = write_plot_arg > 1 tapcfg = ProbeEddy.TapConfig(mode=mode, threshold=tap_threshold) # fmt: off if mode == "butter": if self.params.is_default_butter_config() and self._sensor._data_rate == 250: sos = [ [ 0.046131802093312926, 0.09226360418662585, 0.046131802093312926, 1.0, -1.3297767184682712, 0.5693902189294331, ], [ 1.0, -2.0, 1.0, 1.0, -1.845000600983779, 0.8637525213328747, ], ] elif self.params.is_default_butter_config() and self._sensor._data_rate == 500: sos = [ [ 0.013359200027856505, 0.02671840005571301, 0.013359200027856505, 1.0, -1.686278256753083, 0.753714473246724, ], [ 1.0, -2.0, 1.0, 1.0, -1.9250515947328444, 0.9299234737648037, ], ] elif scipy: sos = scipy.signal.butter( self.params.tap_butter_order, [ self.params.tap_butter_lowcut, self.params.tap_butter_highcut, ], btype="bandpass", fs=self._sensor._data_rate, output="sos", ).tolist() else: raise self._printer.command_error("Scipy is not available, cannot use custom filter, or data rate is not 250 or 500") tapcfg.sos = sos # fmt: on results = [] tap_z = None tap_stddev = None tap_overshoot = None sample_err_count = 0 tap = None try: self._sensor.set_drive_current(tap_drive_current) sample_last_err = None for sample_i in range(max_samples): if self.params.debug: self.save_samples_path = f"/tmp/tap-samples-{sample_i+1}.csv" tap = self.do_one_tap( start_z=tap_start_z, target_z=target_z, tap_speed=tap_speed, lift_speed=lift_speed, tapcfg=tapcfg, ) if write_every_tap_plot: try: self._write_tap_plot(tap, sample_i) except Exception as e: self._log_error(f"Failed to write tap plot: {e}") if tap.error: if "too close to target z" in str(tap.error): self._log_msg(f"Tap {sample_i+1}: failed: try lowering TARGET_Z by 0.100 (to {target_z - 0.100:.3f})") else: self._log_msg(f"Tap {sample_i+1}: failed ({tap.error})") sample_err_count += 1 sample_last_err = tap continue results.append(tap) self._log_msg(f"Tap {sample_i+1}: z={tap.probe_z:.3f}") self._log_debug( f"tap[{sample_i+1}]: {tap.probe_z:.3f} toolhead at: {tap.toolhead_z:.3f} overshoot: {tap.overshoot:.3f} at {tap.tap_time:.4f}s" ) if samples == 1: # only one sample, we're done tap_z = tap.probe_z tap_stddev = 0.0 tap_overshoot = tap.overshoot break if len(results) >= samples: tap_z, tap_stddev, tap_overshoot = self._compute_tap_z(results, samples, samples_stddev, use_median) if tap_z is not None: break finally: self.reset_drive_current() if write_tap_plot and not write_every_tap_plot and tap: try: self._write_tap_plot(tap) except Exception as e: self._log_error(f"Failed to write tap plot: {e}") th = self._toolhead # If we didn't compute a tap_z report the error if tap_z is None: # raise toolhead on failed tap th.manual_move([None, None, tap_start_z], lift_speed) err_msg = "Tap failed:" if tap_stddev is not None: err_msg += f" stddev {tap_stddev:.3f} > {samples_stddev:.3f}." err_msg += " Consider adjusting tap_samples, tap_max_samples, or tap_samples_stddev." if sample_err_count > 0: err_msg += f" {sample_err_count} errors, last: {sample_last_err.error} at toolhead z={sample_last_err.toolhead_z:.3f}" self._log_error(err_msg) raise self._printer.command_error("Tap failed") # Adjust the computed tap_z by the user's tap_adjust_z, typically to raise # it to account for flex in the system (otherwise the Z would be too low) computed_tap_z = adjusted_tap_z = tap_z + tap_adjust_z self._last_tap_z = float(tap_z) homed_to_str = "" if home_z: th_pos = th.get_position() th_z = th_pos[2] #true_z_zero = - (tap_adjust_z + tap_overshoot) true_z_zero = - computed_tap_z th_pos[2] = th_pos[2] + true_z_zero homed_to_str = f"homed z with true_z_zero={true_z_zero:.3f}, thz={th_z:.3f}, setz={th_pos[2]:.3f}, overshoot={tap_overshoot:.3f}, " self._set_toolhead_position(th_pos, [2]) self._last_tap_gcode_adjustment = 0.0 adjusted_tap_z = 0.0 gcode_move = self._printer.lookup_object("gcode_move") gcode_delta = adjusted_tap_z - gcode_move.homing_position[2] gcode_move.base_position[2] += gcode_delta gcode_move.homing_position[2] = adjusted_tap_z self._last_tap_gcode_adjustment = adjusted_tap_z # # Figure out the offset to apply to sensor readings at the home trigger height # for future probes. # # This is actually unrelated to tap, but is related to temperature compensation. # Bed mesh is going to read values relative to the probe's z_offset (home_trigger_height). # But we can't trust the probe's values directly, because of temperature effects. # # What we can do though is move the toolhead to that height, take a probe reading, # then save the delta there to apply as an offset for bed mesh in the future. # That makes this bed height effectively "0", which is fine, because this is # what we did tap at to get a height zero reading. # # Toolhead moves are absolute; they don't take into account the gcode offset. # Probes happen at absolute z=z_offset, so this doesn't take into account the # tap_z computed above. This does mean that the actual physical height probing happens at # is not likely to be exactly the same as the Z position, but all we care about is # variance from that position so this should be fine. self._sensor.set_drive_current(orig_drive_current) th_now = th.get_position() th.manual_move([None, None, self.params.home_trigger_height + 1.0], lift_speed) th.manual_move([th_now[0] - self.params.x_offset, th_now[1] - self.params.y_offset, None], self.params.move_speed) th.manual_move([None, None, self.params.home_trigger_height], self.params.probe_speed) th.dwell(0.500) th.wait_moves() result = self.probe_static_height() self._tap_offset = float(self.params.home_trigger_height - result.value) self._log_msg( f"Probe computed tap at {computed_tap_z:.3f} (tap at z={tap_z:.3f}, " f"stddev {tap_stddev:.3f}) with {samples} samples, {homed_to_str}" f"sensor offset {self._tap_offset:.3f} at z={self.params.home_trigger_height:.3f}" ) if do_retract: th.manual_move([None, None, self._home_start_height], lift_speed) th.wait_moves() th.flush_step_generation() self._log_debug("EDDYng Tap end\n") # Compute the average tap_z from a set of tap results, taking a cluster of samples # from the result that has the lowest standard deviation def _compute_tap_z(self, taps: List[ProbeEddy.TapResult], samples: int, req_stddev: float, use_median: bool) -> Tuple[float, float, float]: if len(taps) < samples: return None, None, None tap_z = math.inf std_min = math.inf overshoot = math.inf for cluster in combinations(taps, samples): tap_zs = np.array([t.probe_z for t in cluster]) overshoots = np.array([t.overshoot for t in cluster]) std = np.std(tap_zs) if std < std_min: std_min = std if use_median: # we need the corresponding overshoot as well, so # can't just use np.median(). sorted_indices = np.argsort(tap_zs) idx = len(tap_zs) // 2 tap_z = tap_zs[sorted_indices[idx]] overshoot = overshoots[sorted_indices[idx]] else: tap_z = np.mean(tap_zs) overshoot = np.mean(overshoots) if std_min <= req_stddev: return float(tap_z), float(std_min), float(overshoot) else: return None, float(std_min), None # Write a tap plot. This also has logic to compute the averages # and the filter mostly-exactly how it's done on the probe MCU itself # (vs using numpy or similar) to make these graphs more reprensetative def _write_tap_plot(self, tap: ProbeEddy.TapResult, tapnum: int = -1): if not plotly: return if tapnum == -1: filename_base = "tap" else: filename_base = f"tap-{tapnum+1}" tapplot_path_png = f"/tmp/{filename_base}.png" tapplot_path_html = f"/tmp/{filename_base}.html" # delete any old plots to avoid confusion if tapplot_path_html and os.path.exists(tapplot_path_html): os.remove(tapplot_path_html) if tapplot_path_png and os.path.exists(tapplot_path_png): os.remove(tapplot_path_png) if not self._last_sampler or not self._last_sampler.times: return s_t = np.asarray(self._last_sampler.times) s_f = np.asarray(self._last_sampler.freqs) s_z = np.asarray(self._last_sampler.heights) s_kinz = np.vectorize(lambda t: self._get_trapq_height(t) or -10)(s_t) # Any values below 0.0 are suspect because they were not calibrated, # and so are just extrapolated from the fit. Show them differently. s_lowz = np.ma.masked_where(s_z >= 0, s_z) s_z = np.ma.masked_where(s_z < 0, s_z) time_start = s_t.min() # normalize times to start at 0 s_t = s_t - time_start tap_start_time = self._last_sampler.memos.get("tap_start_time", time_start) - time_start tap_end_time = self._last_sampler.memos.get("trigger_time", time_start) - time_start trigger_time = tap_start_time + (tap_end_time - tap_start_time) * self.params.tap_time_position tap_threshold = self._last_sampler.memos.get("tap_threshold", 0) time_len = s_t.max() # compute the butterworth filter, if we have scipy if tap is not None and scipy: butter_s_t, butter_s_v = self._compute_butter_tap(self._last_sampler) butter_s_t = butter_s_t - time_start else: butter_s_t = butter_s_v = None # Do this roughly how the C code does it, to keep the values identical # TODO Just report the value from the mcu? butter_accum = None if butter_s_v is not None: # Note: we don't handle freq offset or # start this at same point as the C code does butter_accum = np.zeros(len(butter_s_v)) last_value = butter_s_v[0] falling = False accum_val = 0.0 for bi, bv in enumerate(butter_s_v): if bv <= last_value: falling = True accum_val += last_value - bv elif falling and bv > last_value: falling = False accum_val = 0.0 butter_accum[bi] = accum_val last_value = bv import plotly.graph_objects as go (c_red, c_lt_red) = ('#9e4058', '#C2697F') (c_orange, c_lt_orange) = ('#d0641e', '#E68E54') (c_yellow, c_lt_yellow) = ('#f9ab0e', '"#FBC559') (c_green, c_lt_green) = ('#589e40', '#7FC269') (c_blue, c_lt_blue) = ('#2c3778', '#4151B0') (c_purple, c_lt_purple) = ('#513965', '#785596') fig = go.Figure() # fmt: off if tap_start_time > 0: fig.add_shape(type="line", x0=tap_start_time, x1=tap_start_time, y0=0, y1=1, xref="x", yref="paper", line=dict(color=c_purple, width=2),) if trigger_time > 0: fig.add_shape(type="line", x0=trigger_time, x1=trigger_time, y0=0, y1=1, xref="x", yref="paper", line=dict(color=c_lt_orange, width=2),) if tap_end_time > 0: fig.add_shape(type="line", x0=tap_end_time, x1=tap_end_time, y0=0, y1=1, xref="x", yref="paper", line=dict(color=c_purple, width=2),) if tap_threshold > 0: fig.add_shape(type="line", x0=0, x1=1, y0=tap_threshold, y1=tap_threshold, xref="paper", yref="y3", line=dict(color="gray", width=1, dash="dash"),) fig.add_shape(type="line", x0=0, x1=1, y0=tap.probe_z, y1=tap.probe_z, xref="paper", yref="y", line=dict(color=c_lt_orange, width=1),) # Computed Z, Toolhead Z, Sensor F fig.add_trace(go.Scatter(x=s_t, y=s_z, mode="lines", name="Z", line=dict(color=c_blue))) fig.add_trace(go.Scatter(x=s_t, y=s_lowz, mode="lines", name="Z (low)", line=dict(color=c_lt_blue, dash="dash"))) fig.add_trace(go.Scatter(x=s_t, y=s_kinz, mode="lines", name="KinZ", line=dict(color=c_lt_red))) fig.add_trace(go.Scatter(x=s_t, y=s_f, mode="lines", name="Freq", yaxis="y2", line=dict(color=c_orange))) # the butter tap if we have the data if butter_s_t is not None: fig.add_trace(go.Scatter(x=butter_s_t, y=butter_s_v, mode="lines", name="signal", yaxis="y4", line=dict(color=c_green))) fig.add_trace(go.Scatter(x=butter_s_t, y=butter_accum, mode="lines", name="threshold", yaxis="y3", line=dict(color="#626b73"))) fig.update_xaxes(range=[max(0.0, time_len - 0.60), time_len], autorange=False) fig.update_layout( hovermode="x unified", title=dict(text=f"Tap {tapnum+1}: {tap.probe_z:.3f}"), yaxis=dict(title="Z", side="right"), # Z axis yaxis2=dict(overlaying="y", title="Freq", tickformat="d", side="left"), # Freq + WMA yaxis3=dict(overlaying="y", side="left", tickformat="d", position=0.2), # derivatives, tap accum yaxis4=dict(overlaying="y", side="right", showticklabels=False), # filter height=800, ) # fmt: on timg = 0.0 thtml = 0.0 if tapplot_path_png: t0 = time.time() try: fig.write_image(tapplot_path_png) except: tapplot_path_png = None timg = time.time() - t0 if tapplot_path_html: t0 = time.time() fig.write_html(tapplot_path_html, include_plotlyjs="cdn") thtml = time.time() - t0 self._log_info(f"Wrote tap plot to {tapplot_path_png or ''} {tapplot_path_html or ''} [took {timg:.1f}, {thtml:.1f}]") def cmd_START_STREAM(self, gcmd): self.save_samples_path = "/tmp/stream.csv" self._log_info("Eddy sampling enabled") self.start_sampler() def cmd_STOP_STREAM(self, gcmd): self._log_info("Eddy sampling finished") self._sampler.finish() self._sampler = None # Probe interface that does only scanning, no up/down movement. # It scans at whatever height the probe is, but returns values # as if the probing happened (i.e. relative to # z_offset/home_trigger_height). @final class ProbeEddyScanningProbe: def __init__(self, eddy: ProbeEddy, gcmd: GCodeCommand): self.eddy = eddy self._printer = eddy._printer self._toolhead = self._printer.lookup_object("toolhead") self._toolhead_kin = self._toolhead.get_kinematics() # we're going to scan at this height; pull_probed_results # also expects to return values based on this height self._scan_z = eddy.params.home_trigger_height # sensor thinks is _home_trigger_height vs. what it actually is. # For example, if we do a tap, adjust, and then we move the toolhead up # to 2.0 but the sensor says 1.950, then this would be +0.050. self._tap_offset = eddy._tap_offset # how much to dwell at each sample position in addition to sample_time self._sample_time_delay = self.eddy.params.scan_sample_time_delay self._sample_time: float = gcmd.get_float("SAMPLE_TIME", self.eddy.params.scan_sample_time, above=0.0) self._is_rapid = gcmd.get("METHOD", "automatic").lower() == "rapid_scan" self._sampler: ProbeEddySampler = None self._notes = [] def get_probe_params(self, gcmd): # this seems to be all that external users of get_probe_params # use (bed_mesh, axis_twist_compensation) return { "lift_speed": self.eddy.params.lift_speed, "probe_speed": self.eddy.params.probe_speed, } def _start_session(self): if not self.eddy._z_homed(): raise self._printer.command_error("Z axis must be homed before probing") self.eddy.probe_to_start_position() self._sampler = self.eddy.start_sampler() def end_probe_session(self): self._sampler.finish() self._sampler = None def _rapid_lookahead_cb(self, time, th_pos): # The time passed here is the time when the move finishes; # but this is super obnoxious because we don't get any info # here about _where_ the move is to. So we explicitly pass # in the last position in run_probe start_time = time - self._sample_time / 2.0 self._notes.append([start_time, time, th_pos]) def run_probe(self, gcmd, *args: Any, **kwargs: Any): th = self._toolhead th_pos = th.get_position() if self._is_rapid: # this callback is attached to the last move in the queue, so that # we can grab the toolhead position when the toolhead actually hits it self._toolhead.register_lookahead_callback(lambda time: self._rapid_lookahead_cb(time, th_pos)) return th.dwell(self._sample_time_delay) start_time = th.get_last_move_time() self._toolhead.dwell(self._sample_time + self._sample_time_delay) self._notes.append((start_time, start_time + self._sample_time / 2.0, th_pos)) def pull_probed_results(self): if self._is_rapid: # Flush lookahead (so all lookahead callbacks are invoked) self._toolhead.get_last_move_time() # make sure we get the sample for the final move self._sampler.wait_for_sample_at_time(self._notes[-1][0] + self._sample_time) # note: we can't call finish() here! this session can continue to be used # to probe additional points and pull them, because that's what QGL does. results = [] logging.info(f"ProbeEddyScanningProbe: pulling {len(self._notes)} results") for start_time, sample_time, th_pos in self._notes: if th_pos is None: th_pos, _ = self.eddy._get_trapq_position(sample_time) if th_pos is None: raise self._printer.command_error(f"No trapq history found for {sample_time:.3f} and no position!") end_time = start_time + self._sample_time height = self._sampler.find_height_at_time(start_time, end_time) if not math.isclose(th_pos[2], self._scan_z, rel_tol=1e-3): logging.info( f"ProbeEddyScanningProbe warning: toolhead not at home_trigger_height ({self._scan_z:.3f}) during probes (saw {th_pos[2]:.3f})" ) h_orig = height tz_orig = th_pos[2] # adjust the sensor height value based on the fine-tuned tap offset amount height += self._tap_offset # the delta between where the toolhead thinks it should be (since it # should be homed), and the actual physical offset (height) z_deviation = th_pos[2] - height # what callers want to know is "what Z would the toolhead be at, if it was at the height # the probe would 'trigger'", because this is all done in terms of klicky-type probes z = float(self._scan_z + z_deviation) if HAS_PROBE_RESULT_TYPE: bed_x = th_pos[0] + self.eddy.params.x_offset bed_y = th_pos[1] + self.eddy.params.y_offset res = manual_probe.ProbeResult(bed_x, bed_y, z_deviation, th_pos[0], th_pos[1], th_pos[2]) result_wrapper = [res] self._printer.send_event("probe:update_results", result_wrapper) res = result_wrapper[0] else: res = [th_pos[0], th_pos[1], z] self._printer.send_event("probe:update_results", res) results.append(res) # reset notes so that this session can continue to be used self._notes = [] return results # This is a ProbeEndstopWrapper-compatible class, # which also forwards the "mcu_probe" methods. @final class ProbeEddyEndstopWrapper: REASON_BASE = mcu.MCU_trsync.REASON_COMMS_TIMEOUT + 1 REASON_ERROR_SENSOR = REASON_BASE + 0 REASON_ERROR_PROBE_TOO_LOW = REASON_BASE + 1 REASON_ERROR_TOO_EARLY = REASON_BASE + 2 def __init__(self, eddy: ProbeEddy): self.eddy = eddy self._sensor = eddy._sensor self._printer = eddy._printer self._mcu = eddy._mcu self._reactor = eddy._reactor # these two are filled in by the outside. self.tap_config: Optional[ProbeEddy.TapConfig] = None # if not None, after a probe session is finished we'll # write all samples here self.save_samples_path: Optional[str] = None self._multi_probe_in_progress = False self._dispatch = mcu.TriggerDispatch(self._mcu) # the times of the last successful endstop home_wait self.last_trigger_time = 0.0 self.last_tap_start_time = 0.0 self._homing_in_progress = False self._sampler: ProbeEddySampler = None # Register z_virtual_endstop pin self._printer.lookup_object("pins").register_chip("probe", self) # Register event handlers self._printer.register_event_handler("klippy:mcu_identify", self._handle_mcu_identify) self._printer.register_event_handler("homing:homing_move_begin", self._handle_homing_move_begin) self._printer.register_event_handler("homing:homing_move_end", self._handle_homing_move_end) self._printer.register_event_handler("homing:home_rails_begin", self._handle_home_rails_begin) self._printer.register_event_handler("homing:home_rails_end", self._handle_home_rails_end) self._printer.register_event_handler("gcode:command_error", self._handle_command_error) # copy some things in for convenience self._home_trigger_height = self.eddy.params.home_trigger_height self._home_trigger_safe_start_offset = self.eddy.params.home_trigger_safe_start_offset self._home_start_height = self.eddy._home_start_height # this is trigger + safe_start + 1.0 self._probe_speed = self.eddy.params.probe_speed self._lift_speed = self.eddy.params.lift_speed def _handle_mcu_identify(self): kin = self._printer.lookup_object("toolhead").get_kinematics() for stepper in kin.get_steppers(): if stepper.is_active_axis("z"): self.add_stepper(stepper) def _handle_home_rails_begin(self, homing_state, rails): endstops = [es for rail in rails for es, name in rail.get_endstops()] if self not in endstops: return # Nothing to do pass def _handle_homing_move_begin(self, hmove): if self not in hmove.get_mcu_endstops(): return self._sampler = self.eddy.start_sampler() self._homing_in_progress = True # if we're doing a tap, we're already in the right position; # otherwise move there if self.tap_config is None: self.eddy._probe_to_start_position_unhomed(move_home=True) def _handle_homing_move_end(self, hmove): if self not in hmove.get_mcu_endstops(): return self._sampler.finish() self._homing_in_progress = False def _handle_home_rails_end(self, homing_state, rails): endstops = [es for rail in rails for es, name in rail.get_endstops()] if self not in endstops: return # Nothing to do pass def _handle_command_error(self, gcmd=None): if self._homing_in_progress: self._homing_in_progress = False try: if self._sampler is not None: self._sampler.finish() except: logging.exception("EDDYng handle_command_error: sampler.finish() failed") def setup_pin(self, pin_type, pin_params): if pin_type != "endstop" or pin_params["pin"] != "z_virtual_endstop": raise pins.error("Probe virtual endstop only useful as endstop pin") if pin_params["invert"] or pin_params["pullup"]: raise pins.error("Can not pullup/invert probe virtual endstop") return self # these are the "MCU Probe" methods def get_mcu(self): return self._mcu def add_stepper(self, stepper): self._dispatch.add_stepper(stepper) def get_steppers(self): return self._dispatch.get_steppers() def get_position_endstop(self): if self.tap_config is None: return self._home_trigger_height else: return 0.0 def home_start(self, print_time, sample_time, sample_count, rest_time, triggered=True): if not self._sampler.active(): raise self._printer.command_error("home_start called without a sampler active") self.last_trigger_time = 0.0 self.last_tap_start_time = 0.0 trigger_height = self._home_trigger_height safe_height = trigger_height + self._home_trigger_safe_start_offset if self.tap_config is None: safe_time = print_time + self.eddy.params.home_trigger_safe_time_offset trigger_freq = self.eddy.height_to_freq(trigger_height) safe_freq = self.eddy.height_to_freq(safe_height) else: # TODO: the home trigger safe time won't work, because we'll pass # the home_trigger_height maybe by default given where tap might # start safe_time = 0 # initial freq to pass through safe_freq = self.eddy.height_to_freq(self._home_trigger_height) # second freq to pass through; toolhead acceleration # must be smooth after this point trigger_freq = self.eddy.height_to_freq(self.eddy.params.tap_trigger_safe_start_height) trigger_completion = self._dispatch.start(print_time) if self.tap_config is not None: if self.tap_config.mode == "butter": sos = self.tap_config.sos assert sos for i in range(len(sos)): self.eddy._sensor.set_sos_section(i, sos[i]) mode = "sos" elif self.tap_config.mode == "wma": mode = "wma" else: raise self._printer.command_error(f"Invalid tap mode: {self.tap_config.mode}") tap_threshold = self.tap_config.threshold else: mode = "home" tap_threshold = None self.eddy._log_debug( f"EDDYng home_start {mode}: {print_time:.3f} freq: {trigger_freq:.2f} safe-start: {safe_freq:.2f} @ {safe_time:.3f}" ) # setup homing -- will start scanning and trigger when we hit # trigger_freq self._sensor.setup_home( self._dispatch.get_oid(), mcu.MCU_trsync.REASON_ENDSTOP_HIT, self.REASON_BASE, trigger_freq, safe_freq, safe_time, mode=mode, tap_threshold=tap_threshold, max_errors=self.eddy.params.max_errors, ) return trigger_completion def home_wait(self, home_end_time): self.eddy._log_debug(f"home_wait until {home_end_time:.3f}") # logging.info(f"EDDYng home_wait {home_end_time} cur {curtime} ept {est_print_time} ehe {est_he_time}") self._dispatch.wait_end(home_end_time) # make sure homing is stopped, and grab the trigger_time from the mcu home_result = self._sensor.finish_home() trigger_time = home_result.trigger_time tap_start_time = home_result.tap_start_time error = self._sensor.data_error_to_str(home_result.error) if home_result.error != 0 else "" is_tap = self.tap_config is not None self._sampler.memo("trigger_time", trigger_time) if is_tap: self._sampler.memo("tap_start_time", tap_start_time) self._sampler.memo("tap_threshold", self.tap_config.threshold) self.eddy._log_debug( f"trigger_time {trigger_time} (mcu: {self._mcu.print_time_to_clock(trigger_time)}) tap time: {tap_start_time}-{trigger_time} {error}" ) # nb: _dispatch.stop() will treat anything >= REASON_COMMS_TIMEOUT as an error, # and will only return those results. Fine for us since we only have one trsync, # but annoying in general. res = self._dispatch.stop() # clean these up, and only update them if successful self.last_trigger_time = 0.0 self.last_tap_start_time = 0.0 # always reset this; taps are one-shot usages of the endstop wrapper self.tap_config = None # if we're doing a tap, we wait for samples for the end as well so that we can get # beter data for analysis self._sampler.wait_for_sample_at_time(trigger_time) # success? if res == mcu.MCU_trsync.REASON_ENDSTOP_HIT: self.last_trigger_time = trigger_time self.last_tap_start_time = tap_start_time if is_tap: return tap_start_time + (trigger_time - tap_start_time) * self.eddy.params.tap_time_position return trigger_time # various errors if res == mcu.MCU_trsync.REASON_COMMS_TIMEOUT: raise self._printer.command_error("Communication timeout during homing") if res == self.REASON_ERROR_SENSOR: raise self._printer.command_error(f"Sensor error ({error})") if res == self.REASON_ERROR_PROBE_TOO_LOW: raise self._printer.command_error("Probe too low at start of homing, did not clear safe height.") if res == self.REASON_ERROR_TOO_EARLY: raise self._printer.command_error("Probe cleared safe height too early.") if res == mcu.MCU_trsync.REASON_PAST_END_TIME: raise self._printer.command_error( "Probe completed movement before triggering. If this is a tap, try lowering TARGET_Z or adjusting the THRESHOLD." ) raise self._printer.command_error(f"Unknown homing error: {res}") def query_endstop(self, print_time): return False def _setup_sampler(self): self._sampler = self.eddy.start_sampler() def _finish_sampler(self): self._sampler.finish() self._sampler = None # Helper to gather samples and convert them to probe positions @final class ProbeEddySampler: def __init__( self, eddy: ProbeEddy, calculate_heights: bool = True, ): self.eddy = eddy self._sensor = eddy._sensor self._printer = self.eddy._printer self._reactor = self._printer.get_reactor() self._mcu = self._sensor.get_mcu() self._stopped = False self._started = False self._errors = 0 self._fmap = eddy.map_for_drive_current() if calculate_heights else None self.times = [] self.raw_freqs = [] self.freqs = [] self.heights = [] if self._fmap is not None else None self.memos = dict() @property def raw_count(self): return len(self.times) @property def height_count(self): return len(self.heights) if self.heights else 0 # this is just a handy way to communicate values between different parts of the system, # specifically to record things like trigger times for plotting def memo(self, name, value): self.memos[name] = value def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_value, traceback): self.finish() def active(self): return self._started and not self._stopped # bulk sample callback for when new data arrives # from the probe def _add_hw_measurement(self, msg): if self._stopped: return False self._errors += msg["errors"] data = msg["data"] # data is (t, fv) if data: times, raw_freqs = zip(*data) else: times, raw_freqs = [], [] self.times.extend(times) self.raw_freqs.extend(raw_freqs) return True def start(self): if self._stopped: raise self._printer.command_error("ProbeEddySampler.start() called after finish()") if not self._started: self._sensor.add_bulk_sensor_data_client(self._add_hw_measurement) self._started = True def finish(self): if self._stopped: return if not self._started: raise self._printer.command_error("ProbeEddySampler.finish() called without start()") if self.eddy._sampler is not self: raise self._printer.command_error("ProbeEddySampler.finish(): eddy._sampler is not us!") self._update_samples() self.eddy._sampler_finished(self) self._stopped = True def _update_samples(self): if len(self.freqs) == len(self.raw_freqs): return conv_ratio = self._sensor.freqval_conversion_value() start_idx = len(self.freqs) freqs_np = np.asarray(self.raw_freqs[start_idx:]) * conv_ratio self.freqs.extend(freqs_np.tolist()) if self._fmap is not None: heights_np = self._fmap.freqs_to_heights_np(freqs_np) self.heights.extend(heights_np.tolist()) @property def error_count(self): return self._errors # get the last sampled height def get_last_height(self) -> float: if self.heights is None: raise self._printer.command_error("ProbeEddySampler: no height mapping") self._update_samples() if len(self.heights) == 0: raise self._printer.command_error("ProbeEddySampler: no samples") return self.heights[-1] # wait for a sample for the current time and get a new height def get_height_now(self) -> Optional[float]: now = self.eddy._print_time_now() if not self.wait_for_sample_at_time(now, max_wait_time=1.000, raise_error=False): return None return self.get_last_height() # Wait until a sample for the given time arrives def wait_for_sample_at_time(self, sample_print_time, max_wait_time=0.250, raise_error=True) -> bool: def report_no_samples(): if raise_error: raise self._printer.command_error(f"No samples received for time {sample_print_time:.3f} (waited for {max_wait_time:.3f})") return False if self._stopped: # if we're not getting any more samples, we can check directly if len(self.times) == 0: return report_no_samples() return self.times[-1] >= sample_print_time # quick check if self.times and self.times[-1] >= sample_print_time: return True wait_start_time = self.eddy._print_time_now() # if sample_print_time is in the future, make sure to wait max_wait_time # past the expected time if sample_print_time > wait_start_time: max_wait_time = max_wait_time + (sample_print_time - wait_start_time) # this is just a sanity check, there shouldn't be any reason to ever wait this long if max_wait_time > 30.0: traceback.print_stack() msg = f"ProbeEddyFrequencySampler: max_wait_time {max_wait_time:.3f} is too far into the future" raise self._printer.command_error(msg) self.eddy._log_debug( f"EDDYng waiting for sample at {sample_print_time:.3f} (now: {wait_start_time:.3f}, max_wait_time: {max_wait_time:.3f})" ) now = self.eddy._print_time_now() while len(self.times) == 0 or self.times[-1] < sample_print_time: now = self.eddy._print_time_now() if now - wait_start_time > max_wait_time: return report_no_samples() self._reactor.pause(self._reactor.monotonic() + 0.010) if now - wait_start_time > 1.0: self.eddy._log_info(f"note: waited {now - wait_start_time:.3f}s for sample") return True # Wait for some samples to be collected, even if errors # TODO: there's a minimum wait time -- we need to fill up the buffer before data is sent, and that # depends on the data rate def wait_for_samples( self, max_wait_time=0.300, count_errors=False, min_samples=1, new_only=False, raise_error=True, ): # Make sure enough samples have been collected wait_start_time = self.eddy._print_time_now() start_error_count = self._errors start_count = 0 if new_only: start_count = len(self.raw_freqs) + (self._errors if count_errors else 0) while (len(self.raw_freqs) + (self._errors if count_errors else 0)) - start_count < min_samples: now = self.eddy._print_time_now() if now - wait_start_time > max_wait_time: if raise_error: raise self._printer.command_error( f"probe_eddy_ng sensor outage: no samples for {max_wait_time:.2f}s (got {self._errors - start_error_count} errors)" ) return False self._reactor.pause(self._reactor.monotonic() + 0.010) return True def find_heights_at_times(self, intervals): self._update_samples() times = self.times heights = np.asarray(self.heights) num_samples = len(times) interval_heights = [] i = 0 for iv_start, iv_end in intervals: while i < num_samples and times[i] < iv_start: i += 1 istart = i while i < num_samples and times[i] < iv_end: i += 1 iend = i if istart == iend: # no samples in this range raise self._printer.command_error(f"No samples in time range {iv_start}-{iv_end}") median = np.median(heights[istart:iend]) interval_heights.append(float(median)) return interval_heights def find_height_at_time(self, start_time, end_time): if end_time < start_time: raise self._printer.command_error("find_height_at_time: end_time is before start_time") self._update_samples() if len(self.times) == 0: raise self._printer.command_error("No samples at all, so none in time range") if not self.heights: raise self._printer.command_error("Update samples didn't compute heights") self.eddy._log_debug( f"find_height_at_time: looking between {start_time:.3f}s-{end_time:.3f}s, inside {len(self.times)} samples, time range {self.times[0]:.3f}s to {self.times[-1]:.3f}s" ) # find the first sample that is >= start_time start_idx = bisect.bisect_left(self.times, start_time) if start_idx >= len(self.times): raise self._printer.command_error("Nothing after start_time?") # find the last sample that is < end_time end_idx = start_idx while end_idx < len(self.times) and self.times[end_idx] < end_time: end_idx += 1 # average the heights of the samples in the range heights = self.heights[start_idx:end_idx] if len(heights) == 0: raise self._printer.command_error(f"no samples between time {start_time:.1f} and {end_time:.1f}!") hmin, hmax = np.min(heights), np.max(heights) mean = np.mean(heights) median = np.median(heights) self.eddy._log_debug( f"find_height_at_time: {len(heights)} samples, median: {median:.3f}, mean: {mean:.3f} (range {hmin:.3f}-{hmax:.3f})" ) return float(median) @final class ProbeEddyFrequencyMap: calibration_version = 5 low_z_threshold = 5.0 def __init__(self, eddy: ProbeEddy): self._eddy = eddy self._sensor = eddy._sensor self.drive_current = 0 self.height_range = (math.inf, -math.inf) self.freq_range = (math.inf, -math.inf) self._ftoh: Optional[npp.Polynomial] = None self._ftoh_high: Optional[npp.Polynomial] = None self._htof: Optional[npp.Polynomial] = None def _str_to_exact_floatlist(self, str): return [float.fromhex(v) for v in str.split(",")] def _exact_floatlist_to_str(self, vals): return str.join(", ", [float.hex(v) for v in vals]) def _coefs_to_str(self, coefs): return ", ".join([format(c, ".3f") for c in coefs]) def freq_spread(self) -> float: return ((self.freq_range[1] / self.freq_range[0]) - 1.0) * 100.0 def load_from_config(self, config: ConfigWrapper, drive_current: int): calibstr = config.get(f"calibration_{drive_current}", None) if calibstr is None: self.drive_current = 0 self._ftoh = None self._htof = None self.height_range = (math.inf, -math.inf) self.freq_range = (math.inf, -math.inf) return data = pickle.loads(base64.b64decode(calibstr)) v = data.get("v", None) if v is None or v < self.calibration_version: self._eddy._log_info(f"Calibration for dc {drive_current} is old ({v}), needs recalibration") return False ftoh = data.get("ftoh", None) ftoh_high = data.get("ftoh_high", None) htof = data.get("htof", None) dc = data.get("dc", None) h_range = data.get("h_range", (math.inf, -math.inf)) f_range = data.get("f_range", (math.inf, -math.inf)) if dc != drive_current: raise configerror(f"ProbeEddyFrequencyMap: drive current mismatch: loaded {dc} != requested {drive_current}") self._ftoh = ftoh self._ftoh_high = ftoh_high self._htof = htof self.height_range = h_range self.freq_range = f_range self.drive_current = drive_current self._eddy._log_info(f"Loaded calibration for drive current {drive_current}") return True def save_calibration(self): if self._ftoh is None or self._htof is None: return configfile = self._eddy._printer.lookup_object("configfile") data = { "v": self.calibration_version, "ftoh": self._ftoh, "ftoh_high": self._ftoh_high, "htof": self._htof, "h_range": self.height_range, "f_range": self.freq_range, "dc": self.drive_current, } calibstr = base64.b64encode(pickle.dumps(data)).decode() configfile.set(self._eddy._full_name, f"calibration_{self.drive_current}", calibstr) def calibrate_from_values( self, drive_current: int, raw_times: List[float], raw_freqs_list: List[float], raw_heights_list: List[float], raw_vels_list: List[float], report_errors: bool, write_debug_files: bool, ): if len(raw_freqs_list) != len(raw_heights_list): raise ValueError("freqs and heights must be the same length") if len(raw_freqs_list) == 0: self._eddy._log_info("calibrate_from_values: empty list") return None, None # everything must be a np.array or things get confused below times = np.asarray(raw_times) freqs = np.asarray(raw_freqs_list) heights = np.asarray(raw_heights_list) vels = np.asarray(raw_vels_list) if raw_vels_list else None if write_debug_files: with open("/tmp/eddy-calibration.csv", "w") as data_file: data_file.write("time,frequency,avg_freq,z,avg_z,v\n") for i in range(len(freqs)): s_t = times[i] s_f = freqs[i] s_z = heights[i] s_v = vels[i] if vels is not None else 0.0 data_file.write(f"{s_t},{s_f},{s_z},,{s_v}\n") self._eddy._log_info(f"Wrote {len(freqs)} samples to /tmp/eddy-calibration.csv") if len(freqs) == 0 or len(heights) == 0: if report_errors: self._eddy._log_error( f"Drive current {drive_current}: Calibration failed, couldn't compute averages ({len(raw_freqs_list)}, {len(raw_heights_list)}), probably due to no valid samples received." ) return None, None max_height = float(heights.max()) min_height = float(heights.min()) min_freq = float(freqs.min()) max_freq = float(freqs.max()) freq_spread = ((max_freq / min_freq) - 1.0) * 100.0 # Check if our calibration is good enough if report_errors: if max_height < 2.5: # we really can't do anything with this self._eddy._log_error( f"Drive current {drive_current} error: max height for valid samples is too low: {max_height:.3f} < 2.5. Possible causes: bad drive current, bad sensor mount height." ) if not self._eddy.params.allow_unsafe: return None, None if min_height > 0.65: # this is a bit arbitrary; but if it's this far off we shouldn't trust it self._eddy._log_error( f"Drive current {drive_current} error: min height for valid samples is too high: {min_height:.3f} > 0.65. Possible causes: bad drive current, bad sensor mount height." ) if not self._eddy.params.allow_unsafe: return None, None if min_height > 0.025: self._eddy._log_msg( f"Drive current {drive_current} warning: min height is {min_height:.3f} (> 0.025) is too high for tap. This calibration will work fine for homing, but may not for tap." ) # somewhat arbitrary spread if freq_spread < 0.30: extremely = "EXTREMELY " if freq_spread < 0.15 else "" self._eddy._log_warning( f"Drive current {drive_current} warning: frequency spread is {extremely}low ({freq_spread:.2f}%, {min_freq:.1f}-{max_freq:.1f}), which will greatly impact accuracy. Your sensor may be too high." ) low_samples = heights <= ProbeEddyFrequencyMap.low_z_threshold high_samples = heights >= ProbeEddyFrequencyMap.low_z_threshold - 0.5 ftoh_low_fn = npp.Polynomial.fit(1.0 / freqs[low_samples], heights[low_samples], deg=9) htof_low_fn = npp.Polynomial.fit(heights[low_samples], 1.0 / freqs[low_samples], deg=9) if np.count_nonzero(high_samples) > 50: ftoh_high_fn = npp.Polynomial.fit(1.0 / freqs[high_samples], heights[high_samples], deg=9) else: self._eddy._log_debug(f"not computing ftoh_high, not enough high samples") ftoh_high_fn = None # Calculate rms, only for the low values (where error is most relevant) rmse_fth = np_rmse( ftoh_low_fn, 1.0 / freqs[low_samples], heights[low_samples], ) rmse_htf = np_rmse( htof_low_fn, heights[low_samples], 1.0 / freqs[low_samples], ) if report_errors: if rmse_fth > 0.050: self._eddy._log_error( f"Drive current {drive_current} error: calibration error margin is too high ({rmse_fth:.3f}). Possible causes: bad drive current, bad sensor mount height." ) if not self._eddy.params.allow_unsafe: return None, None self._ftoh = ftoh_low_fn self._htof = htof_low_fn self._ftoh_high = ftoh_high_fn self.drive_current = drive_current self.height_range = [min_height, max_height] self.freq_range = [min_freq, max_freq] self._eddy._log_msg( f"Drive current {drive_current}: valid height: {min_height:.3f} to {max_height:.3f}, " f"freq spread {freq_spread:.2f}% ({min_freq:.1f} - {max_freq:.1f}), " f"Fit {rmse_fth:.4f} ({rmse_htf:.2f})" ) if write_debug_files: self._write_calibration_plot( times, freqs, heights, rmse_fth, rmse_htf, vels=vels, ) return rmse_fth, rmse_htf def _write_calibration_plot( self, times, freqs, heights, rmse_fth, rmse_htf, vels=None, ): if not plotly: return if self._ftoh is None or self._htof is None: logging.warning(f"write_calibration_plot: null calibration?") return import plotly.graph_objects as go low_samples = heights <= ProbeEddyFrequencyMap.low_z_threshold high_samples = heights >= ProbeEddyFrequencyMap.low_z_threshold - 0.5 f_to_z_low_err = heights[low_samples] - self._ftoh(1.0 / freqs[low_samples]) if self._ftoh_high is not None: f_to_z_high_err = heights[high_samples] - self._ftoh_high(1.0 / freqs[high_samples]) else: f_to_z_high_err = None fig = go.Figure() fig.add_trace(go.Scatter(x=times, y=heights, mode="lines", name="Z")) fig.add_trace( go.Scatter( x=times[low_samples], y=self._ftoh(1.0 / freqs[low_samples]), mode="lines", name=f"Z {rmse_fth:.4f}", ) ) if self._ftoh_high is not None: fig.add_trace( go.Scatter( x=times[high_samples], y=self._ftoh_high(1.0 / freqs[high_samples]), mode="lines", name=f"Z (high)", ) ) fig.add_trace(go.Scatter(x=times, y=freqs, mode="lines", name="F", yaxis="y2")) fig.add_trace( go.Scatter( x=times[low_samples], y=1.0 / self._htof(heights[low_samples]), mode="lines", name=f"F ({rmse_htf:.2f})", yaxis="y2", ) ) fig.add_trace( go.Scatter( x=times[low_samples], y=f_to_z_low_err, mode="lines", name="Err", yaxis="y3", ) ) if f_to_z_high_err is not None: fig.add_trace( go.Scatter( x=times[high_samples], y=f_to_z_high_err, mode="lines", name="Err (high)", yaxis="y3", ) ) if vels is not None: fig.add_trace(go.Scatter(x=times, y=vels, mode="lines", name="V", yaxis="y4")) fig.update_layout( hovermode="x unified", title=f"Calibration for drive current {self.drive_current}", yaxis2=dict(title="Freq", overlaying="y", tickformat="d", side="right"), yaxis3=dict(overlaying="y", side="right", position=0.1), yaxis4=dict(overlaying="y", side="right", position=0.2), ) fig.write_html("/tmp/eddy-calibration.html") def freq_to_height(self, freq: float) -> float: if self._ftoh is None: raise self._eddy._printer.command_error("Calling freq_to_height on uncalibrated map") invfreq = 1.0 / freq if self._ftoh_high is not None and invfreq < self._ftoh.domain[0]: return float(self._ftoh_high(invfreq)) return float(self._ftoh(invfreq)) def freqs_to_heights_np(self, freqs: np.array) -> np.array: if self._ftoh is None: raise self._eddy._printer.command_error("Calling freqs_to_heights on uncalibrated map") invfreqs = 1.0 / freqs if self._ftoh_high is not None: heights = np.zeros(len(invfreqs)) low_freq_vals = invfreqs > self._ftoh.domain[1] heights[low_freq_vals] = np.vectorize(self._ftoh_high, otypes=[float])(invfreqs[low_freq_vals]) heights[~low_freq_vals] = np.vectorize(self._ftoh, otypes=[float])(invfreqs[~low_freq_vals]) else: heights = self._ftoh(invfreqs) return heights def height_to_freq(self, height: float) -> float: if self._htof is None: raise self._eddy._printer.command_error("Calling height_to_freq on uncalibrated map") return 1.0 / float(self._htof(height)) def calibrated(self) -> bool: return self._ftoh is not None and self._htof is not None @final class BedMeshScanHelper: def __init__(self, eddy, config): self._eddy = eddy self._printer = eddy._printer bmc = config.getsection("bed_mesh") self._bed_mesh = eddy._printer.load_object(bmc, "bed_mesh") self._x_points, self._y_points = bmc.getintlist("probe_count", count=2, note_valid=False) self._x_min, self._y_min = bmc.getfloatlist("mesh_min", count=2, note_valid=False) self._x_max, self._y_max = bmc.getfloatlist("mesh_max", count=2, note_valid=False) self._speed = bmc.getfloat("speed", 100.0, above=0.0, note_valid=False) self._scan_z = bmc.getfloat("horizontal_move_z", self._eddy.params.home_trigger_height, above=0.0, note_valid=False) self._x_offset = self._eddy.params.x_offset self._y_offset = self._eddy.params.y_offset self._mesh_points, self._mesh_path = self._generate_path() def _generate_path(self): x_vals = np.linspace(self._x_min, self._x_max, self._x_points) y_vals = np.linspace(self._y_min, self._y_max, self._y_points) path = [] reverse = False for y in y_vals: row = [(x, y, True) for x in (reversed(x_vals) if reverse else x_vals)] path.extend(row) reverse = not reverse return path, path def _scan_path(self): th = self._eddy._toolhead times = [] for pt in self._mesh_path: # TODO bounds th.manual_move([pt[0] - self._x_offset, pt[1] - self._y_offset, None], self._speed) th.register_lookahead_callback(lambda t: times.append(t)) th.wait_moves() return times def _set_bed_mesh(self, heights): # heights is in the order of the _mesh_path points; convert to # be ordered min_y..max_y, min_x..max_x, then pull out the heights indexed_points = [] i = 0 for x, y, include in self._mesh_path: if not include: continue indexed_points.append((x, y, i)) i += 1 def sort_points(a, b): if a[1] < b[1]: # y first return -1 if a[1] > b[1]: return 1 if a[0] < b[0]: # then x return -1 if a[0] > b[0]: return 1 return 0 indices = [ki for _, _, ki in sorted(indexed_points, key=cmp_to_key(sort_points))] ki = 0 matrix = [] for _ in range(self._y_points): row = [] for _ in range(self._x_points): v = heights[indices[ki]] row.append(self._scan_z - v) ki += 1 matrix.append(row) params = self._bed_mesh.bmc.mesh_config.copy() params.update({ "min_x": self._x_min, "max_x": self._x_max, "min_y": self._y_min, "max_y": self._y_max, "x_count": self._x_points, "y_count": self._y_points, }) mesh = bed_mesh.ZMesh(params, None) try: mesh.build_mesh(matrix) except bed_mesh.BedMeshError as e: raise self._printer.command_error(str(e)) self._bed_mesh.set_mesh(mesh) self._eddy._log_msg("Mesh scan complete") def scan(self): th = self._eddy._toolhead # move to the start point v = self._mesh_path[0] th.manual_move([None, None, 10.0], self._eddy.params.lift_speed) th.manual_move([v[0] - self._x_offset, v[1] - self._y_offset, None], self._speed) th.manual_move([None, None, self._scan_z], self._eddy.params.probe_speed) th.wait_moves() heights = [] sample_time = self._eddy.params.scan_sample_time with self._eddy.start_sampler() as sampler: path_times = self._scan_path() sampler.wait_for_sample_at_time(path_times[-1] + sample_time*2.) sampler.finish() heights = sampler.find_heights_at_times([(t - sample_time/2., t + sample_time/2.) for t in path_times]) # Note plus tap_offset here, vs -tap_offset when probing. These are actual # heights, the other is "offset from real" heights = [h + self._eddy._tap_offset for h in heights] with open("/tmp/mesh.csv", "w") as mfile: mfile.write("time,x,y,z\n") for i in range(len(self._mesh_points)): t = path_times[i] x = self._mesh_points[i][0] y = self._mesh_points[i][1] z = heights[i] mfile.write(f"{t},{x},{y},{z}\n") self._set_bed_mesh(heights) def np_rmse(p, x, y): y_hat = p(x) return np.sqrt(np.mean((y - y_hat) ** 2)) def bed_mesh_ProbeManager_start_probe_override(self, gcmd): method = gcmd.get("METHOD", "automatic").lower() can_scan = False pprobe = self.printer.lookup_object("probe", None) if pprobe is not None: probe_name = pprobe.get_status(None).get("name", "") can_scan = "eddy" in probe_name if method == "rapid_scan" and can_scan: self.rapid_scan_helper.perform_rapid_scan(gcmd) else: self.probe_helper.start_probe(gcmd) def load_config_prefix(config: ConfigWrapper): return ProbeEddy(config) ================================================ FILE: pyrightconfig.json ================================================ { "reportOptionalMemberAccess": false }