[
  {
    "path": ".beads/issues.jsonl",
    "content": ""
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: [vvuk]\npatreon: # Replace with a single Patreon username\nopen_collective: # Replace with a single Open Collective username\nko_fi: vvuk\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\nlfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry\npolar: # Replace with a single Polar username\nbuy_me_a_coffee: # Replace with a single Buy Me a Coffee username\nthanks_dev: # Replace with a single thanks.dev username\ncustom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']\n"
  },
  {
    "path": ".gitignore",
    "content": ".idea/\n.vscode/\n.DS_Store\n*~\n*.orig\n*.rej\n"
  },
  {
    "path": ".ruff.toml",
    "content": "line-length = 140\nindent-width = 4\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# eddy-ng\r\n\r\n> ***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!***\r\n\r\neddy-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:\r\n\r\n1. Calibration is performed at any temperature (cold).\r\n2. 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.\r\n3. 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).\r\n4. 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.\r\n\r\nThis is a standalone `eddy-ng` repository, intended to be integrated into your own Klipper installation.\r\n\r\n## Support\r\n\r\nQuestions? 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)\r\n\r\nYou can also file issues in [this `eddy-ng` github repo](https://github.com/vvuk/eddy-ng/issues).\r\n\r\n## Installation\r\n\r\n1. Clone this repository:\r\n\r\n```\r\ncd ~\r\ngit clone https://github.com/vvuk/eddy-ng\r\n```\r\n\r\n2. Run the install script:\r\n\r\n```\r\ncd ~/eddy-ng\r\n./install.sh\r\n```\r\n\r\n(If your klipper isn't installed in `~/klipper`, provide the path as the first argument, i.e. `./install.sh ~/my-klipper`.)\r\n\r\n3. Follow the rest of the full `eddy-ng` setup instructions that are [available in the wiki](https://github.com/vvuk/eddy-ng/wiki).\r\n\r\n## Updating\r\n\r\nRun a `git pull` and then run `./install.sh` again:\r\n\r\n```\r\ncd ~/eddy-ng\r\ngit pull\r\n./install.sh\r\n```\r\n\r\n"
  },
  {
    "path": "__init__.py",
    "content": "from klippy.configfile import ConfigWrapper\nfrom .probe_eddy_ng import ProbeEddy\n\ndef load_config_prefix(config: ConfigWrapper):\n    return ProbeEddy(config)\n"
  },
  {
    "path": "eddy-ng/Kconfig",
    "content": "config WANT_EDDY_NG\n    bool \"Include eddy-ng ldc1612 support\"\n\nconfig WANT_EDDY_NG_DEBUG\n    bool \"Enable verbose eddy-ng logging\"\n    depends on WANT_EDDY_NG\n"
  },
  {
    "path": "eddy-ng/Makefile",
    "content": "dirs-y += src/extras/eddy-ng\nsrc-$(CONFIG_WANT_EDDY_NG) += extras/eddy-ng/sensor_ldc1612_ng.c\nsrc-$(CONFIG_WANT_EDDY_NG_DEBUG) += extras/eddy-ng/printf.c\n\n"
  },
  {
    "path": "eddy-ng/printf.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\r\n// \\author (c) Marco Paland (info@paland.com)\r\n//             2014-2019, PALANDesign Hannover, Germany\r\n//\r\n// \\license The MIT License (MIT)\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files (the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be included in\r\n// all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n// THE SOFTWARE.\r\n//\r\n// \\brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on\r\n//        embedded systems with a very limited resources. These routines are thread\r\n//        safe and reentrant!\r\n//        Use this instead of the bloated standard/newlib printf cause these use\r\n//        malloc for printf (and may not be thread safe).\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\n#include <stdbool.h>\r\n#include <stdint.h>\r\n\r\n#include \"printf.h\"\r\n\r\n\r\n// define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the\r\n// printf_config.h header file\r\n// default: undefined\r\n#ifdef PRINTF_INCLUDE_CONFIG_H\r\n#include \"printf_config.h\"\r\n#endif\r\n\r\n\r\n// 'ntoa' conversion buffer size, this must be big enough to hold one converted\r\n// numeric number including padded zeros (dynamically created on stack)\r\n// default: 32 byte\r\n#ifndef PRINTF_NTOA_BUFFER_SIZE\r\n#define PRINTF_NTOA_BUFFER_SIZE    32U\r\n#endif\r\n\r\n// 'ftoa' conversion buffer size, this must be big enough to hold one converted\r\n// float number including padded zeros (dynamically created on stack)\r\n// default: 32 byte\r\n#ifndef PRINTF_FTOA_BUFFER_SIZE\r\n#define PRINTF_FTOA_BUFFER_SIZE    32U\r\n#endif\r\n\r\n// support for the floating point type (%f)\r\n// default: activated\r\n#ifndef PRINTF_DISABLE_SUPPORT_FLOAT\r\n#define PRINTF_SUPPORT_FLOAT\r\n#endif\r\n\r\n// support for exponential floating point notation (%e/%g)\r\n// default: activated\r\n#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL\r\n#define PRINTF_SUPPORT_EXPONENTIAL\r\n#endif\r\n\r\n// define the default floating point precision\r\n// default: 6 digits\r\n#ifndef PRINTF_DEFAULT_FLOAT_PRECISION\r\n#define PRINTF_DEFAULT_FLOAT_PRECISION  6U\r\n#endif\r\n\r\n// define the largest float suitable to print with %f\r\n// default: 1e9\r\n#ifndef PRINTF_MAX_FLOAT\r\n#define PRINTF_MAX_FLOAT  1e9\r\n#endif\r\n\r\n// support for the long long types (%llu or %p)\r\n// default: activated\r\n#ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG\r\n#define PRINTF_SUPPORT_LONG_LONG\r\n#endif\r\n\r\n// support for the ptrdiff_t type (%t)\r\n// ptrdiff_t is normally defined in <stddef.h> as long or long long type\r\n// default: activated\r\n#ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T\r\n#define PRINTF_SUPPORT_PTRDIFF_T\r\n#endif\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\n// internal flag definitions\r\n#define FLAGS_ZEROPAD   (1U <<  0U)\r\n#define FLAGS_LEFT      (1U <<  1U)\r\n#define FLAGS_PLUS      (1U <<  2U)\r\n#define FLAGS_SPACE     (1U <<  3U)\r\n#define FLAGS_HASH      (1U <<  4U)\r\n#define FLAGS_UPPERCASE (1U <<  5U)\r\n#define FLAGS_CHAR      (1U <<  6U)\r\n#define FLAGS_SHORT     (1U <<  7U)\r\n#define FLAGS_LONG      (1U <<  8U)\r\n#define FLAGS_LONG_LONG (1U <<  9U)\r\n#define FLAGS_PRECISION (1U << 10U)\r\n#define FLAGS_ADAPT_EXP (1U << 11U)\r\n\r\n\r\n// import float.h for DBL_MAX\r\n#if defined(PRINTF_SUPPORT_FLOAT)\r\n#include <float.h>\r\n#endif\r\n\r\n\r\n// output function type\r\ntypedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen);\r\n\r\n\r\n// wrapper (used as buffer) for output function type\r\ntypedef struct {\r\n  void  (*fct)(char character, void* arg);\r\n  void* arg;\r\n} out_fct_wrap_type;\r\n\r\n\r\n// internal buffer output\r\nstatic inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen)\r\n{\r\n  if (idx < maxlen) {\r\n    ((char*)buffer)[idx] = character;\r\n  }\r\n}\r\n\r\n\r\n// internal null output\r\nstatic inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen)\r\n{\r\n  (void)character; (void)buffer; (void)idx; (void)maxlen;\r\n}\r\n\r\n\r\n// internal _putchar wrapper\r\nstatic inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen)\r\n{\r\n  (void)buffer; (void)idx; (void)maxlen;\r\n  if (character) {\r\n    _putchar(character);\r\n  }\r\n}\r\n\r\n\r\n// internal output function wrapper\r\nstatic inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen)\r\n{\r\n  (void)idx; (void)maxlen;\r\n  if (character) {\r\n    // buffer is the output fct pointer\r\n    ((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg);\r\n  }\r\n}\r\n\r\n\r\n// internal secure strlen\r\n// \\return The length of the string (excluding the terminating 0) limited by 'maxsize'\r\nstatic inline unsigned int _strnlen_s(const char* str, size_t maxsize)\r\n{\r\n  const char* s;\r\n  for (s = str; *s && maxsize--; ++s);\r\n  return (unsigned int)(s - str);\r\n}\r\n\r\n\r\n// internal test if char is a digit (0-9)\r\n// \\return true if char is a digit\r\nstatic inline bool _is_digit(char ch)\r\n{\r\n  return (ch >= '0') && (ch <= '9');\r\n}\r\n\r\n\r\n// internal ASCII string to unsigned int conversion\r\nstatic unsigned int _atoi(const char** str)\r\n{\r\n  unsigned int i = 0U;\r\n  while (_is_digit(**str)) {\r\n    i = i * 10U + (unsigned int)(*((*str)++) - '0');\r\n  }\r\n  return i;\r\n}\r\n\r\n\r\n// output the specified string in reverse, taking care of any zero-padding\r\nstatic 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)\r\n{\r\n  const size_t start_idx = idx;\r\n\r\n  // pad spaces up to given width\r\n  if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) {\r\n    for (size_t i = len; i < width; i++) {\r\n      out(' ', buffer, idx++, maxlen);\r\n    }\r\n  }\r\n\r\n  // reverse string\r\n  while (len) {\r\n    out(buf[--len], buffer, idx++, maxlen);\r\n  }\r\n\r\n  // append pad spaces up to given width\r\n  if (flags & FLAGS_LEFT) {\r\n    while (idx - start_idx < width) {\r\n      out(' ', buffer, idx++, maxlen);\r\n    }\r\n  }\r\n\r\n  return idx;\r\n}\r\n\r\n\r\n// internal itoa format\r\nstatic 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)\r\n{\r\n  // pad leading zeros\r\n  if (!(flags & FLAGS_LEFT)) {\r\n    if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {\r\n      width--;\r\n    }\r\n    while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) {\r\n      buf[len++] = '0';\r\n    }\r\n    while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) {\r\n      buf[len++] = '0';\r\n    }\r\n  }\r\n\r\n  // handle hash\r\n  if (flags & FLAGS_HASH) {\r\n    if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) {\r\n      len--;\r\n      if (len && (base == 16U)) {\r\n        len--;\r\n      }\r\n    }\r\n    if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) {\r\n      buf[len++] = 'x';\r\n    }\r\n    else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) {\r\n      buf[len++] = 'X';\r\n    }\r\n    else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) {\r\n      buf[len++] = 'b';\r\n    }\r\n    if (len < PRINTF_NTOA_BUFFER_SIZE) {\r\n      buf[len++] = '0';\r\n    }\r\n  }\r\n\r\n  if (len < PRINTF_NTOA_BUFFER_SIZE) {\r\n    if (negative) {\r\n      buf[len++] = '-';\r\n    }\r\n    else if (flags & FLAGS_PLUS) {\r\n      buf[len++] = '+';  // ignore the space if the '+' exists\r\n    }\r\n    else if (flags & FLAGS_SPACE) {\r\n      buf[len++] = ' ';\r\n    }\r\n  }\r\n\r\n  return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags);\r\n}\r\n\r\n\r\n// internal itoa for 'long' type\r\nstatic 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)\r\n{\r\n  char buf[PRINTF_NTOA_BUFFER_SIZE];\r\n  size_t len = 0U;\r\n\r\n  // no hash for 0 values\r\n  if (!value) {\r\n    flags &= ~FLAGS_HASH;\r\n  }\r\n\r\n  // write if precision != 0 and value is != 0\r\n  if (!(flags & FLAGS_PRECISION) || value) {\r\n    do {\r\n      const char digit = (char)(value % base);\r\n      buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10;\r\n      value /= base;\r\n    } while (value && (len < PRINTF_NTOA_BUFFER_SIZE));\r\n  }\r\n\r\n  return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags);\r\n}\r\n\r\n\r\n// internal itoa for 'long long' type\r\n#if defined(PRINTF_SUPPORT_LONG_LONG)\r\nstatic 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)\r\n{\r\n  char buf[PRINTF_NTOA_BUFFER_SIZE];\r\n  size_t len = 0U;\r\n\r\n  // no hash for 0 values\r\n  if (!value) {\r\n    flags &= ~FLAGS_HASH;\r\n  }\r\n\r\n  // write if precision != 0 and value is != 0\r\n  if (!(flags & FLAGS_PRECISION) || value) {\r\n    do {\r\n      const char digit = (char)(value % base);\r\n      buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10;\r\n      value /= base;\r\n    } while (value && (len < PRINTF_NTOA_BUFFER_SIZE));\r\n  }\r\n\r\n  return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags);\r\n}\r\n#endif  // PRINTF_SUPPORT_LONG_LONG\r\n\r\n\r\n#if defined(PRINTF_SUPPORT_FLOAT)\r\n\r\n#if defined(PRINTF_SUPPORT_EXPONENTIAL)\r\n// forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT\r\nstatic 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);\r\n#endif\r\n\r\n\r\n// internal ftoa for fixed decimal floating point\r\nstatic 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)\r\n{\r\n  char buf[PRINTF_FTOA_BUFFER_SIZE];\r\n  size_t len  = 0U;\r\n  double diff = 0.0;\r\n\r\n  // powers of 10\r\n  static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };\r\n\r\n  // test for special values\r\n  if (value != value)\r\n    return _out_rev(out, buffer, idx, maxlen, \"nan\", 3, width, flags);\r\n  if (value < -DBL_MAX)\r\n    return _out_rev(out, buffer, idx, maxlen, \"fni-\", 4, width, flags);\r\n  if (value > DBL_MAX)\r\n    return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? \"fni+\" : \"fni\", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags);\r\n\r\n  // test for very large values\r\n  // standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad\r\n  if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) {\r\n#if defined(PRINTF_SUPPORT_EXPONENTIAL)\r\n    return _etoa(out, buffer, idx, maxlen, value, prec, width, flags);\r\n#else\r\n    return 0U;\r\n#endif\r\n  }\r\n\r\n  // test for negative\r\n  bool negative = false;\r\n  if (value < 0) {\r\n    negative = true;\r\n    value = 0 - value;\r\n  }\r\n\r\n  // set default precision, if not set explicitly\r\n  if (!(flags & FLAGS_PRECISION)) {\r\n    prec = PRINTF_DEFAULT_FLOAT_PRECISION;\r\n  }\r\n  // limit precision to 9, cause a prec >= 10 can lead to overflow errors\r\n  while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) {\r\n    buf[len++] = '0';\r\n    prec--;\r\n  }\r\n\r\n  int whole = (int)value;\r\n  double tmp = (value - whole) * pow10[prec];\r\n  unsigned long frac = (unsigned long)tmp;\r\n  diff = tmp - frac;\r\n\r\n  if (diff > 0.5) {\r\n    ++frac;\r\n    // handle rollover, e.g. case 0.99 with prec 1 is 1.0\r\n    if (frac >= pow10[prec]) {\r\n      frac = 0;\r\n      ++whole;\r\n    }\r\n  }\r\n  else if (diff < 0.5) {\r\n  }\r\n  else if ((frac == 0U) || (frac & 1U)) {\r\n    // if halfway, round up if odd OR if last digit is 0\r\n    ++frac;\r\n  }\r\n\r\n  if (prec == 0U) {\r\n    diff = value - (double)whole;\r\n    if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) {\r\n      // exactly 0.5 and ODD, then round up\r\n      // 1.5 -> 2, but 2.5 -> 2\r\n      ++whole;\r\n    }\r\n  }\r\n  else {\r\n    unsigned int count = prec;\r\n    // now do fractional part, as an unsigned number\r\n    while (len < PRINTF_FTOA_BUFFER_SIZE) {\r\n      --count;\r\n      buf[len++] = (char)(48U + (frac % 10U));\r\n      if (!(frac /= 10U)) {\r\n        break;\r\n      }\r\n    }\r\n    // add extra 0s\r\n    while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) {\r\n      buf[len++] = '0';\r\n    }\r\n    if (len < PRINTF_FTOA_BUFFER_SIZE) {\r\n      // add decimal\r\n      buf[len++] = '.';\r\n    }\r\n  }\r\n\r\n  // do whole part, number is reversed\r\n  while (len < PRINTF_FTOA_BUFFER_SIZE) {\r\n    buf[len++] = (char)(48 + (whole % 10));\r\n    if (!(whole /= 10)) {\r\n      break;\r\n    }\r\n  }\r\n\r\n  // pad leading zeros\r\n  if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) {\r\n    if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {\r\n      width--;\r\n    }\r\n    while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) {\r\n      buf[len++] = '0';\r\n    }\r\n  }\r\n\r\n  if (len < PRINTF_FTOA_BUFFER_SIZE) {\r\n    if (negative) {\r\n      buf[len++] = '-';\r\n    }\r\n    else if (flags & FLAGS_PLUS) {\r\n      buf[len++] = '+';  // ignore the space if the '+' exists\r\n    }\r\n    else if (flags & FLAGS_SPACE) {\r\n      buf[len++] = ' ';\r\n    }\r\n  }\r\n\r\n  return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags);\r\n}\r\n\r\n\r\n#if defined(PRINTF_SUPPORT_EXPONENTIAL)\r\n// internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse <m.jasperse@gmail.com>\r\nstatic 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)\r\n{\r\n  // check for NaN and special values\r\n  if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) {\r\n    return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags);\r\n  }\r\n\r\n  // determine the sign\r\n  const bool negative = value < 0;\r\n  if (negative) {\r\n    value = -value;\r\n  }\r\n\r\n  // default precision\r\n  if (!(flags & FLAGS_PRECISION)) {\r\n    prec = PRINTF_DEFAULT_FLOAT_PRECISION;\r\n  }\r\n\r\n  // determine the decimal exponent\r\n  // based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c)\r\n  union {\r\n    uint64_t U;\r\n    double   F;\r\n  } conv;\r\n\r\n  conv.F = value;\r\n  int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023;           // effectively log2\r\n  conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U);  // drop the exponent so conv.F is now in [1,2)\r\n  // now approximate log10 from the log2 integer part and an expansion of ln around 1.5\r\n  int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168);\r\n  // now we want to compute 10^expval but we want to be sure it won't overflow\r\n  exp2 = (int)(expval * 3.321928094887362 + 0.5);\r\n  const double z  = expval * 2.302585092994046 - exp2 * 0.6931471805599453;\r\n  const double z2 = z * z;\r\n  conv.U = (uint64_t)(exp2 + 1023) << 52U;\r\n  // compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex\r\n  conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14)))));\r\n  // correct for rounding errors\r\n  if (value < conv.F) {\r\n    expval--;\r\n    conv.F /= 10;\r\n  }\r\n\r\n  // the exponent format is \"%+03d\" and largest value is \"307\", so set aside 4-5 characters\r\n  unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U;\r\n\r\n  // in \"%g\" mode, \"prec\" is the number of *significant figures* not decimals\r\n  if (flags & FLAGS_ADAPT_EXP) {\r\n    // do we want to fall-back to \"%f\" mode?\r\n    if ((value >= 1e-4) && (value < 1e6)) {\r\n      if ((int)prec > expval) {\r\n        prec = (unsigned)((int)prec - expval - 1);\r\n      }\r\n      else {\r\n        prec = 0;\r\n      }\r\n      flags |= FLAGS_PRECISION;   // make sure _ftoa respects precision\r\n      // no characters in exponent\r\n      minwidth = 0U;\r\n      expval   = 0;\r\n    }\r\n    else {\r\n      // we use one sigfig for the whole part\r\n      if ((prec > 0) && (flags & FLAGS_PRECISION)) {\r\n        --prec;\r\n      }\r\n    }\r\n  }\r\n\r\n  // will everything fit?\r\n  unsigned int fwidth = width;\r\n  if (width > minwidth) {\r\n    // we didn't fall-back so subtract the characters required for the exponent\r\n    fwidth -= minwidth;\r\n  } else {\r\n    // not enough characters, so go back to default sizing\r\n    fwidth = 0U;\r\n  }\r\n  if ((flags & FLAGS_LEFT) && minwidth) {\r\n    // if we're padding on the right, DON'T pad the floating part\r\n    fwidth = 0U;\r\n  }\r\n\r\n  // rescale the float value\r\n  if (expval) {\r\n    value /= conv.F;\r\n  }\r\n\r\n  // output the floating part\r\n  const size_t start_idx = idx;\r\n  idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP);\r\n\r\n  // output the exponent part\r\n  if (minwidth) {\r\n    // output the exponential symbol\r\n    out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen);\r\n    // output the exponent value\r\n    idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS);\r\n    // might need to right-pad spaces\r\n    if (flags & FLAGS_LEFT) {\r\n      while (idx - start_idx < width) out(' ', buffer, idx++, maxlen);\r\n    }\r\n  }\r\n  return idx;\r\n}\r\n#endif  // PRINTF_SUPPORT_EXPONENTIAL\r\n#endif  // PRINTF_SUPPORT_FLOAT\r\n\r\n\r\n// internal vsnprintf\r\nstatic int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va)\r\n{\r\n  unsigned int flags, width, precision, n;\r\n  size_t idx = 0U;\r\n\r\n  if (!buffer) {\r\n    // use null output function\r\n    out = _out_null;\r\n  }\r\n\r\n  while (*format)\r\n  {\r\n    // format specifier?  %[flags][width][.precision][length]\r\n    if (*format != '%') {\r\n      // no\r\n      out(*format, buffer, idx++, maxlen);\r\n      format++;\r\n      continue;\r\n    }\r\n    else {\r\n      // yes, evaluate it\r\n      format++;\r\n    }\r\n\r\n    // evaluate flags\r\n    flags = 0U;\r\n    do {\r\n      switch (*format) {\r\n        case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break;\r\n        case '-': flags |= FLAGS_LEFT;    format++; n = 1U; break;\r\n        case '+': flags |= FLAGS_PLUS;    format++; n = 1U; break;\r\n        case ' ': flags |= FLAGS_SPACE;   format++; n = 1U; break;\r\n        case '#': flags |= FLAGS_HASH;    format++; n = 1U; break;\r\n        default :                                   n = 0U; break;\r\n      }\r\n    } while (n);\r\n\r\n    // evaluate width field\r\n    width = 0U;\r\n    if (_is_digit(*format)) {\r\n      width = _atoi(&format);\r\n    }\r\n    else if (*format == '*') {\r\n      const int w = va_arg(va, int);\r\n      if (w < 0) {\r\n        flags |= FLAGS_LEFT;    // reverse padding\r\n        width = (unsigned int)-w;\r\n      }\r\n      else {\r\n        width = (unsigned int)w;\r\n      }\r\n      format++;\r\n    }\r\n\r\n    // evaluate precision field\r\n    precision = 0U;\r\n    if (*format == '.') {\r\n      flags |= FLAGS_PRECISION;\r\n      format++;\r\n      if (_is_digit(*format)) {\r\n        precision = _atoi(&format);\r\n      }\r\n      else if (*format == '*') {\r\n        const int prec = (int)va_arg(va, int);\r\n        precision = prec > 0 ? (unsigned int)prec : 0U;\r\n        format++;\r\n      }\r\n    }\r\n\r\n    // evaluate length field\r\n    switch (*format) {\r\n      case 'l' :\r\n        flags |= FLAGS_LONG;\r\n        format++;\r\n        if (*format == 'l') {\r\n          flags |= FLAGS_LONG_LONG;\r\n          format++;\r\n        }\r\n        break;\r\n      case 'h' :\r\n        flags |= FLAGS_SHORT;\r\n        format++;\r\n        if (*format == 'h') {\r\n          flags |= FLAGS_CHAR;\r\n          format++;\r\n        }\r\n        break;\r\n#if defined(PRINTF_SUPPORT_PTRDIFF_T)\r\n      case 't' :\r\n        flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);\r\n        format++;\r\n        break;\r\n#endif\r\n      case 'j' :\r\n        flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);\r\n        format++;\r\n        break;\r\n      case 'z' :\r\n        flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);\r\n        format++;\r\n        break;\r\n      default :\r\n        break;\r\n    }\r\n\r\n    // evaluate specifier\r\n    switch (*format) {\r\n      case 'd' :\r\n      case 'i' :\r\n      case 'u' :\r\n      case 'x' :\r\n      case 'X' :\r\n      case 'o' :\r\n      case 'b' : {\r\n        // set the base\r\n        unsigned int base;\r\n        if (*format == 'x' || *format == 'X') {\r\n          base = 16U;\r\n        }\r\n        else if (*format == 'o') {\r\n          base =  8U;\r\n        }\r\n        else if (*format == 'b') {\r\n          base =  2U;\r\n        }\r\n        else {\r\n          base = 10U;\r\n          flags &= ~FLAGS_HASH;   // no hash for dec format\r\n        }\r\n        // uppercase\r\n        if (*format == 'X') {\r\n          flags |= FLAGS_UPPERCASE;\r\n        }\r\n\r\n        // no plus or space flag for u, x, X, o, b\r\n        if ((*format != 'i') && (*format != 'd')) {\r\n          flags &= ~(FLAGS_PLUS | FLAGS_SPACE);\r\n        }\r\n\r\n        // ignore '0' flag when precision is given\r\n        if (flags & FLAGS_PRECISION) {\r\n          flags &= ~FLAGS_ZEROPAD;\r\n        }\r\n\r\n        // convert the integer\r\n        if ((*format == 'i') || (*format == 'd')) {\r\n          // signed\r\n          if (flags & FLAGS_LONG_LONG) {\r\n#if defined(PRINTF_SUPPORT_LONG_LONG)\r\n            const long long value = va_arg(va, long long);\r\n            idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);\r\n#endif\r\n          }\r\n          else if (flags & FLAGS_LONG) {\r\n            const long value = va_arg(va, long);\r\n            idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);\r\n          }\r\n          else {\r\n            const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int);\r\n            idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);\r\n          }\r\n        }\r\n        else {\r\n          // unsigned\r\n          if (flags & FLAGS_LONG_LONG) {\r\n#if defined(PRINTF_SUPPORT_LONG_LONG)\r\n            idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags);\r\n#endif\r\n          }\r\n          else if (flags & FLAGS_LONG) {\r\n            idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags);\r\n          }\r\n          else {\r\n            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);\r\n            idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags);\r\n          }\r\n        }\r\n        format++;\r\n        break;\r\n      }\r\n#if defined(PRINTF_SUPPORT_FLOAT)\r\n      case 'f' :\r\n      case 'F' :\r\n        if (*format == 'F') flags |= FLAGS_UPPERCASE;\r\n        idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);\r\n        format++;\r\n        break;\r\n#if defined(PRINTF_SUPPORT_EXPONENTIAL)\r\n      case 'e':\r\n      case 'E':\r\n      case 'g':\r\n      case 'G':\r\n        if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP;\r\n        if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE;\r\n        idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);\r\n        format++;\r\n        break;\r\n#endif  // PRINTF_SUPPORT_EXPONENTIAL\r\n#endif  // PRINTF_SUPPORT_FLOAT\r\n      case 'c' : {\r\n        unsigned int l = 1U;\r\n        // pre padding\r\n        if (!(flags & FLAGS_LEFT)) {\r\n          while (l++ < width) {\r\n            out(' ', buffer, idx++, maxlen);\r\n          }\r\n        }\r\n        // char output\r\n        out((char)va_arg(va, int), buffer, idx++, maxlen);\r\n        // post padding\r\n        if (flags & FLAGS_LEFT) {\r\n          while (l++ < width) {\r\n            out(' ', buffer, idx++, maxlen);\r\n          }\r\n        }\r\n        format++;\r\n        break;\r\n      }\r\n\r\n      case 's' : {\r\n        const char* p = va_arg(va, char*);\r\n        unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1);\r\n        // pre padding\r\n        if (flags & FLAGS_PRECISION) {\r\n          l = (l < precision ? l : precision);\r\n        }\r\n        if (!(flags & FLAGS_LEFT)) {\r\n          while (l++ < width) {\r\n            out(' ', buffer, idx++, maxlen);\r\n          }\r\n        }\r\n        // string output\r\n        while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) {\r\n          out(*(p++), buffer, idx++, maxlen);\r\n        }\r\n        // post padding\r\n        if (flags & FLAGS_LEFT) {\r\n          while (l++ < width) {\r\n            out(' ', buffer, idx++, maxlen);\r\n          }\r\n        }\r\n        format++;\r\n        break;\r\n      }\r\n\r\n      case 'p' : {\r\n        width = sizeof(void*) * 2U;\r\n        flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE;\r\n#if defined(PRINTF_SUPPORT_LONG_LONG)\r\n        const bool is_ll = sizeof(uintptr_t) == sizeof(long long);\r\n        if (is_ll) {\r\n          idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags);\r\n        }\r\n        else {\r\n#endif\r\n          idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags);\r\n#if defined(PRINTF_SUPPORT_LONG_LONG)\r\n        }\r\n#endif\r\n        format++;\r\n        break;\r\n      }\r\n\r\n      case '%' :\r\n        out('%', buffer, idx++, maxlen);\r\n        format++;\r\n        break;\r\n\r\n      default :\r\n        out(*format, buffer, idx++, maxlen);\r\n        format++;\r\n        break;\r\n    }\r\n  }\r\n\r\n  // termination\r\n  out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen);\r\n\r\n  // return written chars without terminating \\0\r\n  return (int)idx;\r\n}\r\n\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nint printf_(const char* format, ...)\r\n{\r\n  va_list va;\r\n  va_start(va, format);\r\n  char buffer[1];\r\n  const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va);\r\n  va_end(va);\r\n  return ret;\r\n}\r\n\r\n\r\nint sprintf_(char* buffer, const char* format, ...)\r\n{\r\n  va_list va;\r\n  va_start(va, format);\r\n  const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va);\r\n  va_end(va);\r\n  return ret;\r\n}\r\n\r\n\r\nint snprintf_(char* buffer, size_t count, const char* format, ...)\r\n{\r\n  va_list va;\r\n  va_start(va, format);\r\n  const int ret = _vsnprintf(_out_buffer, buffer, count, format, va);\r\n  va_end(va);\r\n  return ret;\r\n}\r\n\r\n\r\nint vprintf_(const char* format, va_list va)\r\n{\r\n  char buffer[1];\r\n  return _vsnprintf(_out_char, buffer, (size_t)-1, format, va);\r\n}\r\n\r\n\r\nint vsnprintf_(char* buffer, size_t count, const char* format, va_list va)\r\n{\r\n  return _vsnprintf(_out_buffer, buffer, count, format, va);\r\n}\r\n\r\n\r\nint fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...)\r\n{\r\n  va_list va;\r\n  va_start(va, format);\r\n  const out_fct_wrap_type out_fct_wrap = { out, arg };\r\n  const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va);\r\n  va_end(va);\r\n  return ret;\r\n}\r\n"
  },
  {
    "path": "eddy-ng/printf.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\r\n// \\author (c) Marco Paland (info@paland.com)\r\n//             2014-2019, PALANDesign Hannover, Germany\r\n//\r\n// \\license The MIT License (MIT)\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files (the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions:\r\n// \r\n// The above copyright notice and this permission notice shall be included in\r\n// all copies or substantial portions of the Software.\r\n// \r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n// THE SOFTWARE.\r\n//\r\n// \\brief Tiny printf, sprintf and snprintf implementation, optimized for speed on\r\n//        embedded systems with a very limited resources.\r\n//        Use this instead of bloated standard/newlib printf.\r\n//        These routines are thread safe and reentrant.\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\n#ifndef _PRINTF_H_\r\n#define _PRINTF_H_\r\n\r\n#include <stdarg.h>\r\n#include <stddef.h>\r\n\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n\r\n\r\n/**\r\n * Output a character to a custom device like UART, used by the printf() function\r\n * This function is declared here only. You have to write your custom implementation somewhere\r\n * \\param character Character to output\r\n */\r\nvoid _putchar(char character);\r\n\r\n\r\n/**\r\n * Tiny printf implementation\r\n * You have to implement _putchar if you use printf()\r\n * To avoid conflicts with the regular printf() API it is overridden by macro defines\r\n * and internal underscore-appended functions like printf_() are used\r\n * \\param format A string that specifies the format of the output\r\n * \\return The number of characters that are written into the array, not counting the terminating null character\r\n */\r\n#define printf printf_\r\nint printf_(const char* format, ...);\r\n\r\n\r\n/**\r\n * Tiny sprintf implementation\r\n * Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD!\r\n * \\param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output!\r\n * \\param format A string that specifies the format of the output\r\n * \\return The number of characters that are WRITTEN into the buffer, not counting the terminating null character\r\n */\r\n#define sprintf sprintf_\r\nint sprintf_(char* buffer, const char* format, ...);\r\n\r\n\r\n/**\r\n * Tiny snprintf/vsnprintf implementation\r\n * \\param buffer A pointer to the buffer where to store the formatted string\r\n * \\param count The maximum number of characters to store in the buffer, including a terminating null character\r\n * \\param format A string that specifies the format of the output\r\n * \\param va A value identifying a variable arguments list\r\n * \\return The number of characters that COULD have been written into the buffer, not counting the terminating\r\n *         null character. A value equal or larger than count indicates truncation. Only when the returned value\r\n *         is non-negative and less than count, the string has been completely written.\r\n */\r\n#define snprintf  snprintf_\r\n#define vsnprintf vsnprintf_\r\nint  snprintf_(char* buffer, size_t count, const char* format, ...);\r\nint vsnprintf_(char* buffer, size_t count, const char* format, va_list va);\r\n\r\n\r\n/**\r\n * Tiny vprintf implementation\r\n * \\param format A string that specifies the format of the output\r\n * \\param va A value identifying a variable arguments list\r\n * \\return The number of characters that are WRITTEN into the buffer, not counting the terminating null character\r\n */\r\n#define vprintf vprintf_\r\nint vprintf_(const char* format, va_list va);\r\n\r\n\r\n/**\r\n * printf with output function\r\n * You may use this as dynamic alternative to printf() with its fixed _putchar() output\r\n * \\param out An output function which takes one character and an argument pointer\r\n * \\param arg An argument pointer for user data passed to output function\r\n * \\param format A string that specifies the format of the output\r\n * \\return The number of characters that are sent to the output function, not counting the terminating null character\r\n */\r\nint fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...);\r\n\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n\r\n#endif  // _PRINTF_H_\r\n"
  },
  {
    "path": "eddy-ng/printf_config.h",
    "content": "#ifndef PRINTF_CONFIG_H_\n#define PRINTF_CONFIG_H_\n\n#define PRINTF_DISABLE_SUPPORT_EXPONENTIAL\n#define PRINTF_DISABLE_SUPPORT_LONG_LONG\n#define PRINTF_DISABLE_SUPPORT_PTRDIFF_T\n\n#endif\n"
  },
  {
    "path": "eddy-ng/pyproject.toml",
    "content": "[project]\nname = \"probe-eddy-ng\"\nversion = \"0.1.0\"\ndescription = \"Add your description here\"\nrequires-python = \">=3.12\"\ndependencies = [\n    \"klippy>=0.0\",\n    \"plotly>=6.0.1\",\n    \"scipy>=1.15.2\",\n]\n\n[tool.pyright]\nexecutionEnvironments = [\n  { root = \"~/proj/k/kalico\", extraPaths = [ ] },\n]\n"
  },
  {
    "path": "eddy-ng/sensor_ldc1612_ng.c",
    "content": "// Support for eddy current sensor data from ldc1612 chip (v2)\n//\n// Copyright (C) 2023 Alan.Ma <tech@biqu3d.com>\n// Copyright (C) 2024  Kevin O'Connor <kevin@koconnor.net>\n// Copyright (C) 2025 Vladimir Vukicevic <vladimir@pobox.com>\n//\n// This file may be distributed under the terms of the GNU GPLv3 license.\n\n#include <string.h> // memcpy\n#include <stdbool.h>\n#include \"autoconf.h\"\n#include \"basecmd.h\" // oid_alloc\n#include \"board/irq.h\" // irq_disable\n#include \"board/misc.h\" // timer_read_time\n#include \"command.h\" // DECL_COMMAND\n#include \"i2ccmds.h\" // i2cdev_oid_lookup\n#include \"sched.h\" // DECL_TASK\n#include \"sensor_bulk.h\" // sensor_bulk_report\n#include \"trsync.h\" // trsync_do_trigger\n\n#if !defined(LDC_DEBUG)\n#define LDC_DEBUG 0\n#endif\n\n#if CONFIG_MACH_STM32F0\n// For Cartographer\n#include \"board/internal.h\"\n#include \"board/gpio.h\"\n#define SUPPORT_CARTOGRAPHER 1\n#else\n#define SUPPORT_CARTOGRAPHER 0\n#endif\n\n#if LDC_DEBUG > 0\n#include \"printf.h\"\nvoid dprint(const char *fmt, ...);\n#else\n#define dprint(...) do { } while (0)\n#endif\n\nenum {\n    // There's a pending sample that needs to be read\n    LDC_PENDING = 1<<0,\n    // Use the intb pin to detect when a sample is ready\n    // vs. just polling\n    LDC_HAVE_INTB = 1<<1,\n};\n\n// Number of bytes in each ldc1612 sample. Always 4.\n#define BYTES_PER_SAMPLE 4\n\n// should match ldc1612_ng.py\n#define HOME_MODE_NONE 0\n#define HOME_MODE_HOME 1\n#define HOME_MODE_WMA 2\n#define HOME_MODE_SOS 3\n\n// should match probe_eddy.py\n#define REASON_ERROR_SENSOR 0\n#define REASON_ERROR_PROBE_TOO_LOW 1\n#define REASON_ERROR_TOO_EARLY 2\n\n// should match ldc1612_ng.py\n#define PRODUCT_UNKNOWN 0\n#define PRODUCT_BTT_EDDY 1\n#define PRODUCT_CARTOGRAPHER 2\n#define PRODUCT_MELLOW_FLY 3\n#define PRODUCT_LDC1612_INTERNAL_CLK 4\n\n// Chip registers\n#define REG_DATA0_MSB 0x00\n#define REG_DATA0_LSB 0x01\n#define REG_STATUS    0x18\n\n// Error flags reported in samples: undeer range, over range, watchdog, amplitude \n#define SAMPLE_ERR(data) ((data) >> 28)\n#define SAMPLE_ERR_UR 0x8\n#define SAMPLE_ERR_OR 0x4\n#define SAMPLE_ERR_WD 0x2\n#define SAMPLE_ERR_AE 0x1\n\n// conversion under range\n#define STATUS_ERR_UR 0x2000\n// conversion over range\n#define STATUS_ERR_OR 0x1000\n// watchdog timeout\n#define STATUS_ERR_WD 0x0800\n// amplitude high error\n#define STATUS_ERR_AHE 0x0400\n// amplitude low error\n#define STATUS_ERR_ALE 0x0200\n\n// Homing configuration\n#define FREQ_WINDOW_SIZE 16\n#define WMA_D_WINDOW_SIZE 4\n\n#define MAX_SOS_SECTIONS 4\n\nstruct sosfilter_sos {\n    uint8_t num_sections;\n    float sos[MAX_SOS_SECTIONS*6];\n};\n\nstruct ldc1612_ng_homing_wma_tap {\n    // the tap detection threshold: specifically, the total downward\n    // change in the frequency derivative before we see a direction\n    // reveral (the windowed moving average of the derivative of the wmd\n    // to be exact)\n    int32_t tap_threshold;\n\n    // number of samples to ignore for detection (to avoid spikes before\n    // we fill buffers)\n    uint8_t init_sample_count;\n\n    // frequencies are always positive, as is their average\n    // the derivative however is signed\n    uint32_t freq_buffer[FREQ_WINDOW_SIZE];\n    int32_t wma_d_buf[WMA_D_WINDOW_SIZE];\n    // current index in freq/deriv buffers\n    uint8_t freq_i;\n    uint8_t wma_d_i;\n\n    uint32_t wma; // last computed weighted moving average\n    int32_t wma_d_avg; // last computed wma derivative average\n\n    // the wema_d_avg at the start\n    int32_t tap_start_value;\n};\n\nstruct ldc1612_ng_homing_sos_tap {\n    float state[MAX_SOS_SECTIONS*4];\n    float tap_threshold;\n\n    float frequency_offset;\n    float tap_start_value;\n    float last_value;\n};\n\nstruct ldc1612_ng_homing {\n    uint8_t mode;\n\n    // frequency we must pass through to have a valid home/tap\n    uint32_t safe_start_freq;\n    // and it must happen after this time\n    uint32_t safe_start_time;\n\n    // the frequency to trigger on for homing, or\n    // the second threshold before we start looking for a tap\n    uint32_t homing_trigger_freq;\n\n    // What time we fire with the trigger -- either the time homing\n    // triggered, or the computed time for the tap (which will be\n    // earlier than when the tap was detected).\n    uint32_t trigger_time;\n\n    // If it was a tap, the start of tap detection\n    uint32_t tap_start_time;\n\n    // Number of errors we've seen in a row\n    uint8_t error_count;\n    // Number we're allowed to see, from home setup\n    uint8_t error_threshold;\n    // The final error that caused an abort\n    uint32_t error;\n\n    union {\n        struct ldc1612_ng_homing_wma_tap wma_tap;\n        struct ldc1612_ng_homing_sos_tap sos_tap;\n    };\n};\n\nstruct ldc1612_ng {\n    struct timer timer;\n    struct i2cdev_s *i2c;\n    struct sensor_bulk sb;\n    struct gpio_in intb_pin;\n\n    uint8_t product;\n    float sensor_cvt;\n\n    uint32_t rest_ticks;\n    uint8_t flags;\n    uint16_t last_status;\n    uint32_t last_read_value;\n\n    // Samples per second (configurable)\n    uint32_t data_rate;\n\n    // homing triggers\n    struct trsync *ts;\n    uint8_t success_reason;\n    uint8_t other_reason_base;\n\n    // active sosfilter\n    struct sosfilter_sos sos_filter;\n\n    // homing state\n    struct ldc1612_ng_homing homing;\n\n#if SUPPORT_CARTOGRAPHER\n    struct gpio_out led_gpio;\n#endif\n};\n\nvoid command_config_ldc1612_ng(uint32_t *args);\n\nstatic void read_reg(struct ldc1612_ng* ld, uint8_t reg, uint8_t* res);\nstatic uint16_t read_reg_status(struct ldc1612_ng* ld);\n\nstatic uint_fast8_t ldc1612_ng_timer_event(struct timer* timer);\n\nstatic void ldc1612_ng_update(struct ldc1612_ng* ld, uint8_t oid);\n\nstatic void check_homing(struct ldc1612_ng* ld, uint32_t data, uint32_t time);\nstatic void check_wma_tap(struct ldc1612_ng* ld, uint32_t data, uint32_t time);\nstatic void check_sos_tap(struct ldc1612_ng* ld, uint32_t data, uint32_t time);\n\n//\n// Core sample timers and loop\n//\nstatic struct task_wake ldc1612_ng_wake;\n\nstatic int\ncheck_intb_asserted(struct ldc1612_ng *ld)\n{\n    return !gpio_in_read(ld->intb_pin);\n}\n\nvoid\nldc1612_ng_task(void)\n{\n    if (!sched_check_wake(&ldc1612_ng_wake))\n        return;\n    uint8_t oid;\n    struct ldc1612_ng *ld;\n    foreach_oid(oid, ld, command_config_ldc1612_ng) {\n        uint_fast8_t flags = ld->flags;\n        if (!(flags & LDC_PENDING))\n            continue;\n        ldc1612_ng_update(ld, oid);\n    }\n}\nDECL_TASK(ldc1612_ng_task);\n\nuint_fast8_t\nldc1612_ng_timer_event(struct timer *timer)\n{\n    struct ldc1612_ng *ld = container_of(timer, struct ldc1612_ng, timer);\n\n    if (ld->flags & LDC_PENDING)\n        ld->sb.possible_overflows++;\n\n    if (!(ld->flags & LDC_HAVE_INTB) || check_intb_asserted(ld)) {\n        ld->flags |= LDC_PENDING;\n        sched_wake_task(&ldc1612_ng_wake);\n    }\n\n    // reschedule to run in rest_ticks\n    ld->timer.waketime += ld->rest_ticks;\n    return SF_RESCHEDULE;\n}\n\n// Read a register on the ldc1612\nvoid\nread_reg(struct ldc1612_ng *ld, uint8_t reg, uint8_t *res)\n{\n    int ret = i2c_dev_read(ld->i2c, sizeof(reg), &reg, 2, res);\n    i2c_shutdown_on_err(ret);\n}\n\n// Read the status register on the ldc1612\nuint16_t\nread_reg_status(struct ldc1612_ng *ld)\n{\n    uint8_t data_status[2];\n    read_reg(ld, REG_STATUS, data_status);\n    ld->last_status = (data_status[0] << 8) | data_status[1];\n    return ld->last_status;\n}\n\n// Notify trsync of event\nstatic void\nnotify_trigger(struct ldc1612_ng *ld, uint32_t time, uint8_t reason)\n{\n    ld->homing.mode = 0;\n    trsync_do_trigger(ld->ts, reason);\n    dprint(\"ZZZ notify_trigger: %u at %u\", reason, time);\n}\n\nvoid\nldc1612_ng_shutdown(void)\n{\n    // make sure we stop measurements on shutdown so we don't\n    // spam host on startup\n    uint8_t oid;\n    struct ldc1612_ng *ld;\n    foreach_oid(oid, ld, command_config_ldc1612_ng) {\n        sched_del_timer(&ld->timer);\n        ld->flags &= ~LDC_PENDING;\n        ld->rest_ticks = 0;\n    }\n}\nDECL_SHUTDOWN(ldc1612_ng_shutdown);\n\nstatic void\nconfig_ldc1612_ng(uint32_t oid, uint32_t i2c_oid, uint8_t product, int32_t intb_pin)\n{\n    dprint(\"EDDYng cfg o=%u i=%u b=%d\", oid, i2c_oid, intb_pin);\n\n    struct ldc1612_ng *ld = oid_alloc(oid, command_config_ldc1612_ng, sizeof(*ld));\n\n    ld->timer.func = ldc1612_ng_timer_event;\n    ld->i2c = i2cdev_oid_lookup(i2c_oid);\n    if (intb_pin != -1) {\n        ld->intb_pin = gpio_in_setup(intb_pin, 1);\n        ld->flags = LDC_HAVE_INTB;\n    }\n    ld->product = product;\n\n    switch (product) {\n    case PRODUCT_UNKNOWN:\n    case PRODUCT_BTT_EDDY:\n        ld->sensor_cvt = 12000000.0f / (float)(1<<28);\n        break;\n    case PRODUCT_MELLOW_FLY:\n        ld->sensor_cvt = 40000000.0f / (float)(1<<28);\n        break;\n#if SUPPORT_CARTOGRAPHER\n    case PRODUCT_CARTOGRAPHER:\n        ld->sensor_cvt = 24000000.0f / (float)(1<<28);\n\n        // This enables the ldc1612 (CS?)\n        gpio_out_setup(GPIO('A', 15), 0);\n\n        // The Cartographer hardware uses a timer in the STM32F0\n        // to generate a 24MHz reference clock for the ldc1612.\n        // Uses a new _with_max setup here because otherwise we\n        // can't actually get to 24MHz from 48MHz. This could be\n        // configured from the python side but that requires\n        // adding a bunch of new commands.\n        gpio_pwm_setup_with_max(GPIO('B', 4), 1, 1, 2);\n\n        // There's a LED -- do something with it in the future,\n        // showing homing progress\n        ld->led_gpio = gpio_out_setup(GPIO('B', 5), 1);\n        gpio_out_write(ld->led_gpio, 1);\n\n        // There's also a temp sensor on A4, but we can\n        // pull that out on the python side.\n        break;\n#endif\n    case PRODUCT_LDC1612_INTERNAL_CLK:\n        ld->sensor_cvt = 43400000.0f / (float)(1<<28);\n        break;\n    default:\n        shutdown(\"ldc1612_ng: unknown product\");\n    }\n}\n\nvoid\ncommand_config_ldc1612_ng(uint32_t *args)\n{\n    uint32_t oid = args[0];\n    uint32_t i2c_oid = args[1];\n    uint8_t product = args[2];\n\n    config_ldc1612_ng(oid, i2c_oid, product, -1);\n}\nDECL_COMMAND(command_config_ldc1612_ng, \"config_ldc1612_ng oid=%c i2c_oid=%c product=%i\");\n\nvoid\ncommand_config_ldc1612_ng_with_intb(uint32_t *args)\n{\n    uint32_t oid = args[0];\n    uint32_t i2c_oid = args[1];\n    uint8_t product = args[2];\n    uint32_t intb_pin = args[3];\n\n    config_ldc1612_ng(oid, i2c_oid, product, intb_pin);\n}\nDECL_COMMAND(command_config_ldc1612_ng_with_intb,\n             \"config_ldc1612_ng_with_intb oid=%c i2c_oid=%c product=%i intb_pin=%c\");\n\nvoid\ncommand_query_ldc1612_ng_latched_status(uint32_t *args)\n{\n    struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng);\n\n    uint32_t status = ld->last_status;\n    uint32_t lastval = ld->last_read_value;\n\n    // If we're not actively running, then read the status and\n    // value directly\n    if (ld->rest_ticks == 0) {\n        status = read_reg_status(ld);\n        uint8_t d[4];\n        read_reg(ld, REG_DATA0_MSB, &d[0]);\n        read_reg(ld, REG_DATA0_LSB, &d[2]);\n\n        lastval =   ((uint32_t)d[0] << 24)\n                  | ((uint32_t)d[1] << 16)\n                  | ((uint32_t)d[2] << 8)\n                  | ((uint32_t)d[3]);\n    }\n\n    sendf(\"ldc1612_ng_latched_status oid=%c status=%u lastval=%u\"\n          , args[0], status, lastval);\n}\nDECL_COMMAND(command_query_ldc1612_ng_latched_status,\n             \"query_ldc1612_ng_latched_status_v2 oid=%c\");\n// ^ this command name is also used as an API version of sorts\n\nvoid\ncommand_ldc1612_ng_start_stop(uint32_t *args)\n{\n    struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng);\n\n    sched_del_timer(&ld->timer);\n    ld->flags &= ~LDC_PENDING;\n    ld->rest_ticks = args[1];\n\n    if (ld->rest_ticks == 0) {\n        // End measurements\n        dprint(\"ZZZ stop\");\n        return;\n    }\n\n    dprint(\"ZZZ start\");\n\n    // Start new measurements query\n    sensor_bulk_reset(&ld->sb);\n    irq_disable();\n    ld->timer.waketime = timer_read_time() + ld->rest_ticks;\n    sched_add_timer(&ld->timer);\n    irq_enable();\n}\nDECL_COMMAND(command_ldc1612_ng_start_stop, \"ldc1612_ng_start_stop oid=%c rest_ticks=%u\");\n\nvoid\ncommand_ldc1612_ng_query_bulk_status(uint32_t *args)\n{\n    struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng);\n\n    if (ld->flags & LDC_HAVE_INTB) {\n        // Check if a sample is pending in the chip via the intb line\n        irq_disable();\n        uint32_t time = timer_read_time();\n        int p = check_intb_asserted(ld);\n        irq_enable();\n        sensor_bulk_status(&ld->sb, args[0], time, 0, p ? BYTES_PER_SAMPLE : 0);\n    } else {\n        // Query sensor to see if a sample is pending\n        uint32_t time1 = timer_read_time();\n        uint16_t status = read_reg_status(ld);\n        uint32_t time2 = timer_read_time();\n\n        uint32_t fifo = status & 0x08 ? BYTES_PER_SAMPLE : 0;\n        sensor_bulk_status(&ld->sb, args[0], time1, time2-time1, fifo);\n    }\n}\nDECL_COMMAND(command_ldc1612_ng_query_bulk_status, \"ldc1612_ng_query_bulk_status oid=%c\");\n\n#if defined(LDC_DEBUG) && LDC_DEBUG > 0\nvoid dprint(const char *fmt, ...)\n{\n    char buf[60];\n\n    va_list args;\n    va_start(args, fmt);\n    int len = vsnprintf(buf, sizeof(buf)-1, fmt, args);\n    va_end(args);\n\n    sendf(\"debug_print m=%*s\", len, buf);\n}\n#endif\n\n//\n// Set up and start homing.  This assumes the sensor has been started;\n// it will error otherwise.\n//\nvoid\ncommand_ldc1612_ng_setup_home(uint32_t *args)\n{\n    struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng);\n    struct ldc1612_ng_homing *lh = &ld->homing;\n\n    uint32_t trsync_oid = args[1];\n    uint8_t trigger_reason = args[2];\n    uint8_t other_reason_base = args[3];\n    uint32_t trigger_freq = args[4];\n    uint32_t start_freq = args[5];\n    uint32_t start_time = args[6];\n    uint8_t mode = args[7];\n    int32_t tap_threshold = args[8];\n    uint8_t err_max = args[9];\n\n    if (trigger_freq == 0 || trsync_oid == 0) {\n        dprint(\"ZZZ resetting homing/tapping\");\n        ld->ts = NULL;\n        lh->mode = 0;\n        return;\n    }\n\n    if (ld->rest_ticks == 0) {\n        notify_trigger(ld, 0, other_reason_base);\n        dprint(\"ZZZ sensor not started!\");\n        return;\n    }\n\n    if (lh->mode > 0) {\n        notify_trigger(ld, 0, other_reason_base);\n        dprint(\"ZZZ homing already set up!\");\n        return;\n    }\n\n    // Clear the homing state before setting up\n    memset(lh, 0, sizeof(*lh));\n\n    lh->safe_start_freq = start_freq;\n    lh->safe_start_time = start_time;\n    lh->homing_trigger_freq = trigger_freq;\n\n    lh->error_threshold = err_max;\n\n    ld->ts = trsync_oid_lookup(trsync_oid);\n    ld->success_reason = trigger_reason;\n    ld->other_reason_base = other_reason_base;\n\n    lh->mode = mode;\n\n    switch (mode) {\n    case HOME_MODE_HOME:\n        dprint(\"ZZZ setup home sf=%u tf=%u\", start_freq, trigger_freq);\n        break;\n    case HOME_MODE_WMA:\n        lh->wma_tap.tap_threshold = tap_threshold >> 16;\n        lh->wma_tap.init_sample_count = FREQ_WINDOW_SIZE * 2;\n        dprint(\"ZZZ setup wma sf=%u tf=%u tap=%u\", start_freq, trigger_freq, tap_threshold);\n        break;\n    case HOME_MODE_SOS:\n        lh->sos_tap.tap_threshold = tap_threshold / 65536.0f;\n        dprint(\"ZZZ setup sos sf=%u tf=%u tap=%f\", start_freq, trigger_freq, lh->sos_tap.tap_threshold);\n        break;\n    default:\n        shutdown(\"bad homing mode\");\n    }\n}\nDECL_COMMAND(command_ldc1612_ng_setup_home,\n             \"ldc1612_ng_setup_home oid=%c\"\n             \" trsync_oid=%c trigger_reason=%c other_reason_base=%c\"\n             \" trigger_freq=%u start_freq=%u start_time=%u\"\n             \" mode=%c tap_threshold=%i err_max=%c\");\n\n//\n// Once homing has finished, call this to clear the homing state and\n// retrieve the tap end time and tap final threshold amount.\n//\nvoid\ncommand_ldc1612_ng_finish_home(uint32_t *args)\n{\n    struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng);\n    struct ldc1612_ng_homing *lh = &ld->homing;\n\n    uint32_t trigger_time = lh->trigger_time; // note: same as homing_clock in parent struct\n    uint32_t tap_start_time = lh->tap_start_time;\n    uint32_t error = lh->error;\n\n    ld->ts = NULL;\n    lh->mode = 0;\n\n    sendf(\"ldc1612_ng_finish_home_reply oid=%c trigger_clock=%u tap_start_clock=%u error=%u\"\n          , args[0], trigger_time, tap_start_time, error);\n\n    dprint(\"ZZZ finish tap_s=%u trig_t=%u\", tap_start_time, trigger_time);\n}\nDECL_COMMAND(command_ldc1612_ng_finish_home,\n             \"ldc1612_ng_finish_home oid=%c\");\n\n// Read a value from the chip if one is ready, put it in the bulk data buffer,\n// and do any processing if we're homing.\nvoid\nldc1612_ng_update(struct ldc1612_ng *ld, uint8_t oid)\n{\n    uint16_t status = read_reg_status(ld);\n    irq_disable();\n    ld->flags &= ~LDC_PENDING;\n    irq_enable();\n    if (!(status & 0x08)) // UNREADCONV1\n        return;\n\n    uint32_t time = timer_read_time();\n\n    // Read coil0 frequency\n    uint8_t *d = &ld->sb.data[ld->sb.data_count];\n    read_reg(ld, REG_DATA0_MSB, &d[0]);\n    read_reg(ld, REG_DATA0_LSB, &d[2]);\n    ld->sb.data_count += BYTES_PER_SAMPLE;\n\n    uint32_t data =   ((uint32_t)d[0] << 24)\n                    | ((uint32_t)d[1] << 16)\n                    | ((uint32_t)d[2] << 8)\n                    | ((uint32_t)d[3]);\n\n    ld->last_read_value = data;\n\n    switch (ld->homing.mode) {\n    case HOME_MODE_HOME: check_homing(ld, data, time); break;\n    case HOME_MODE_WMA: check_wma_tap(ld, data, time); break;\n    case HOME_MODE_SOS: check_sos_tap(ld, data, time); break;\n    }\n\n    // Flush local buffer if needed\n    if (ld->sb.data_count + BYTES_PER_SAMPLE > ARRAY_SIZE(ld->sb.data))\n        sensor_bulk_report(&ld->sb, oid);\n}\n\nstatic inline uint32_t\nwindowed_moving_average_u32(uint32_t* buf, uint8_t buf_size, uint8_t start_i)\n{\n    // TODO: We can avoid 64-bit integers here by just offseting\n    // the input numbers to ensure that we can always add buf_size values\n    // without overflow into an uint32_t. For frequencies, it should be safe\n    // to subtract the safe_start_freq and just deal with offsets above that,\n    // because ultimately we only care about the derivative.\n    // But this 64-bit math is here for now to keep the logic simple\n    // during development.\n    uint64_t wma_sum = 0;\n    for (uint8_t i = 0; i < buf_size; i++) {\n        uint8_t j = (start_i + i) % buf_size;\n        wma_sum += buf[j] * (i+1);\n    }\n\n    uint32_t freq_weight_sum = (buf_size * (buf_size + 1)) / 2;\n\n    return (uint32_t)(wma_sum / freq_weight_sum);\n}\n\nstatic inline int32_t\nsimple_average_i32(int32_t* buf, uint8_t buf_size)\n{\n    // This assumes that the sum can fit in an i32.\n    int32_t sum = 0;\n    for (uint8_t i = 0; i < buf_size; i++) {\n        sum += buf[i];\n    }\n\n    return sum / buf_size;\n}\n\nstatic float\nsosfilter(float value, struct sosfilter_sos* filter, float* state)\n{\n    const uint8_t num_sections = filter->num_sections;\n    const float* sos = filter->sos;\n\n    for (int k = 0; k < num_sections; k++) {\n        float w1 = state[2*k];\n        float w2 = state[2*k+1];\n        float b0 = *sos++; //sos[6*k];\n        float b1 = *sos++; //sos[6*k+1];\n        float b2 = *sos++; //sos[6*k+2];\n        sos++; // a0 unused\n        float a1 = *sos++; //sos[6*k+4];\n        float a2 = *sos++; //sos[6*k+5];\n\n        float w0 = value - a1 * w1 - a2 * w2;\n        value = b0 * w0 + b1 * w1 + b2 * w2;\n\n        state[2*k] = w0;\n        state[2*k+1] = w1;\n    }\n\n    return value;\n}\n\n// Check whether the sample has error bits set, and decide what to do\n// if it does\nbool\ncheck_error(struct ldc1612_ng* ld, uint32_t data, uint32_t time)\n{\n    struct ldc1612_ng_homing *lh = &ld->homing;\n    if (!SAMPLE_ERR(data)) {\n        lh->error_count = 0;\n        return true;\n    }\n\n    uint8_t is_tap = lh->mode > 0;\n\n    // Ignore amplitude too high errors for homing,\n    // because this is generally the probe being very\n    // far from the build plate.\n    if (!is_tap && (ld->last_status & STATUS_ERR_AHE) != 0) {\n        lh->error_count = 0;\n        return false;\n    }\n\n    lh->error_count++;\n\n    dprint(\"ZZZ err=%u t=%u s=%u cnt=%u\", data, time, ld->last_status,\n        lh->error_count);\n\n    if (lh->error_count <= lh->error_threshold)\n        return false;\n\n    lh->error = data;\n\n    // Sensor reports an issue - cancel homing\n    notify_trigger(ld, 0, ld->other_reason_base + REASON_ERROR_SENSOR);\n    return false;\n}\n\n// Check whether we've passed the safety thresholds in order for the\n// operation to proceed\nbool\ncheck_safe_start(struct ldc1612_ng* ld, uint32_t data, uint32_t time)\n{\n    struct ldc1612_ng_homing *lh = &ld->homing;\n    uint8_t is_tap = lh->mode > 0;\n\n    if (lh->safe_start_freq == 0)\n        return true;\n\n    // We need to pass through this frequency threshold to be a valid dive.\n    // We just use the simple data value here.\n    if (data < lh->safe_start_freq)\n        return false;\n\n    // And we need to do it _after_ this time, to make sure we didn't\n    // start below the threshold\n    if (lh->safe_start_time != 0 && timer_is_before(time, lh->safe_start_time)) {\n        dprint(\"ZZZ EARLY! time=%u < %u\", time, lh->safe_start_time);\n        notify_trigger(ld, 0, ld->other_reason_base + REASON_ERROR_TOO_EARLY);\n        return false;\n    }\n\n    if (is_tap && lh->homing_trigger_freq != 0) {\n        // If we're tapping, then make the homing trigger freq a second thershold.\n        // These would typically be set to something like the 3.0mm freq for the first,\n        // then the 2.0mm homing freq.\n        lh->safe_start_freq = lh->homing_trigger_freq;\n        lh->homing_trigger_freq = 0;\n        return false;\n    }\n\n    dprint(\"ZZZ safe start\");\n\n    // Ok, we've passed all the safety thresholds. Values from this point on\n    // will be considered for homing/tapping\n    lh->safe_start_freq = 0;\n\n    return true;\n}\n\n//\n// Basic homing (simple threshold)\n//\nvoid\ncheck_homing(struct ldc1612_ng* ld, uint32_t data, uint32_t time)\n{\n    struct ldc1612_ng_homing *lh = &ld->homing;\n\n    if (!check_error(ld, data, time))\n        return;\n    \n    if (!check_safe_start(ld, data, time))\n        return;\n    \n    if (data > lh->homing_trigger_freq) {\n        notify_trigger(ld, time, ld->success_reason);\n        lh->trigger_time = time;\n        dprint(\"ZZZ home t=%u f=%u\", time, data);\n    }\n}\n\n//\n// Tap detection using a windowed moving average of the frequency derivative\n//\nvoid\ncheck_wma_tap(struct ldc1612_ng* ld, uint32_t data, uint32_t time)\n{\n    struct ldc1612_ng_homing *lh = &ld->homing;\n    struct ldc1612_ng_homing_wma_tap *wma_tap = &lh->wma_tap;\n\n    if (!check_error(ld, data, time))\n        return;\n\n    if (!check_safe_start(ld, data, time))\n        return;\n    \n    //\n    // Update the sensor averages and derivatives\n    //\n    // We use a windowed moving average for the frequencies. This seems to give a\n    // better signal after staring at a jupyter notebook with plotly plots\n    // for far too long. Because the values are always increasing as we probe,\n    // WMA undershoots the true value by by a bit but it does a great job of\n    // smoothing out the noise in the sensor.\n    //\n    // Because the sensor is always going to be used at the same ranges,\n    // we could calibrate a fixed offset to apply to the frequency values (by\n    // calculating the average offset between the true centered average vs.\n    // the WMA to get a more accurate number.\n    //\n    // However, the actual frequency value itself is only used for coarse homing;\n    // and because we're not doing any temperature calibration coarse homing\n    // is never going to be super accurate anyway.\n    //\n    // Tap detection is done by looking at the derivative of this value only.\n    //\n\n    // TODO: the below can absolutely be made more efficient, but I'm\n    // keeping it simple while things are dialed in.\n\n    // Helpers to clean up the adds/mods/etc. to make the below more readable\n    #define NEXT_FREQ_I(i) (((i) + 1) % FREQ_WINDOW_SIZE)\n    #define NEXT_WMA_D_I(i) (((i) + 1) % WMA_D_WINDOW_SIZE)\n\n    wma_tap->freq_buffer[wma_tap->freq_i] = data;\n    wma_tap->freq_i = NEXT_FREQ_I(wma_tap->freq_i);\n\n    uint32_t wma = windowed_moving_average_u32(wma_tap->freq_buffer, FREQ_WINDOW_SIZE, wma_tap->freq_i);\n    int32_t wma_d = wma - wma_tap->wma;\n\n    // A simple average of wma_d to smooth it out a bit. Without this,\n    // we'll see some small spikes which will reset the accumulator;\n    // I think this is due to the drip move.\n    wma_tap->wma_d_buf[wma_tap->wma_d_i] = wma_d;\n    wma_tap->wma_d_i = NEXT_WMA_D_I(wma_tap->wma_d_i);\n\n    int32_t wma_d_avg = simple_average_i32(wma_tap->wma_d_buf, WMA_D_WINDOW_SIZE);\n    int32_t last_wma_d_avg = wma_tap->wma_d_avg;\n\n    wma_tap->wma = wma;\n    wma_tap->wma_d_avg = wma_d_avg;\n\n    if (wma_tap->init_sample_count) {\n        wma_tap->init_sample_count--;\n        return;\n    }\n\n    // The core tap threshold computation. If the derivative is\n    // increasing, keep resetting the tap start until we hit a peak.\n\n    if (wma_d_avg > last_wma_d_avg) {\n        // derivative is increasing; reset the accumulator,\n        // and reset the tap time\n        lh->tap_start_time = time;\n        wma_tap->tap_start_value = wma_d_avg;\n        return;\n    }\n\n    if (wma_tap->tap_start_value - wma_d_avg >= wma_tap->tap_threshold) {\n        // Note: we notify with the time the tap started, not the current time\n        notify_trigger(ld, lh->tap_start_time, ld->success_reason);\n        lh->trigger_time = time;\n        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);\n    }\n}\n\nvoid\ncheck_sos_tap(struct ldc1612_ng* ld, uint32_t data, uint32_t time)\n{\n    struct ldc1612_ng_homing *lh = &ld->homing;\n    struct ldc1612_ng_homing_sos_tap *sos_tap = &lh->sos_tap;\n\n    if (!check_error(ld, data, time))\n        return;\n\n    float freq = data * ld->sensor_cvt;\n\n    // We need to offset the frequencies by the first\n    // one we feed to the filter so we don't get a crazy\n    // response at the start.\n\n    // if we haven't even hit the safe_start_freq\n    if (lh->homing_trigger_freq != 0) {\n        sos_tap->frequency_offset = freq;\n        if (check_safe_start(ld, data, time))\n            shutdown(\"bug\"); // this should never return true in here\n        return;\n    }\n\n    float val = sosfilter(freq - sos_tap->frequency_offset, &ld->sos_filter, sos_tap->state);\n    //dprint(\"%f,%f\", freq, val);\n\n    // this is the second threshold; but we want to feed the filter values\n    // before this to avoid the initial impulse response\n    if (!check_safe_start(ld, data, time))\n        return;\n\n    // Note: == is explicitly excluded below. We don't want to\n    // overwrite the \"start\" time (so >= won't work), and\n    // it can't make a difference to the last diff check\n    if (val < sos_tap->last_value) {\n        float diff = sos_tap->tap_start_value - val;\n        if (diff >= sos_tap->tap_threshold) {\n            lh->trigger_time = time;\n            notify_trigger(ld, time, ld->success_reason);\n            dprint(\"ZZZ tap st=%u tt=%u l=%f (f=%f)\", lh->tap_start_time, time, sos_tap->tap_start_value - val, freq);\n            return;\n        }\n    } else if (val > sos_tap->last_value) {\n        // This keeps getting updated even on the rise, so that\n        // the values are correct for the start of the tap (i.e. the peak)\n        // once we realize the value is falling.\n        sos_tap->tap_start_value = val;\n        lh->tap_start_time = time;\n    }\n\n    sos_tap->last_value = val;\n}\n\nvoid\ncommand_ldc1612_ng_set_sos_section(uint32_t *args)\n{\n    struct ldc1612_ng *ld = oid_lookup(args[0], command_config_ldc1612_ng);\n    uint8_t section = args[1];\n    uint8_t values_len = args[2];\n    if (values_len == 0) {\n        // reset filter\n        ld->sos_filter.num_sections = 0;\n        return;\n    }\n\n    uint8_t* data = command_decode_ptr(args[3]);\n    if (values_len != 4*6) {\n        shutdown(\"ldc1612_ng: wrong sos section length\");\n    }\n\n    // these commands need to come in order of increasing section\n    ld->sos_filter.num_sections = section + 1;\n    memcpy(&ld->sos_filter.sos[section*6], data, values_len);\n}\nDECL_COMMAND(command_ldc1612_ng_set_sos_section,\n             \"ldc1612_ng_set_sos_section oid=%c section=%c values=%*s\");\n"
  },
  {
    "path": "install.py",
    "content": "#!/usr/bin/env python3\n\nimport os\nimport sys\nimport argparse\nimport shutil\nfrom pathlib import Path\n\nIS_MAC = os.path.isdir(\"/System/Library\")\n\nSED_IN_PLACE_ARG = \"-i ''\" if IS_MAC else \"-i\"\nFILES_TO_COPY = {\n    \"eddy-ng/sensor_ldc1612_ng.c\": \"src\",\n    \"probe_eddy_ng.py\": \"klippy/extras\",\n    \"ldc1612_ng.py\": \"klippy/extras\"\n}\n\n\ndef get_script_dir():\n    return os.path.dirname(os.path.realpath(__file__))\n\n\ndef uninstall_klipper(target_dir: str):\n    for src_file, dest_dir in FILES_TO_COPY.items():\n        dest_path = os.path.join(target_dir, dest_dir)\n        dest_file = os.path.join(dest_path, os.path.basename(src_file))\n        if os.path.islink(dest_file) or os.path.isfile(dest_file):\n            print(f\"Removing {dest_file}\")\n            os.remove(dest_file)\n        else:\n            print(f\"File {dest_file} does not exist. Skipping.\")\n\n    print(\"Unpatching src/Makefile...\")\n    makefile_path = os.path.join(target_dir, \"src/Makefile\")\n    os.system(f\"sed {SED_IN_PLACE_ARG} 's, sensor_ldc1612_ng.c,,' '{makefile_path}'\")\n\n    print(\"Unpatching klippy/extras/bed-mesh.py...\")\n    bed_mesh_path = os.path.join(target_dir, \"klippy/extras/bed_mesh.py\")\n    os.system(\n        f\"sed {SED_IN_PLACE_ARG} 's,\\\"eddy\\\" in probe_name #eddy-ng,probe_name.startswith(\\\"probe_eddy_current\\\"),' '{bed_mesh_path}'\"\n    )\n    return\n\n\ndef install_kalico(target_dir: str, uninstall: bool, copy: bool):\n    if not uninstall:\n        print(\"Congrats, you're running Kalico!\")\n        print(\"================================\")\n\n    python_module_path = os.path.join(target_dir, \"klippy/plugins/probe_eddy_ng\")\n    firmware_module_path = os.path.join(target_dir, \"src/extras/eddy-ng\")\n\n    old_module_path = os.path.join(target_dir, \"klippy/extras/probe_eddy_ng.py\")\n    if os.path.islink(old_module_path) or os.path.isfile(old_module_path):\n        print(\"Uninstalling old installation...\")\n        uninstall_klipper(target_dir)\n\n    if os.path.exists(python_module_path) or os.path.islink(python_module_path):\n        if not os.path.islink(python_module_path):\n            print(f\"{python_module_path} exists, but is not a symlink. Please remove it and try again.\")\n            sys.exit(1)\n        os.unlink(python_module_path)\n\n    if os.path.exists(firmware_module_path) or os.path.islink(firmware_module_path):\n        if not os.path.islink(firmware_module_path):\n            print(f\"{firmware_module_path} exists, but is not a symlink. Please remove it and try again.\")\n            sys.exit(1)\n        os.unlink(firmware_module_path)\n\n    if uninstall:\n        print(\"Removed firmware and plugin module links.\")\n        sys.exit(0)\n\n    if copy:\n        shutil.copytree(get_script_dir(), python_module_path)\n        shutil.copytree(os.path.join(get_script_dir(), \"eddy-ng\"), firmware_module_path)\n    else:\n        os.symlink(get_script_dir(), python_module_path)\n        os.symlink(os.path.join(get_script_dir(), \"eddy-ng\"), firmware_module_path)\n\n    print(\"Installed links to firmware and plugin modules.\")\n    print(\"When rebuilding firmware, make sure to select eddy-ng\")\n    print(\"from the firmware extras in menuconfig.\")\n    print(\"(There's no need to run install again after eddy-ng updates.)\")\n\ndef install_klipper(target_dir: str, uninstall: bool, copy: bool):\n    if uninstall:\n        print(\"Uninstalling files...\")\n        uninstall_klipper(target_dir)\n        return\n\n    print(\"Installing files...\")\n    for src_file, dest_dir in FILES_TO_COPY.items():\n        src_path = os.path.join(get_script_dir(), src_file)\n        dest_path = os.path.join(target_dir, dest_dir)\n        dest_file = os.path.join(dest_path, os.path.basename(src_file))\n\n        if copy:\n            print(f\"Copying {src_file} to {dest_dir}/\")\n            shutil.copyfile(src_file, dest_file)\n        else:\n            link_path = os.path.relpath(os.path.realpath(src_path), dest_path)\n            print(f\"Linking {link_path} to {dest_dir}/\")\n            if os.path.islink(dest_file) or os.path.exists(dest_file):\n                os.remove(dest_file)\n            os.symlink(link_path, dest_file)\n\n    print(\"Patching src/Makefile...\")\n    makefile_path = os.path.join(target_dir, \"src/Makefile\")\n    os.system(f\"sed {SED_IN_PLACE_ARG} 's,sensor_ldc1612.c$,sensor_ldc1612.c sensor_ldc1612_ng.c,' '{makefile_path}'\")\n\n    print(\"Patching klippy/extras/bed-mesh.py...\")\n    bed_mesh_path = os.path.join(target_dir, \"klippy/extras/bed_mesh.py\")\n    os.system(\n        f\"sed {SED_IN_PLACE_ARG} 's,probe_name.startswith(\\\"probe_eddy_current\\\"),\\\"eddy\\\" in probe_name #eddy-ng,' '{bed_mesh_path}'\"\n    )\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Install or uninstall components.\")\n    parser.add_argument(\"-u\", \"--uninstall\", action=\"store_true\", help=\"Uninstall files\")\n    parser.add_argument(\"--copy\", action=\"store_true\", help=\"Copy files instead of linking\")\n    parser.add_argument(\"target_dir\", nargs=\"?\", help=\"Target directory\")\n\n    args = parser.parse_args()\n\n    uninstall = args.uninstall\n    copy = args.copy\n    target_dir = args.target_dir\n\n    # If no target directory provided, try defaults\n    if not target_dir:\n        home_dir = str(Path.home())\n        if os.path.isdir(os.path.join(home_dir, \"klipper\")):\n            target_dir = os.path.join(home_dir, \"klipper\")\n        elif os.path.isdir(os.path.join(home_dir, \"kalico\")):\n            target_dir = os.path.join(home_dir, \"kalico\")\n        else:\n            print(\"Error: No target directory provided and no default directories found.\")\n            parser.print_help()\n            sys.exit(1)\n\n    if not os.path.isdir(target_dir):\n        print(f\"Error: Target directory '{target_dir}' does not exist.\")\n        sys.exit(1)\n\n    if os.path.exists(os.path.join(target_dir, \"klippy/extras/danger_options.py\")):\n        install_kalico(target_dir, uninstall, copy)\n    else:\n        install_klipper(target_dir, uninstall, copy)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "install.sh",
    "content": "#!/bin/bash\nexec python3 install.py $*\n\n"
  },
  {
    "path": "klipper.patch",
    "content": "diff --git src/Makefile src/Makefile\nindex cfedc56f7..422e0179e 100644\n--- a/src/Makefile\n+++ b/src/Makefile\n@@ -20,6 +20,6 @@ src-$(CONFIG_WANT_LIS2DW) += sensor_lis2dw.c\n src-$(CONFIG_WANT_MPU9250) += sensor_mpu9250.c\n src-$(CONFIG_WANT_HX71X) += sensor_hx71x.c\n src-$(CONFIG_WANT_ADS1220) += sensor_ads1220.c\n-src-$(CONFIG_WANT_LDC1612) += sensor_ldc1612.c\n+src-$(CONFIG_WANT_LDC1612) += sensor_ldc1612.c sensor_ldc1612_ng.c\n src-$(CONFIG_WANT_SENSOR_ANGLE) += sensor_angle.c\n src-$(CONFIG_NEED_SENSOR_BULK) += sensor_bulk.c\n"
  },
  {
    "path": "ldc1612_ng.py",
    "content": "# Support for reading frequency samples from ldc1612 (v2)\n#\n# Copyright (C) 2020-2024  Kevin O'Connor <kevin@koconnor.net>\n# Copyright (C) 2025  Vladimir Vukicevic <vladimir@pobox.com>\n#\n# This file may be distributed under the terms of the GNU GPLv3 license.\nimport math\nimport logging\nimport struct\nfrom dataclasses import dataclass\nfrom typing import List, Optional\n\ntry:\n    from klippy.extras import bus, bulk_sensor\n    from klippy.printer import Printer\n\n    IS_KALICO = True\nexcept ImportError:\n    from . import bus, bulk_sensor\n    from klippy import Printer\n\n    IS_KALICO = False\n\nMIN_MSG_TIME = 0.100\n\nBATCH_UPDATES = 0.100\n\nLDC1612_ADDR = 0x2A\n\n# TODO: configure these as part of calibration\nDEGLITCH_1_0MHZ = 0x01\nDEGLITCH_3_3MHZ = 0x04\nDEGLITCH_10MHZ = 0x05\nDEGLITCH_33MHZ = 0x07\n\nLDC1612_MANUF_ID = 0x5449\nLDC1612_DEV_ID = 0x3055\n\nREG_RCOUNT0 = 0x08\nREG_OFFSET0 = 0x0C\nREG_SETTLECOUNT0 = 0x10\nREG_CLOCK_DIVIDERS0 = 0x14\nREG_ERROR_CONFIG = 0x19\nREG_CONFIG = 0x1A\nREG_MUX_CONFIG = 0x1B\nREG_DRIVE_CURRENT0 = 0x1E\nREG_MANUFACTURER_ID = 0x7E\nREG_DEVICE_ID = 0x7F\n\n# Device product (match sensor_ldc1612_ng.c)\nPRODUCT_UNKNOWN = 0\nPRODUCT_BTT_EDDY = 1\nPRODUCT_CARTOGRAPHER = 2\nPRODUCT_MELLOW_FLY = 3\nPRODUCT_LDC1612_INTERNAL_CLK = 4\n\nHOME_MODE_NONE = 0\nHOME_MODE_HOME = 1\nHOME_MODE_WMA = 2\nHOME_MODE_SOS = 3\n\n\n@dataclass\nclass LDC1612_ng_value:\n    status: int\n    freqval: int\n    freq: float\n\n\n@dataclass\nclass LDC1612_ng_homing_result:\n    trigger_time: float\n    tap_start_time: float\n    error: int\n\n\n# Interface class to LDC1612 mcu support\nclass LDC1612_ng:\n    def __init__(self, config):\n        self.printer: Printer = config.get_printer()\n\n        self._name = config.get_name().split()[-1]\n        self._verbose = config.getboolean(\"debug\", False)\n\n        device_choices = {\n            \"ldc1612\": PRODUCT_UNKNOWN,\n            \"btt_eddy\": PRODUCT_BTT_EDDY,\n            \"cartographer\": PRODUCT_CARTOGRAPHER,\n            \"mellow_fly\": PRODUCT_MELLOW_FLY,\n            \"ldc1612_internal_clk\": PRODUCT_LDC1612_INTERNAL_CLK,\n        }\n        self._device_product = config.getchoice(\"sensor_type\", device_choices, PRODUCT_UNKNOWN)\n\n        # Fin0 = Fsensor0 / FIN_DIVIDER0\n        # Fref0 = Fclk / FREF_DIVIDER0\n        if self._device_product == PRODUCT_CARTOGRAPHER:\n            self._ldc_freq_clk = 24_000_000\n            self._ldc_fin_divider = 1\n            self._ldc_fref_divider = 1\n            self._ldc_settle_time = 0.0001706\n            self._default_drive_current = 26\n        elif self._device_product == PRODUCT_MELLOW_FLY:\n            self._ldc_freq_clk = 40_000_000\n            self._ldc_fin_divider = 1\n            self._ldc_fref_divider = 2\n            self._ldc_settle_time = 0.00125\n            self._default_drive_current = 15\n        elif self._device_product == PRODUCT_LDC1612_INTERNAL_CLK:\n            # A generic setup that usees internal LDC1612 clock\n            # using LDC1612 internal typical clock frequency 43.4MHz\n            self._ldc_freq_clk = 43_400_000\n            self._ldc_fin_divider = 1\n            self._ldc_fref_divider = 1\n            self._ldc_settle_time = 0.00125\n            self._default_drive_current = 15\n        else:  # Generic/BTT Eddy using external 12MHz clock source\n            self._ldc_freq_clk = 12_000_000\n            self._ldc_settle_time = 0.005\n            self._ldc_fin_divider = 1\n            self._ldc_fref_divider = 1\n            self._default_drive_current = 15\n\n        self._ldc_freq_ref = round(self._ldc_freq_clk / self._ldc_fref_divider)\n\n        drive_current: int = config.getint(\"reg_drive_current\", 0, minval=0, maxval=31)\n        saved_drive_current: int = config.getint(\"saved_reg_drive_current\", 0, minval=0, maxval=31)\n        if drive_current == 0:\n            drive_current = saved_drive_current\n        if drive_current == 0:\n            drive_current = self._default_drive_current\n        self._drive_current = drive_current\n\n        self._deglitch: str = config.get(\"ldc_deglitch\", \"default\").lower()\n        self._data_rate: int = config.getint(\"samples_per_second\", 250, minval=50)\n        self._ldc_settle_time = min(self._ldc_settle_time, 1.0 / self._data_rate)\n\n        # Setup mcu sensor_ldc1612 bulk query code\n        self._i2c = bus.MCU_I2C_from_config(config, default_addr=LDC1612_ADDR, default_speed=400000)\n        self._mcu = mcu = self._i2c.get_mcu()\n        self._oid = oid = mcu.create_oid()\n\n        logging.info(f\"LDC1612ng {self._name} oid: {oid} i2c_oid {self._i2c.get_oid()}\")\n\n        # params ending in \"_pin\" are magic and are a %s on this side, but %c on\n        # the native side. There doesn't seem to be a way to pass \"no pin\". So we\n        # need two separate config commands.\n        if config.get(\"intb_pin\", None) is not None:\n            ppins = config.get_printer().lookup_object(\"pins\")\n            pin_params = ppins.lookup_pin(config.get(\"intb_pin\"))\n            if pin_params[\"chip\"] != mcu:\n                raise config.error(\"ldc1612 intb_pin must be on same mcu\")\n            mcu.add_config_cmd(\n                \"config_ldc1612_ng_with_intb oid=%d i2c_oid=%d product=%i intb_pin=%s\"\n                % (\n                    oid,\n                    self._i2c.get_oid(),\n                    self._device_product,\n                    pin_params[\"pin\"],\n                )\n            )\n        else:\n            mcu.add_config_cmd(\"config_ldc1612_ng oid=%d i2c_oid=%d product=%i\" % (oid, self._i2c.get_oid(), self._device_product))\n\n        # Make sure the sensor is stopped on restart\n        mcu.add_config_cmd(\n            \"ldc1612_ng_start_stop oid=%d rest_ticks=0\" % (oid,),\n            on_restart=True,\n        )\n        mcu.register_config_callback(self._build_config)\n\n        self._start_count = 0\n        self._chip_initialized = False\n\n        # Bulk sample message reading\n        chip_smooth = self._data_rate * BATCH_UPDATES * 2\n        self._ffreader = bulk_sensor.FixedFreqReader(mcu, chip_smooth, \">I\")\n        # Process messages in batches\n        self._batch_bulk = bulk_sensor.BatchBulkHelper(\n            self.printer,\n            self._process_batch,\n            self._start_measurements,\n            self._finish_measurements,\n            BATCH_UPDATES,\n        )\n        hdr = (\"time\", \"frequency\", \"z\")\n        self._batch_bulk.add_mux_endpoint(\"ldc1612_ng/dump_ldc1612\", \"sensor\", self._name, {\"header\": hdr})\n\n        gcode = self.printer.lookup_object(\"gcode\")\n        gcode.register_mux_command(\n            \"LDC_NG_CALIBRATE_DRIVE_CURRENT\",\n            \"CHIP\",\n            self._name,\n            self.cmd_LDC_CALIBRATE,\n            desc=self.cmd_LDC_CALIBRATE_help,\n        )\n        gcode.register_mux_command(\n            \"LDC_NG_SET_DRIVE_CURRENT\",\n            \"CHIP\",\n            self._name,\n            self.cmd_LDC_SET_DC,\n            desc=self.cmd_LDC_SET_DC_help,\n        )\n\n    cmd_LDC_SET_DC_help = \"Set LDC1612 DRIVE_CURRENT register (idrive value only)\"\n\n    def cmd_LDC_SET_DC(self, gcmd):\n        drive_cur = gcmd.get_int(\"VAL\", minval=0, maxval=31)\n        self.set_drive_current(drive_cur)\n\n    cmd_LDC_CALIBRATE_help = \"Calibrate LDC1612 DRIVE_CURRENT register\"\n\n    def cmd_LDC_CALIBRATE(self, gcmd):\n        is_in_progress = True\n\n        def handle_batch(msg):\n            return is_in_progress\n\n        self.add_bulk_sensor_data_client(handle_batch)\n        toolhead = self.printer.lookup_object(\"toolhead\")\n        toolhead.dwell(0.100)\n        toolhead.wait_moves()\n        old_config = self.read_reg(REG_CONFIG)\n        if (self._device_product == PRODUCT_LDC1612_INTERNAL_CLK):\n            self.set_reg(REG_CONFIG, 0x001)\n        else:\n            self.set_reg(REG_CONFIG, 0x001 | (1 << 9))\n        toolhead.wait_moves()\n        toolhead.dwell(0.100)\n        toolhead.wait_moves()\n        reg_drive_current0 = self.read_reg(REG_DRIVE_CURRENT0)\n        self.set_reg(REG_CONFIG, old_config)\n        is_in_progress = False\n        # Report found value to user\n        drive_cur = (reg_drive_current0 >> 6) & 0x1F\n        gcmd.respond_info(\n            f\"{self._name}: Estimated reg_drive_current: {drive_cur}\\n\"\n            \"Add this to your config as either reg_drive_current or tap_drive_current\\n\"\n            \"then restart.\"\n        )\n\n    def _build_config(self):\n        cmdqueue = self._i2c.get_command_queue()\n\n        self._ldc1612_ng_start_stop_cmd = self._mcu.lookup_command(\"ldc1612_ng_start_stop oid=%c rest_ticks=%u\", cq=cmdqueue)\n\n        self._ffreader.setup_query_command(\"ldc1612_ng_query_bulk_status oid=%c\", oid=self._oid, cq=cmdqueue)\n\n        self._ldc1612_ng_latched_status_cmd = self._mcu.lookup_query_command(\n            \"query_ldc1612_ng_latched_status_v2 oid=%c\",\n            \"ldc1612_ng_latched_status oid=%c status=%u lastval=%u\",\n            oid=self._oid,\n            cq=cmdqueue,\n        )\n\n        self._ldc1612_ng_setup_home_cmd = self._mcu.lookup_command(\n            \"ldc1612_ng_setup_home oid=%c\"\n            \" trsync_oid=%c trigger_reason=%c other_reason_base=%c\"\n            \" trigger_freq=%u start_freq=%u start_time=%u mode=%c tap_threshold=%i\"\n            \" err_max=%c\",\n            cq=cmdqueue,\n        )\n\n        self._ldc1612_ng_finish_home_cmd = self._mcu.lookup_query_command(\n            \"ldc1612_ng_finish_home oid=%c\",\n            \"ldc1612_ng_finish_home_reply oid=%c trigger_clock=%u tap_start_clock=%u error=%u\",\n            oid=self._oid,\n            cq=cmdqueue,\n        )\n\n        self._ldc1612_ng_set_sos_section = self._mcu.lookup_command(\n            \"ldc1612_ng_set_sos_section oid=%c section=%c values=%*s\",\n            cq=cmdqueue,\n        )\n\n        if hasattr(self._mcu, \"register_serial_response\"):\n            # infuriating: these used to be able to be registered for optional\n            # things (that the firmware never sends)\n            #self._mcu.register_serial_response(self._handle_debug_print, \"debug_print m=%*s\")\n            pass\n        else:\n            self._mcu.register_response(self._handle_debug_print, \"debug_print\")\n\n    def _handle_debug_print(self, params):\n        logging.info(params[\"m\"])\n\n    def _clock32_to_print_time(self, clock) -> float:\n        return self._mcu.clock_to_print_time(self._mcu.clock32_to_clock64(clock))\n\n    def get_mcu(self):\n        return self._i2c.get_mcu()\n\n    def read_reg(self, reg):\n        params = self._i2c.i2c_read([reg], 2)\n        response = bytearray(params[\"response\"])\n        return (response[0] << 8) | response[1]\n\n    def set_reg(self, reg, val, minclock=0):\n        self._i2c.i2c_write([reg, (val >> 8) & 0xFF, val & 0xFF], minclock=minclock)\n\n    def add_bulk_sensor_data_client(self, cb):\n        self._batch_bulk.add_client(cb)\n\n    def latched_status(self):\n        response = self._ldc1612_ng_latched_status_cmd.send([self._oid])\n        return response[\"status\"]\n\n    def latched_status_str(self):\n        s = self.latched_status()\n        return self.status_to_str(s)\n\n    def status_to_str(self, s: int):\n        status_bits = [\n            \"0\",\n            \"1\",\n            \"2\",\n            \"UNREADCONV1\",\n            \"4\",\n            \"5\",\n            \"DRDY\",\n            \"7\",\n            \"ERR_ZC\",\n            \"ERR_ALE\",\n            \"ERR_AHE\",\n            \"ERR_WD\",\n            \"ERR_OR\",\n            \"ERR_UR\",\n            \"14\",\n            \"ERR_CH1\",\n        ]\n        flags = []\n        for bit, flag in enumerate(status_bits):\n            if s & (1 << bit):\n                flags.append(flag)\n        return \" \".join(flags)\n\n    def data_error_to_str(self, d: int):\n        err_bits = [\n            \"Under-range Error\",\n            \"Over-range Error\",\n            \"Watchdog Error\",\n            \"Amplitude Error\",\n        ]\n        d = d >> 12  # shift out the data bits\n        errors = []\n        for bit, err in enumerate(err_bits):\n            if d & (1 << bit):\n                errors.append(err)\n        return \" \".join(errors)\n\n    def read_one_value(self):\n        self._init_chip()\n        # the status command also returns the last value\n        res = self._ldc1612_ng_latched_status_cmd.send([self._oid])\n        status = res[\"status\"]\n        lastval = res[\"lastval\"]\n        freq = self.from_ldc_freqval(lastval) if lastval <= 0x0FFFFFFF else 0.0\n\n        return LDC1612_ng_value(\n            status=status,\n            freqval=lastval,\n            freq=freq,\n        )\n\n    def to_ldc_freqval(self, freq):\n        return int(freq * (1 << 28) / float(self._ldc_freq_ref) + 0.5)\n\n    def from_ldc_freqval(self, val, ignore_err=False):\n        if val > 0x0FFFFFFF and not ignore_err:\n            raise self.printer.command_error(f\"LDC1612 frequency value has error bits: {hex(val)}\")\n        return round(val * (float(self._ldc_freq_ref) / (1 << 28)), 3)\n\n    #\n    # Homing\n    #\n    def setup_home(\n        self,\n        trsync_oid: int,\n        hit_reason: int,\n        other_reason_base: int,\n        trigger_freq: float,\n        start_freq: float,\n        start_time: float,\n        mode: str = \"home\",\n        tap_threshold: Optional[float] = None,\n        max_errors: int = 0,\n    ):\n        MODES = {\n            \"home\": HOME_MODE_HOME,\n            \"wma\": HOME_MODE_WMA,\n            \"sos\": HOME_MODE_SOS,\n        }\n        mode_val = MODES.get(mode.lower(), None)\n        if mode_val is None:\n            raise self.printer.command_error(f\"Invalid mode: {mode}\")\n\n        t_freqvl = self.to_ldc_freqval(trigger_freq)\n        s_freqval = self.to_ldc_freqval(start_freq)\n        start_time_mcu = self._mcu.print_time_to_clock(start_time) if start_time > 0 else 0\n        tap_threshold_val = int(tap_threshold * 65536.0) if tap_threshold is not None else 0\n\n        if self._verbose:\n            logging.info(\n                f\"LDC1612_ng setup_home: {mode} trigger: {trigger_freq:.2f} ({t_freqvl}) \"\n                f\"safe: {start_freq:.2f} ({s_freqval}) @ {start_time:.2f} ({start_time_mcu}) \"\n                f\"trsync: {trsync_oid} {hit_reason} {other_reason_base} TAP: {tap_threshold} ({tap_threshold_val:x})\"\n            )\n\n        self._ldc1612_ng_setup_home_cmd.send(\n            [\n                self._oid,\n                trsync_oid,\n                hit_reason,\n                other_reason_base,\n                t_freqvl,\n                s_freqval,\n                start_time_mcu,\n                mode_val,\n                tap_threshold_val,\n                max_errors,\n            ]\n        )\n\n    def _convert_clock(self, c):\n        if c == 0:\n            return 0\n        return self._clock32_to_print_time(c)\n\n    def finish_home(self):\n        # \"ldc1612_finish_home2_reply oid=%c homing=%c trigger_clock=%u tap_start_clock=%u\",\n        reply = self._ldc1612_ng_finish_home_cmd.send([self._oid])\n        trigger_clock = reply[\"trigger_clock\"]\n        tap_start_clock = reply[\"tap_start_clock\"]\n        error = reply[\"error\"]\n        trigger_time = self._convert_clock(trigger_clock)\n        tap_start_time = self._convert_clock(tap_start_clock)\n\n        return LDC1612_ng_homing_result(trigger_time, tap_start_time, error)\n\n    def set_sos_section(self, sect_num: int, sect_vals: List[float]):\n        # pack sect_vals into a byte array using struct.pack\n        sect_bytes = [b for b in struct.pack(\"<6f\", *sect_vals)]\n        self._ldc1612_ng_set_sos_section.send([self._oid, sect_num, sect_bytes])\n\n    # The value that freqvals are multiplied by to get a float frequency\n    def freqval_conversion_value(self):\n        return float(self._ldc_freq_ref) / (1 << 28)\n\n    def _verify_chip(self):\n        # In case of miswiring, testing LDC1612 device ID prevents treating\n        # noise or wrong signal as a correctly initialized device\n        manuf_id = self.read_reg(REG_MANUFACTURER_ID)\n        dev_id = self.read_reg(REG_DEVICE_ID)\n        if manuf_id != LDC1612_MANUF_ID or dev_id != LDC1612_DEV_ID:\n            raise self.printer.command_error(\n                \"Invalid ldc1612 id (got %x,%x vs %x,%x).\\n\"\n                \"This is generally indicative of connection problems\\n\"\n                \"(e.g. faulty wiring) or a faulty ldc1612 chip.\" % (manuf_id, dev_id, LDC1612_MANUF_ID, LDC1612_DEV_ID)\n            )\n\n    def _init_chip(self):\n        if self._chip_initialized:\n            return\n\n        self._verify_chip()\n\n        # TODO: have a max_frequency and pick the best deglitch for it\n        if self._deglitch == \"1mhz\":\n            deglitch = DEGLITCH_1_0MHZ\n        elif self._deglitch == \"3.3mhz\":\n            deglitch = DEGLITCH_3_3MHZ\n        elif self._deglitch == \"10mhz\" or self._deglitch == \"default\":\n            deglitch = DEGLITCH_10MHZ\n        elif self._deglitch == \"33mhz\":\n            deglitch = DEGLITCH_33MHZ\n        else:\n            raise self.printer.error(f\"Invalid {self._name} deglitch value: {self._deglitch}\")\n\n        # This is the TI-recommended register configuration order\n        # Setup chip in requested query rate\n        rcount0 = self._ldc_freq_ref / (16.0 * (self._data_rate - 4))\n        self.set_reg(REG_RCOUNT0, int(rcount0 + 0.5))\n        self.set_reg(REG_OFFSET0, 0)\n        self.set_reg(\n            REG_SETTLECOUNT0,\n            int(self._ldc_settle_time * self._ldc_freq_ref / 16.0 + 0.5),\n        )\n        self.set_reg(\n            REG_CLOCK_DIVIDERS0,\n            (self._ldc_fin_divider << 12) | (self._ldc_fref_divider),\n        )\n        self.set_reg(REG_ERROR_CONFIG, 0b1111_1100_1111_1001)  # report everything to STATUS and INTB except ZC\n        self.set_reg(REG_MUX_CONFIG, 0x0208 | deglitch)\n        if (self._device_product == PRODUCT_LDC1612_INTERNAL_CLK):\n            # use internal oscillator\n            # RP_OVERRIDE_EN | AUTO_AMP_DIS | reserved\n            self.set_reg(REG_CONFIG, (1 << 12) | (1 << 10) | 0x001)\n        else:\n            # RP_OVERRIDE_EN | AUTO_AMP_DIS | REF_CLK_SRC=clkin | reserved\n            self.set_reg(REG_CONFIG, (1 << 12) | (1 << 10) | (1 << 9) | 0x001)\n        self.set_reg(REG_DRIVE_CURRENT0, self._drive_current << 11)\n\n        self._chip_initialized = True\n\n    def get_deglitch(self):\n        return self.read_reg(REG_MUX_CONFIG) & ~0x0208\n\n    def set_deglitch(self, val: int):\n        logging.info(f\"LDC1612ng {self._name} deglitch set {val}\")\n        self.set_reg(REG_MUX_CONFIG, val | 0x0208)\n\n    def get_drive_current(self) -> int:\n        return self._drive_current\n\n    def set_drive_current(self, cval: int, maxfreq: float = None):\n        if cval < 0 or cval > 31:\n            raise self.printer.command_error(\"Drive current must be between 0 and 31\")\n        if self._drive_current == cval:\n            return\n\n        if maxfreq is not None:\n            if maxfreq < 1_000_000.0:\n                self.set_deglitch(DEGLITCH_1_0MHZ)\n            elif maxfreq < 3_300_000.0:\n                self.set_deglitch(DEGLITCH_3_3MHZ)\n            elif maxfreq < 10_000_000.0:\n                self.set_deglitch(DEGLITCH_10MHZ)\n            else:\n                self.set_deglitch(DEGLITCH_33MHZ)\n\n        logging.info(f\"LDC1612ng {self._name} set drive current {cval}\")\n        self._drive_current = cval\n        self.set_reg(REG_DRIVE_CURRENT0, cval << 11)\n\n    # Start, stop, and process message batches\n    def _start_measurements(self):\n        self._init_chip()\n        self._start_count += 1\n\n        if self._start_count > 1:\n            logging.info(\"LDC1612 start count: %d\", self._start_count)\n            return\n\n        # Start bulk reading\n        rest_ticks = self._mcu.seconds_to_clock(0.5 / self._data_rate)\n        self._ldc1612_ng_start_stop_cmd.send([self._oid, rest_ticks])\n        # logging.info(\"LDC1612 starting '%s' measurements\", self._name)\n        # Initialize clock tracking\n        self._ffreader.note_start()\n\n    def _finish_measurements(self):\n        self._start_count -= 1\n\n        if self._start_count > 0:\n            logging.info(\"LDC1612 stop, start count now: %d\", self._start_count)\n            return\n\n        # Halt bulk reading\n        self._ldc1612_ng_start_stop_cmd.send_wait_ack([self._oid, 0])\n        self._ffreader.note_end()\n        # logging.info(\"LDC1612 finished '%s' measurements\", self._name)\n\n    def _process_batch(self, eventtime):\n        samples = self._ffreader.pull_samples()\n        count = 0\n        err_count = 0\n        last_err_kind = 0\n        for ptime, val in samples:\n            if val > 0x0FFFFFFF:  # high nibble indicates an error\n                err_kind = (val >> 28)\n                err_count += 1\n                if last_err_kind != err_kind:\n                    if self._verbose:\n                        logging.info(f\"LDC1612 error: {hex(val)}\")\n                    last_err_kind = err_kind\n            else:\n                # val is a raw value\n                samples[count] = (ptime, val)\n                count += 1\n        # remove the samples we didn't fill in because of errors\n        del samples[count:]\n        return {\n            \"data\": samples,\n            \"errors\": err_count,\n            \"overflows\": self._ffreader.get_last_overflows(),\n        }\n\n"
  },
  {
    "path": "probe_eddy_ng.py",
    "content": "# EDDY-ng\n#\n# Copyright (C) 2025  Vladimir Vukicevic <vladimir@pobox.com>\n#\n# Based on original probe_eddy_current code by:\n# Copyright (C) 2020-2024  Kevin O'Connor <kevin@koconnor.net>\n#\n# This file may be distributed under the terms of the GNU GPLv3 license.\nfrom __future__ import annotations\n\nimport os\nimport logging\nimport math\nimport bisect\nimport re\nimport traceback\nimport pickle\nimport base64\nimport time\nimport numpy as np\nimport numpy.polynomial as npp\nfrom itertools import combinations\nfrom functools import cmp_to_key\n\nfrom dataclasses import dataclass, field\nfrom typing import (\n    Any,\n    Dict,\n    List,\n    Optional,\n    Tuple,\n    ClassVar,\n    final,\n)\n\ntry:\n    from klippy import mcu, pins, chelper\n    from klippy.printer import Printer\n    from klippy.configfile import ConfigWrapper\n    from klippy.configfile import error as configerror\n    from klippy.gcode import GCodeCommand\n    from klippy.toolhead import ToolHead\n    from klippy.extras import probe, manual_probe, bed_mesh\n    from klippy.extras.homing import HomingMove\n\n    IS_KALICO = True\n    HAS_PROBE_RESULT_TYPE = False\nexcept ImportError:\n    import mcu\n    import pins\n    import chelper\n    from klippy import Printer\n    from configfile import ConfigWrapper\n    from configfile import error as configerror\n    from gcode import GCodeCommand\n    from toolhead import ToolHead\n    from . import probe, manual_probe, bed_mesh\n    from .homing import HomingMove\n\n    IS_KALICO = False\n    HAS_PROBE_RESULT_TYPE = hasattr(manual_probe, \"ProbeResult\")\n\nfrom . import ldc1612_ng\n\ntry:\n    import plotly  # noqa\nexcept ImportError:\n    plotly = None\n\ntry:\n    import scipy  # noqa\nexcept ImportError:\n    scipy = None\n\n# In this file, a couple of conventions are used (for sanity).\n# Variables are named according to:\n# - \"height\" is always a physical height as detected by the probe in mm\n# - \"z\" is always a z axis position (which may or may not match height)\n# - \"freq\" is always a frequency value (float)\n# - \"freqval\" is always an encoded frequency value, as communicated to/from the sensor (int)\n\n# There are three distinct operations/phases. Homing Z via the virtual\n# endstop is the only operation that can happen while Z is not homed:\n#\n# 1. Homing Z using a virtual probe endstop. This is largely handled by\n#    ProbeEddyEndstopWrapper. It sets up the sensor to trigger when a certain\n#    frequency is crossed, and then lets a HomingMove continue that moves the\n#    toolhead down. When that frequency is hit, it triggers, and Klipper stops\n#    the toolhead from moving down. The time point when it triggers is set as\n#    the z=trigger_height (which is home_trigger_height in the configurable\n#    params). Z should be accurate enough at this point. This operation can be run\n#    when the bed/toolhead are cold or hot.\n#\n# Once Z is homed, two additional operations become available:\n#\n# 2. Probing at either a single point or multiple points. This is used for\n#    Quad Gantry Leveling, Bed Mesh, and other similar operations. This is\n#    largely handled by the ProbeEddyScannigProbe class -- one is returned\n#    from the ProbeEddy `probe` object when `start_probe_session` is called.\n#    For Eddy probes, there is no reason to move the toolhead up and down at\n#    each probe point: the measured distance between the sensor and the build\n#    plate can be read directly. This class starts gathering sample data when\n#    the session starts and records the times when there's a sample that we\n#    care about, along with the toolhead position, whenever a caller calls\n#    `run_probe`. If this is a `rapid_scan` scan, then a callback is attached\n#    to the current motion so that we can save the movement's time and position\n#    without actually waiting for it. If it's in normal mode, then the toolhead\n#    will pause at each position. In both cases, the results are obtained by\n#    calling `pull_probed_results`, which returns an array of results at each\n#    point that `run_probe` was called for, in order.\n#\n#    PROBE_STATIC HOME_Z=1 can be used to set the toolhead's Z position\n#    based on the current height reading from the probe while the toolhead is\n#    static, leading to a more accurate result than a regular homing operation\n#    (which involves movement).\n#\n# 3. A \"tap\" to fine-tune the Z offset. This should be run with the bed at print\n#    temperature and soaked for a bit. The nozzle should also be warm but not so\n#    hot that filament risks oozing out. The nozzle also must be clean. 150C\n#    is a good temperature to both clean and tap at.\n#\n#    This operation will identify the exact position of the Z axis\n#    when the nozzle touches the bed, which means that a precise Z offset\n#    can be set.\n#\n# The eddy current response and readings depend on temperature of both the target\n# (bed) and the sensor (coil). EddyNG does not do any temperature compensation. Instead\n# it relies on the \"tap\" operation to get an accurate reference point for z=0 regardless\n# of temperatures. Empirically, small offsets from a reference point can still be read\n# accurately from the sensor, even if the absolute value is incorrect at temperature.\n# For example, taking sensor readings at Z=2 when perfectly homed via tap may read as\n# 1.9 due to temperatures, which is not correct. However, raising the toolhead to Z=2.1\n# will raise the sensor reading to 2.0; likewise, lowering the toolhead to Z=1.9 will\n# lower the sensor reading to 1.8.\n#\n# Care in macros should be taken to not invalidate the Z offset set after a tap\n# by relying on absolute sensor readings.\n#\n\n\n@dataclass\nclass ProbeEddyParams:\n    # The speed at which to perform normal homing operations\n    probe_speed: float = 5.0\n    # The speed at which to lift the toolhead during probing operations\n    lift_speed: float = 10.0\n    # The speed at which to move in the xy plane (typically only for calibration)\n    move_speed: float = 50.0\n    # The height at which the virtual endstop should trigger. A value\n    # between 1.0 and 3.0 is recommended, with 2.0 or 2.5 being good\n    # choices.\n    home_trigger_height: float = 2.0\n    # The amount higher the probe needs to detect the toolhead is at  in order to\n    # allow homing to begin. For example, if the trigger height is 2.0, and the\n    # start offset is 1.5, then homing will abort if the sensor detects the\n    # toolhead is below 3.5mm off the print bed.\n    home_trigger_safe_start_offset: float = 1.0\n    # The amount of time that must elapse from the start of probing until the\n    # safe start position is crossed. This is to make sure there are some values\n    # that are above the safe position before it's crossed, to ensure that homing\n    # doesn't begin with the toolhead too low.\n    home_trigger_safe_time_offset: float = 0.100\n    # The maximum z value to calibrate from. 15.0 is fine as a default, calibrating\n    # at higher values is not needed. Calibration will start with the first\n    # valid height.\n    calibration_z_max: float = 15.0\n    # The \"drive current\" for the LDC1612 sensor. This value is typically\n    # sensor specific and depends on the coil design and the operating distance.\n    # A good starting value for BTT Eddy is 15. A good value can be obtained\n    # by placing the toolhead ~10mm above the bed and running LDC_NG_CALIBRATE_\n    # DRIVE_CURRENT.\n    reg_drive_current: int = 0\n    # The drive current to use for tap operations. If not set, the `reg_drive_current`\n    # value will be used. Tapping involves reading values much closer to the print\n    # bed than basic homing, and may require a different, typically higher,\n    # drive current. For example, BTT Eddy performs best with this value at 16.\n    # Note that the sensor needs to be calibrated for both drive currents separately.\n    # Pass the DRIVE_CURRENT argument to EDDY_NG_CALIBRATE.\n    tap_drive_current: int = 0\n    # The Z position at which to start a tap-home operation. This height may\n    # need to be fine-tuned to ensure that the sensor can provide readings across the\n    # entire tap range (i.e. from this value down to tap_target_z), which in turn\n    # will depend on the tap_drive_current. When the tap_drive_current is\n    # increased, the sensor may not be able to read values at higher heights.\n    # For example, BTT Eddy typically cannot work with heights above 3.5mm with\n    # a drive current of 16.\n    #\n    # Note that all of these values are in terms of offsets from the nozzle\n    # to the toolhead. The actual sensor coil is mounted higher -- but must be placed\n    # between 2.5 and 3mm above the nozzle, ideally around 2.75mm. If there are\n    # amplitude errors, try raising or lowering the sensor coil slightly.\n    tap_start_z: float = 3.0\n    # The target Z position for a tap operation. This is the lowest position that\n    # the toolhead may travel to in case of a failed tap. Do not set this very low,\n    # as it will cause your toolhead to try to push through your build plate in\n    # the case of a failed tap. A value like -0.250 is no worse than moving the\n    # nozzle down one or two notches too far when doing manual Z adjustment.\n    tap_target_z: float = -0.250\n    # the tap mode to use. 'wma' is a derivative of weighted moving average,\n    # 'butter' is a butterworth filter\n    tap_mode: str = \"butter\"\n    # The threshold at which to detect a tap. This value is raw sensor value\n    # specific. A good value can be obtained by running [....] and examining\n    # the graph. See [calibration docs coming soon].\n    #\n    # The meaning of this depends on tap_mode, and the value will be different\n    # if a different tap_mode is used.  You can experiment to arrive at this\n    # value. Typically, a lower value will make tap detection more sensitive,\n    # but might lead to false positives (too early detections). A higher value\n    # may cause the detection to wait too long or miss a tap entirely.\n    # You can pass a THRESHOLD parameter to the TAP command to experiment to\n    # find a good value.\n    #\n    # You may also need to use different thresholds for different build plates.\n    # Note that the default value of this threshold depends on the tap_mode.\n    tap_threshold: float = 250.0\n    # The speed at which a tap operation should be performed at. This shouldn't\n    # be much slower than 3.0, but you can experiment with lower or higher values.\n    # Don't go too high though, because Klipper needs some small amount of time\n    # to react to a tap trigger, and the toolhead will still be moving at this\n    # speed even past the tap point. So, consider any speed you'd feel comfortable\n    # triggering a toolhead move to tap_target_z at.\n    tap_speed: float = 3.0\n    # A static additional amount to add to the computed tap Z offset. Use this if\n    # the computed tap is a bit too high or too low for your taste. Positive\n    # values will raise the toolhead, negative values will lower it.\n    tap_adjust_z: float = 0.0\n    # The number of times to do a tap, averaging the results.\n    tap_samples: int = 3\n    # The maximum number of tap samples.\n    tap_max_samples: int = 5\n    # The maximum standard deviation for any 3 samples to be considered valid.\n    tap_samples_stddev: float = 0.020\n    # Use the median value instead of the mean\n    tap_use_median: bool = False\n    # Where in the time range of tap detection start to the time the threshold\n    # is crossed should the tap be placed. 0.0 places it at the earliest start\n    # of tap detection; 1.0 places it at the point where the threshold is hit.\n    # A value between 0.2-0.5 generally results in more consistent tap position detection,\n    # but you may want to adjust this for your configuration. This is a number\n    # in the range of 0.0 to 1.0.\n    tap_time_position: float = 0.3\n\n    # When probing multiple points (not rapid scan), how long to sample for at each probe point,\n    # after a scan_sample_time_delay delay. The total dwell time at each probe point is\n    # scan_sample_time + scan_sample_time_delay.\n    scan_sample_time: float = 0.100\n    # When probing multiple points (not rapid scan), how long to delay at each probe point\n    # before the scan_sample_time kicks in.\n    scan_sample_time_delay: float = 0.050\n    # number of points to save for calibration\n    calibration_points: int = 150\n    # configuration for butterworth filter\n    tap_butter_lowcut: float = 5.0\n    tap_butter_highcut: float = 25.0\n    tap_butter_order: int = 2\n    # Probe position relative to toolhead\n    x_offset: float = 0.0\n    y_offset: float = 0.0\n    # remove some safety checks, largely for testing/development\n    allow_unsafe: bool = False\n    # whether to write the tap plot for the last tap\n    write_tap_plot: bool = False\n    # whether to write the tap plot for every tap\n    write_every_tap_plot: bool = False\n    # maximum number of errors to allow in a row on the sensor\n    max_errors: int = 0\n    # whether to print lots of verbose debug info to the log\n    debug: bool = True\n\n    tap_trigger_safe_start_height: float = 1.5\n\n    _warning_msgs: List[str] = field(default_factory=list)\n\n    @staticmethod\n    def str_to_floatlist(s):\n        if s is None:\n            return None\n        try:\n            return [float(v) for v in re.split(r\"\\s*,\\s*|\\s+\", s)]\n        except:\n            raise configerror(f\"Can't parse '{s}' as list of floats\")\n\n    def is_default_butter_config(self):\n        return self.tap_butter_lowcut == 5.0 and self.tap_butter_highcut == 25.0 and self.tap_butter_order == 2\n\n    def load_from_config(self, config: ConfigWrapper):\n        mode_choices = [\"wma\", \"butter\"]\n\n        self.probe_speed = config.getfloat(\"probe_speed\", self.probe_speed, above=0.0)\n        self.lift_speed = config.getfloat(\"lift_speed\", self.lift_speed, above=0.0)\n        self.move_speed = config.getfloat(\"move_speed\", self.move_speed, above=0.0)\n        self.home_trigger_height = config.getfloat(\"home_trigger_height\", self.home_trigger_height, minval=1.0)\n        self.home_trigger_safe_start_offset = config.getfloat(\n            \"home_trigger_safe_start_offset\",\n            self.home_trigger_safe_start_offset,\n            minval=0.5,\n        )\n        self.calibration_z_max = config.getfloat(\"calibration_z_max\", self.calibration_z_max, above=0.0)\n\n        self.reg_drive_current = config.getint(\"reg_drive_current\", 0, minval=0, maxval=31)\n        self.tap_drive_current = config.getint(\"tap_drive_current\", 0, minval=0, maxval=31)\n\n        self.tap_start_z = config.getfloat(\"tap_start_z\", self.tap_start_z, above=0.0)\n        self.tap_target_z = config.getfloat(\"tap_target_z\", self.tap_target_z)\n        self.tap_speed = config.getfloat(\"tap_speed\", self.tap_speed, above=0.0)\n        self.tap_adjust_z = config.getfloat(\"tap_adjust_z\", self.tap_adjust_z)\n        self.calibration_points = config.getint(\"calibration_points\", self.calibration_points)\n\n        self.tap_mode = config.getchoice(\"tap_mode\", mode_choices, self.tap_mode)\n        default_tap_threshold = 1000.0  # for wma\n        if self.tap_mode == \"butter\":\n            default_tap_threshold = 250.0\n        self.tap_threshold = config.getfloat(\"tap_threshold\", default_tap_threshold)\n\n        self.scan_sample_time = config.getfloat(\"scan_sample_time\", self.scan_sample_time, above=0.0)\n        self.scan_sample_time_delay = config.getfloat(\"scan_sample_time_delay\", self.scan_sample_time_delay, minval=0.0)\n\n        # for 'butter'\n        self.tap_butter_lowcut = config.getfloat(\"tap_butter_lowcut\", self.tap_butter_lowcut, above=0.0)\n        self.tap_butter_highcut = config.getfloat(\n            \"tap_butter_highcut\",\n            self.tap_butter_highcut,\n            above=self.tap_butter_lowcut,\n        )\n        self.tap_butter_order = config.getint(\"tap_butter_order\", self.tap_butter_order, minval=1)\n\n        self.tap_samples = config.getint(\"tap_samples\", self.tap_samples, minval=1)\n        self.tap_max_samples = config.getint(\"tap_max_samples\", self.tap_max_samples, minval=self.tap_samples)\n        self.tap_samples_stddev = config.getfloat(\"tap_samples_stddev\", self.tap_samples_stddev, above=0.0)\n        self.tap_use_median = config.getboolean(\"tap_use_median\", self.tap_use_median)\n        self.tap_trigger_safe_start_height = config.getfloat(\n            \"tap_trigger_safe_start_height\",\n            -1.0,\n            above=0.0,\n        )\n        self.tap_time_position = config.getfloat(\"tap_time_position\", self.tap_time_position, minval=0.0, maxval=1.0)\n\n        if self.tap_trigger_safe_start_height == -1.0:  # sentinel\n            self.tap_trigger_safe_start_height = self.home_trigger_height / 2.0\n\n        self.allow_unsafe = config.getboolean(\"allow_unsafe\", self.allow_unsafe)\n        self.write_tap_plot = config.getboolean(\"write_tap_plot\", self.write_tap_plot)\n        self.write_every_tap_plot = config.getboolean(\"write_every_tap_plot\", self.write_every_tap_plot)\n        self.debug = config.getboolean(\"debug\", self.debug)\n\n        self.max_errors = config.getint(\"max_errors\", self.max_errors)\n\n        self.x_offset = config.getfloat(\"x_offset\", self.x_offset)\n        self.y_offset = config.getfloat(\"y_offset\", self.y_offset)\n\n        self.validate(config)\n\n    def validate(self, config: ConfigWrapper = None):\n        printer = config.get_printer()\n        req_cal_z_max = self.home_trigger_safe_start_offset + self.home_trigger_height + 1.0\n        if self.calibration_z_max < req_cal_z_max:\n            raise printer.config_error(\n                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})\"\n            )\n        if self.x_offset == 0.0 and self.y_offset == 0.0 and not self.allow_unsafe:\n            raise printer.config_error(\"ProbeEddy: x_offset and y_offset are both 0.0; is the sensor really mounted at the nozzle?\")\n\n        if self.home_trigger_height <= self.tap_trigger_safe_start_height:\n            raise printer.config_error(\"ProbeEddy: home_trigger_height must be greater than tap_trigger_safe_start_height\")\n\n        need_scipy = False\n        if self.tap_mode == \"butter\" and not self.is_default_butter_config():\n            need_scipy = True\n\n        if need_scipy and not scipy:\n            raise printer.config_error(\n                \"ProbeEddy: butter mode with custom filter parameters requires scipy, which is not available; please install scipy, use the defaults, or use wma mode\"\n            )\n\n\n@dataclass\nclass ProbeEddyProbeResult:\n    samples: List[float]\n    mean: float = 0.0\n    median: float = 0.0\n    min_value: float = 0.0\n    max_value: float = 0.0\n    tstart: float = 0.0\n    tend: float = 0.0\n    errors: int = 0\n\n    USE_MEAN_FOR_VALUE: ClassVar[bool] = False\n\n    @property\n    def valid(self):\n        return len(self.samples) > 0\n\n    @property\n    def value(self):\n        return self.mean if self.USE_MEAN_FOR_VALUE else self.median\n\n    @property\n    def stddev(self):\n        stddev_sum = np.sum([(s - self.value) ** 2.0 for s in self.samples])\n        return float((stddev_sum / len(self.samples)) ** 0.5)\n\n    @classmethod\n    def make(cls, times: List[float], heights: List[float], errors: int = 0) -> ProbeEddyProbeResult:\n        h = np.array(heights)\n        return ProbeEddyProbeResult(\n            samples=h.tolist(),\n            mean=float(np.mean(h)),\n            median=float(np.median(h)),\n            min_value=float(np.min(h)),\n            max_value=float(np.max(h)),\n            tstart=float(times[0]),\n            tend=float(times[-1]),\n            errors=errors\n        )\n\n    def __format__(self, spec):\n        if spec == \"v\":\n            return f\"{self.value:.3f}\"\n        if self.USE_MEAN_FOR_VALUE:\n            value = f\"{self.mean:.3f}\"\n            extra = f\"med={self.median:.3f}\"\n        else:\n            value = f\"{self.median:.3f}\"\n            extra = f\"avg={self.mean:.3f}\"\n\n        return f\"{value} ({extra}, {self.min_value:.3f} to {self.max_value:.3f}, [{self.stddev:.3f}])\"\n\n\n@final\nclass ProbeEddy:\n    def __init__(self, config: ConfigWrapper):\n        logging.info(\"Hello from ProbeEddyNG\")\n\n        self._printer: Printer = config.get_printer()\n        self._reactor = self._printer.get_reactor()\n        self._gcode = self._printer.lookup_object(\"gcode\")\n        self._full_name = config.get_name()\n        self._name = self._full_name.split()[-1]\n\n        sensors = {\n            \"ldc1612\": ldc1612_ng.LDC1612_ng,\n            \"btt_eddy\": ldc1612_ng.LDC1612_ng,\n            \"cartographer\": ldc1612_ng.LDC1612_ng,\n            \"mellow_fly\": ldc1612_ng.LDC1612_ng,\n            \"ldc1612_internal_clk\": ldc1612_ng.LDC1612_ng,\n        }\n        sensor_type = config.getchoice(\"sensor_type\", {s: s for s in sensors})\n\n        self._sensor_type = sensor_type\n        self._sensor = sensors[sensor_type](config)\n        self._mcu = self._sensor.get_mcu()\n        self._toolhead: ToolHead = None  # filled in _handle_connect\n        self._trapq = None\n\n        self.params = ProbeEddyParams()\n        self.params.load_from_config(config)\n\n        # figure out if either of these comes from the autosave section\n        # so we can sort out what we want to write out later on\n        asfc = self._printer.lookup_object(\"configfile\").autosave.fileconfig\n        self._saved_reg_drive_current = asfc.getint(self._full_name, \"reg_drive_current\", fallback=None)\n        self._saved_tap_drive_current = asfc.getint(self._full_name, \"tap_drive_current\", fallback=None)\n\n        # in case there's legacy drive currents\n        old_saved_reg_drive_current = asfc.getint(self._full_name, \"saved_reg_drive_current\", fallback=0)\n        old_saved_tap_drive_current = asfc.getint(self._full_name, \"saved_tap_drive_current\", fallback=0)\n\n        self._reg_drive_current = self.params.reg_drive_current or old_saved_reg_drive_current or self._sensor._drive_current\n        self._tap_drive_current = self.params.tap_drive_current or old_saved_tap_drive_current or self._reg_drive_current\n\n        # at what minimum physical height to start homing. It must be above the safe start position,\n        # because we need to move from the start through the safe start position\n        self._home_start_height = self.params.home_trigger_height + self.params.home_trigger_safe_start_offset + 1.0\n\n        # physical offsets between probe and nozzle\n        self.offset = {\n            \"x\": self.params.x_offset,\n            \"y\": self.params.y_offset,\n        }\n\n        version = config.getint(\"calibration_version\", default=-1)\n        calibration_bad = False\n        if version == -1:\n            if config.get(\"calibrated_drive_currents\", None) is not None:\n                calibration_bad = True\n        elif version != ProbeEddyFrequencyMap.calibration_version:\n            calibration_bad = True\n\n        calibrated_drive_currents = config.getintlist(\"calibrated_drive_currents\", [])\n\n        self._dc_to_fmap: Dict[int, ProbeEddyFrequencyMap] = {}\n        if not calibration_bad:\n            for dc in calibrated_drive_currents:\n                fmap = ProbeEddyFrequencyMap(self)\n                if fmap.load_from_config(config, dc):\n                    self._dc_to_fmap[dc] = fmap\n        else:\n            for dc in calibrated_drive_currents:\n                # read so that there are no warnings about unknown fields\n                _ = config.get(f\"calibration_{dc}\")\n            self.params._warning_msgs.append(\"EDDYng calibration: calibration data invalid, please recalibrate\")\n\n        # Our virtual endstop wrapper -- used for homing.\n        self._endstop_wrapper = ProbeEddyEndstopWrapper(self)\n\n        # There can only be one active sampler at a time\n        self._sampler: ProbeEddySampler = None\n        self._last_sampler: ProbeEddySampler = None\n        self.save_samples_path = None\n\n        # The last tap Z value, in absolute axis terms. Used for status.\n        self._last_tap_z = 0.0\n        # The last gcode offset applied after tap, either the tap\n        # value, or 0.0 if HOME_Z=1\n        self._last_tap_gcode_adjustment = 0.0\n\n        # This class emulates \"PrinterProbe\". We use some existing helpers to implement\n        # functionality like start_session\n        self._printer.add_object(\"probe\", self)\n\n        self._bed_mesh_helper = BedMeshScanHelper(self, config)\n\n        # TODO: get rid of this\n        if hasattr(probe, \"ProbeCommandHelper\"):\n            self._cmd_helper = probe.ProbeCommandHelper(config, self, self._endstop_wrapper.query_endstop)\n        else:\n            self._cmd_helper = None\n\n        # when doing a scan, what's the offset between probe readings at the bed\n        # scan height and the accurate bed height, based on the last tap.\n        self._tap_offset = 0.0\n        self._last_probe_result = 0.0\n\n        # runtime configurable\n        self._tap_adjust_z = self.params.tap_adjust_z\n\n        # define our own commands\n        self._dummy_gcode_cmd: GCodeCommand = self._gcode.create_gcode_command(\"\", \"\", {})\n        self.define_commands(self._gcode)\n\n        self._printer.register_event_handler(\"gcode:command_error\", self._handle_command_error)\n        self._printer.register_event_handler(\"klippy:connect\", self._handle_connect)\n\n        # patch bed_mesh because Klipper\n        if not IS_KALICO:\n            bed_mesh.ProbeManager.start_probe = bed_mesh_ProbeManager_start_probe_override\n\n    def _log_error(self, msg):\n        logging.error(f\"{self._name}: {msg}\")\n        self._gcode.respond_raw(f\"!! EDDYng: {msg}\\n\")\n\n    def _log_warning(self, msg):\n        logging.warning(f\"{self._name}: {msg}\")\n        self._gcode.respond_raw(f\"!! EDDYng: {msg}\\n\")\n\n    def _log_msg(self, msg):\n        logging.info(f\"{self._name}: {msg}\")\n        self._gcode.respond_info(f\"{msg}\", log=False)\n\n    def _log_info(self, msg):\n        logging.info(f\"{self._name}: {msg}\")\n\n    def _log_debug(self, msg):\n        if self.params.debug:\n            logging.info(f\"{self._name}: {msg}\")\n\n    def define_commands(self, gcode):\n        gcode.register_command(\"PROBE_EDDY_NG_STATUS\", self.cmd_STATUS, self.cmd_STATUS_help)\n        gcode.register_command(\n            \"PROBE_EDDY_NG_CALIBRATE\",\n            self.cmd_CALIBRATE,\n            self.cmd_CALIBRATE_help,\n        )\n        gcode.register_command(\n            \"PROBE_EDDY_NG_CALIBRATION_STATUS\",\n            self.cmd_CALIBRATION_STATUS,\n            self.cmd_CALIBRATION_STATUS_help,\n        )\n        gcode.register_command(\n            \"PROBE_EDDY_NG_SETUP\",\n            self.cmd_SETUP,\n            self.cmd_SETUP_help,\n        )\n        gcode.register_command(\n            \"PROBE_EDDY_NG_CLEAR_CALIBRATION\",\n            self.cmd_CLEAR_CALIBRATION,\n            self.cmd_CLEAR_CALIBRATION_help,\n        )\n        gcode.register_command(\"PROBE_EDDY_NG_PROBE\", self.cmd_PROBE, self.cmd_PROBE_help)\n        gcode.register_command(\n            \"PROBE_EDDY_NG_PROBE_STATIC\",\n            self.cmd_PROBE_STATIC,\n            self.cmd_PROBE_STATIC_help,\n        )\n        gcode.register_command(\n            \"PROBE_EDDY_NG_PROBE_ACCURACY\",\n            self.cmd_PROBE_ACCURACY,\n            self.cmd_PROBE_ACCURACY_help,\n        )\n        gcode.register_command(\"PROBE_EDDY_NG_TAP\", self.cmd_TAP, self.cmd_TAP_help)\n        gcode.register_command(\n            \"PROBE_EDDY_NG_SET_TAP_OFFSET\",\n            self.cmd_SET_TAP_OFFSET,\n            \"Set or clear the tap offset for the bed mesh scan and other probe operations\",\n        )\n        gcode.register_command(\n            \"PROBE_EDDY_NG_SET_TAP_ADJUST_Z\",\n            self.cmd_SET_TAP_ADJUST_Z,\n            \"Set the tap adjustment value\",\n        )\n        gcode.register_command(\n            \"PROBE_EDDY_NG_TEST_DRIVE_CURRENT\",\n            self.cmd_TEST_DRIVE_CURRENT,\n            \"Test a drive current.\",\n        )\n        gcode.register_command(\"Z_OFFSET_APPLY_PROBE\", None)\n        gcode.register_command(\n            \"Z_OFFSET_APPLY_PROBE\",\n            self.cmd_Z_OFFSET_APPLY_PROBE,\n            \"Apply the current G-Code Z offset to tap_adjust_z\",\n        )\n\n        # some handy aliases while I'm debugging things to save my fingers\n        gcode.register_command(\n            \"PES\",\n            self.cmd_STATUS,\n            self.cmd_STATUS_help + \" (alias for PROBE_EDDY_NG_STATUS)\",\n        )\n        gcode.register_command(\n            \"PEP\",\n            self.cmd_PROBE,\n            self.cmd_PROBE_help + \" (alias for PROBE_EDDY_NG_PROBE)\",\n        )\n        gcode.register_command(\n            \"PEPS\",\n            self.cmd_PROBE_STATIC,\n            self.cmd_PROBE_STATIC_help + \" (alias for PROBE_EDDY_NG_PROBE_STATIC)\",\n        )\n        gcode.register_command(\n            \"PETAP\",\n            self.cmd_TAP,\n            self.cmd_TAP_help + \" (alias for PROBE_EDDY_NG_TAP)\",\n        )\n\n        gcode.register_command(\"EDDYNG_BED_MESH_EXPERIMENTAL\", self.cmd_MESH, \"\")\n        gcode.register_command(\"EDDYNG_START_STREAM_EXPERIMENTAL\", self.cmd_START_STREAM, \"\")\n        gcode.register_command(\"EDDYNG_STOP_STREAM_EXPERIMENTAL\", self.cmd_STOP_STREAM, \"\")\n\n    def _handle_command_error(self, gcmd=None):\n        try:\n            if self._sampler is not None:\n                self._sampler.finish()\n        except:\n            logging.exception(\"EDDYng handle_command_error: sampler.finish() failed\")\n\n    def _handle_connect(self):\n        self._toolhead = self._printer.lookup_object(\"toolhead\")\n        self._trapq = self._toolhead.get_trapq()\n        for msg in self.params._warning_msgs:\n            self._log_warning(msg)\n\n    def _get_trapq_position(self, print_time: float) -> Tuple[Tuple[float, float, float], float]:\n        ffi_main, ffi_lib = chelper.get_ffi()\n        data = ffi_main.new(\"struct pull_move[1]\")\n        count = ffi_lib.trapq_extract_old(self._trapq, data, 1, 0.0, print_time)\n        if not count:\n            return None, None\n        move = data[0]\n        move_time = max(0.0, min(move.move_t, print_time - move.print_time))\n        dist = (move.start_v + 0.5 * move.accel * move_time) * move_time\n        pos = (\n            move.start_x + move.x_r * dist,\n            move.start_y + move.y_r * dist,\n            move.start_z + move.z_r * dist,\n        )\n        velocity = move.start_v + move.accel * move_time\n        return pos, velocity\n\n    def _get_trapq_height(self, print_time: float) -> float:\n        th_pos, _ = self._get_trapq_position(print_time)\n        if th_pos is None:\n            return None\n        return th_pos[2]\n\n    def current_drive_current(self) -> int:\n        return self._sensor.get_drive_current()\n\n    def reset_drive_current(self, tap=False):\n        dc = self._tap_drive_current if tap else self._reg_drive_current\n        if dc == 0:\n            raise self._printer.command_error(f\"Unknown {'tap' if tap else 'homing'} drive current\")\n        self._sensor.set_drive_current(dc)\n\n    def map_for_drive_current(self, dc: Optional[int] = None) -> ProbeEddyFrequencyMap:\n        if dc is None:\n            dc = self.current_drive_current()\n        if dc not in self._dc_to_fmap:\n            raise self._printer.command_error(f\"Drive current {dc} not calibrated\")\n        return self._dc_to_fmap[dc]\n\n    # helpers to forward to the map\n    def height_to_freq(self, height: float, drive_current: Optional[int] = None) -> float:\n        if drive_current is None:\n            drive_current = self.current_drive_current()\n        return self.map_for_drive_current(drive_current).height_to_freq(height)\n\n    def freq_to_height(self, freq: float, drive_current: Optional[int] = None) -> float:\n        if drive_current is None:\n            drive_current = self.current_drive_current()\n        return self.map_for_drive_current(drive_current).freq_to_height(freq)\n\n    def calibrated(self, drive_current: Optional[int] = None) -> bool:\n        if drive_current is None:\n            drive_current = self.current_drive_current()\n        return drive_current in self._dc_to_fmap and self._dc_to_fmap[drive_current].calibrated()\n\n    def _print_time_now(self):\n        return self._mcu.estimated_print_time(self._reactor.monotonic())\n\n    def _z_homed(self):\n        curtime = self._reactor.monotonic()\n        kin_status = self._printer.lookup_object(\"toolhead\").get_kinematics().get_status(curtime)\n        return \"z\" in kin_status[\"homed_axes\"]\n\n    def _xy_homed(self):\n        curtime = self._reactor.monotonic()\n        kin_status = self._printer.lookup_object(\"toolhead\").get_kinematics().get_status(curtime)\n        return \"x\" in kin_status[\"homed_axes\"] and \"y\" in kin_status[\"homed_axes\"]\n\n    def _z_hop(self, by=5.0):\n        if by < 0.0:\n            raise self._printer.command_error(\"Z hop must be positive\")\n        toolhead: ToolHead = self._printer.lookup_object(\"toolhead\")\n        curpos = toolhead.get_position()\n        curpos[2] = curpos[2] + by\n        toolhead.manual_move(curpos, self.params.probe_speed)\n\n    def _set_toolhead_position(self, pos, homing_axes):\n        # klipper changed homing_axes to be a \"xyz\" string instead\n        # of a tuple randomly on jan10 without support for the old\n        # syntax\n        func = self._toolhead.set_position\n        kind = type(func.__defaults__[0])\n        if kind is str:\n            # new\n            homing_axes_str = \"\".join([\"xyz\"[axis] for axis in homing_axes])\n            return self._toolhead.set_position(pos, homing_axes=homing_axes_str)\n        else:\n            # old\n            return self._toolhead.set_position(pos, homing_axes=homing_axes)\n\n    def _z_not_homed(self):\n        kin = self._toolhead.get_kinematics()\n        # klipper got rid of this\n        if hasattr(kin, \"note_z_not_homed\"):\n            kin.note_z_not_homed()\n        else:\n            try:\n                kin.clear_homing_state(\"z\")\n            except TypeError:\n                raise self._printer.command_error(\n                    \"clear_homing_state failed: please update Klipper, your klipper is from the brief 5 day window where this was broken\"\n                )\n\n    def save_config(self):\n        configfile = self._printer.lookup_object(\"configfile\")\n        configfile.remove_section(self._full_name)\n\n        configfile.set(\n            self._full_name,\n            \"calibrated_drive_currents\",\n            str.join(\", \", [str(dc) for dc in self._dc_to_fmap.keys()]),\n        )\n        configfile.set(\n            self._full_name,\n            \"calibration_version\",\n            str(ProbeEddyFrequencyMap.calibration_version),\n        )\n\n        if self.params.reg_drive_current != self._reg_drive_current or self.params.reg_drive_current == self._saved_reg_drive_current:\n            configfile.set(self._full_name, \"reg_drive_current\", str(self._reg_drive_current))\n\n        if self.params.tap_drive_current != self._tap_drive_current or self.params.tap_drive_current == self._saved_tap_drive_current:\n            configfile.set(self._full_name, \"tap_drive_current\", str(self._tap_drive_current))\n\n        for _, fmap in self._dc_to_fmap.items():\n            fmap.save_calibration()\n\n        self._log_msg(\"Calibration saved. Issue a SAVE_CONFIG to write the values to your config file and restart Klipper.\")\n\n    def start_sampler(self, *args, **kwargs) -> ProbeEddySampler:\n        if self._sampler:\n            raise self._printer.command_error(\"EDDYng: Already sampling! (This shouldn't happen; FIRMWARE_RESTART to fix)\")\n        self._sampler = ProbeEddySampler(self, *args, **kwargs)\n        self._sampler.start()\n        return self._sampler\n\n    def sampler_is_active(self):\n        return self._sampler is not None and self._sampler.active()\n\n    # Called by samplers when they're finished\n    def _sampler_finished(self, sampler: ProbeEddySampler, **kwargs):\n        if self._sampler is not sampler:\n            raise self._printer.command_error(\"EDDYng finishing sampler that's not active\")\n\n        self._last_sampler = sampler\n        self._sampler = None\n\n        if self.save_samples_path is not None:\n            with open(self.save_samples_path, \"w\") as data_file:\n                times = sampler.times\n                raw_freqs = sampler.raw_freqs\n                freqs = sampler.freqs\n                heights = sampler.heights\n\n                data_file.write(\"time,frequency,z,kin_z,kin_v,raw_f,trigger_time,tap_start_time\\n\")\n                trigger_time = kwargs.get(\"trigger_time\", \"\")\n                tap_start_time = kwargs.get(\"tap_start_time\", \"\")\n                for i in range(len(times)):\n                    past_pos, past_v = self._get_trapq_position(times[i])\n                    past_k_z = past_pos[2] if past_pos is not None else \"\"\n                    past_v = past_v if past_v is not None else \"\"\n                    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\")\n            logging.info(f\"Wrote {len(times)} samples to {self.save_samples_path}\")\n            self.save_samples_path = None\n\n    def cmd_MESH(self, gcmd: GCodeCommand):\n        self._bed_mesh_helper.scan()\n\n    cmd_STATUS_help = \"Query the last raw coil value and status\"\n\n    def cmd_STATUS(self, gcmd: GCodeCommand):\n        result = self._sensor.read_one_value()\n\n        status = result.status\n        freqval = result.freqval\n        freq = result.freq\n        height = -math.inf\n\n        err = \"\"\n        if freqval > 0x0FFFFFFF:\n            height = -math.inf\n            freq = 0.0\n            err = f\"ERROR: {bin(freqval >> 28)} \"\n        elif freq <= 0.0:\n            err += \"(Zero frequency) \"\n        elif self.calibrated():\n            height = self.freq_to_height(freq)\n        else:\n            err += \"(Not calibrated) \"\n\n        gcmd.respond_info(\n            f\"Last coil value: {freq:.2f} ({height:.3f}mm) raw: {hex(freqval)} {err}status: {hex(status)} {self._sensor.status_to_str(status)}\"\n        )\n\n    cmd_PROBE_ACCURACY_help = \"Probe accuracy\"\n\n    def cmd_PROBE_ACCURACY(self, gcmd: GCodeCommand):\n        if not self._z_homed():\n            raise self._printer.command_error(\"Must home Z before PROBE_ACCURACY\")\n\n        # How long to read at each sample time\n        duration: float = gcmd.get_float(\"DURATION\", 0.100, above=0.0)\n        # whether to check +/- 1mm positions for accuracy\n        start_z: float = gcmd.get_float(\"Z\", 5.0)\n        offsets: str = gcmd.get(\"OFFSETS\", None)\n\n        probe_speed = gcmd.get_float(\"SPEED\", self.params.probe_speed, above=0.0)\n        lift_speed = gcmd.get_float(\"LIFT_SPEED\", self.params.lift_speed, above=0.0)\n\n        probe_zs = [start_z]\n\n        if offsets is not None:\n            probe_zs.extend([float(v) + start_z for v in offsets.split(\",\")])\n        else:\n            probe_zs.extend(np.arange(0.5, start_z, 0.5).tolist())\n\n        probe_zs.sort()\n        probe_zs.reverse()\n\n        # drive current to use\n        old_drive_current = self.current_drive_current()\n        drive_current: int = gcmd.get_int(\"DRIVE_CURRENT\", old_drive_current, minval=0, maxval=31)\n\n        if not self.calibrated(drive_current):\n            raise self._printer.command_error(f\"Drive current {drive_current} not calibrated\")\n\n        th = self._toolhead\n        try:\n            self._sensor.set_drive_current(drive_current)\n\n            th.manual_move(\n                [None, None, probe_zs[0] + 1.0],\n                lift_speed,\n            )\n            th.wait_moves()\n\n            results = []\n            ranges = []\n            from_zs = []\n            stddev_sums = []\n            stddev_count = 0\n\n            for pz in probe_zs:\n                th.manual_move([None, None, pz], probe_speed)\n                th.dwell(0.050)\n                th.wait_moves()\n\n                result = self.probe_static_height(duration=duration)\n                rangev = result.max_value - result.min_value\n                from_z = result.value - pz\n                stddev_sum = np.sum([(s - result.value) ** 2.0 for s in result.samples])\n\n                self._log_msg(f\"Probe at z={pz:.3f} is {result}\")\n\n                stddev_sums.append(stddev_sum)\n                stddev_count += len(result.samples)\n                results.append(result)\n                ranges.append(rangev)\n                from_zs.append(from_z)\n\n            if len(results) > 1:\n                avg_range = np.mean(ranges)\n                avg_from_z = np.mean(from_zs)\n                stddev = (np.sum(stddev_sums) / stddev_count) ** 0.5\n                gcmd.respond_info(f\"Probe spread: {avg_range:.3f}, z deviation: {avg_from_z:.3f}, stddev: {stddev:.3f}\")\n\n        finally:\n            self._sensor.set_drive_current(old_drive_current)\n            th.manual_move(\n                [None, None, start_z],\n                lift_speed,\n            )\n\n    cmd_CLEAR_CALIBRATION_help = \"Clear calibration for all drive currents\"\n\n    def cmd_CLEAR_CALIBRATION(self, gcmd: GCodeCommand):\n        drive_current: int = gcmd.get_int(\"DRIVE_CURRENT\", -1)\n        if drive_current == -1:\n            self._dc_to_fmap = {}\n            gcmd.respond_info(\"Cleared calibration for all drive currents\")\n        else:\n            if drive_current not in self._dc_to_fmap:\n                raise self._printer.command_error(f\"Drive current {drive_current} not calibrated\")\n            del self._dc_to_fmap[drive_current]\n            gcmd.respond_info(f\"Cleared calibration for drive current {drive_current}\")\n        self.save_config()\n\n    cmd_CALIBRATION_STATUS_help = \"Display information about EDDYng calibration\"\n\n    def cmd_CALIBRATION_STATUS(self, gcmd: GCodeCommand):\n        for dc in self._dc_to_fmap:\n            m = self._dc_to_fmap[dc]\n            hmin, hmax = m.height_range\n            fmin, fmax = m.freq_range\n            fspread = m.freq_spread()\n            self._log_msg(\n                f\"Drive current {dc}: {hmin:.3f} to {hmax:.3f} ({fmin:.1f} to {fmax:.1f}, {fspread:.2f}%; ftoh_high: {m._ftoh_high is not None})\"\n            )\n\n    def cmd_SET_TAP_OFFSET(self, gcmd: GCodeCommand):\n        value = gcmd.get_float(\"VALUE\", None)\n        adjust = gcmd.get_float(\"ADJUST\", None)\n        tap_offset = self._tap_offset\n        if value is not None:\n            tap_offset = value\n        if adjust is not None:\n            tap_offset += adjust\n        self._tap_offset = tap_offset\n        gcmd.respond_info(f\"Set tap offset: {tap_offset:.3f}\")\n\n    def cmd_SET_TAP_ADJUST_Z(self, gcmd: GCodeCommand):\n        value = gcmd.get_float(\"VALUE\", None)\n        adjust = gcmd.get_float(\"ADJUST\", None)\n        tap_adjust_z = self._tap_adjust_z\n        if value is not None:\n            tap_adjust_z = value\n        if adjust is not None:\n            tap_adjust_z += adjust\n        self._tap_adjust_z = tap_adjust_z\n\n        if self.params.tap_adjust_z != self._tap_adjust_z:\n            configfile = self._printer.lookup_object(\"configfile\")\n            configfile.set(self._full_name, \"tap_adjust_z\", str(float(self._tap_adjust_z)))\n\n        gcmd.respond_info(f\"Set tap_adjust_z: {tap_adjust_z:.3f} (SAVE_CONFIG to make it permanent)\")\n\n    def cmd_Z_OFFSET_APPLY_PROBE(self, gcmd: GCodeCommand):\n        gcode_move = self._printer.lookup_object(\"gcode_move\")\n        offset = gcode_move.get_status()[\"homing_origin\"].z\n        offset += self.params.tap_adjust_z\n        offset -= self._last_tap_gcode_adjustment\n        configfile = self._printer.lookup_object(\"configfile\")\n        configfile.set(self._full_name, \"tap_adjust_z\", f\"{offset:.3f}\")\n        self._log_msg(\n            f\"{self._name}: new tap_adjust_z: {offset:.3f}\\n\"\n            \"The SAVE_CONFIG command will update the printer config file\\n\"\n            \"with the above and restart the printer.\"\n        )\n\n    def probe_static_height(self, duration: float = 0.100) -> ProbeEddyProbeResult:\n        with self.start_sampler() as sampler:\n            now = self._print_time_now()\n            sampler.wait_for_sample_at_time(now + (duration + self._sensor._ldc_settle_time))\n            sampler.finish()\n\n        if sampler.height_count == 0:\n            return ProbeEddyProbeResult([])\n\n        etime = sampler.times[-1]\n        stime = etime - duration\n\n        first_idx = bisect.bisect_left(sampler.times, stime)\n        if first_idx == len(sampler.times):\n            raise self._printer.command_error(f\"No samples in time range\")\n\n        errors = sampler.error_count\n        return ProbeEddyProbeResult.make(sampler.times[first_idx:], sampler.heights[first_idx:], errors=errors)\n\n    cmd_PROBE_help = \"Probe the height using the eddy current sensor, moving the toolhead to the home trigger height, or Z if specified.\"\n\n    def cmd_PROBE(self, gcmd: GCodeCommand):\n        if not self._z_homed():\n            raise self._printer.command_error(\"Must home Z before PROBE\")\n\n        z: float = gcmd.get_float(\"Z\", self.params.home_trigger_height)\n\n        th = self._printer.lookup_object(\"toolhead\")\n        th_pos = th.get_position()\n        if th_pos[2] < z:\n            th.manual_move([None, None, z + 3.0], self.params.lift_speed)\n        th.manual_move([None, None, z], self.params.probe_speed)\n        th.dwell(0.100)\n        th.wait_moves()\n\n        self.cmd_PROBE_STATIC(gcmd)\n\n    cmd_PROBE_STATIC_help = \"Probe the current height using the eddy current sensor without moving the toolhead.\"\n\n    def cmd_PROBE_STATIC(self, gcmd: GCodeCommand):\n        old_drive_current = self.current_drive_current()\n        drive_current: int = gcmd.get_int(\"DRIVE_CURRENT\", old_drive_current, minval=0, maxval=31)\n        duration: float = gcmd.get_float(\"DURATION\", 0.100, above=0.0)\n        save: bool = gcmd.get_int(\"SAVE\", 0) == 1\n        home_z: bool = gcmd.get_int(\"HOME_Z\", 0) == 1\n\n        if not self.calibrated(drive_current):\n            raise self._printer.command_error(f\"Drive current {drive_current} not calibrated\")\n\n        try:\n            self._sensor.set_drive_current(drive_current)\n\n            if save:\n                self.save_samples_path = \"/tmp/eddy-probe-static.csv\"\n\n            r = self.probe_static_height(duration)\n\n            if self._cmd_helper is not None:\n                self._cmd_helper.last_z_result = float(r.value)\n\n            self._last_probe_result = float(r.value)\n\n            if home_z:\n                th = self._printer.lookup_object(\"toolhead\")\n                th_pos = th.get_position()\n                th_pos[2] = r.value\n                self._set_toolhead_position(th_pos, [2])\n                self._log_debug(f\"Homed Z to {r}\")\n            else:\n                self._log_msg(f\"Probed {r}\")\n\n        finally:\n            self._sensor.set_drive_current(old_drive_current)\n\n    cmd_SETUP_help = \"Setup\"\n\n    def cmd_SETUP(self, gcmd: GCodeCommand):\n        if not self._xy_homed():\n            raise self._printer.command_error(\"X and Y must be homed before setup\")\n\n        if self._z_homed():\n            # z-hop so that manual probe helper doesn't complain if we're already\n            # at the right place\n            self._z_hop()\n\n        # Now reset the axis so that we have a full range to calibrate with\n        th = self._printer.lookup_object(\"toolhead\")\n        th_pos = th.get_position()\n        # XXX This is proably not correct for some printers?\n        zrange = th.get_kinematics().rails[2].get_range()\n        th_pos[2] = zrange[1] - 20.0\n        self._set_toolhead_position(th_pos, [2])\n\n        manual_probe.ManualProbeHelper(\n            self._printer,\n            gcmd,\n            lambda kin_pos: self.cmd_SETUP_next(gcmd, kin_pos),\n        )\n\n    def cmd_SETUP_next(self, gcmd: GCodeCommand, kin_pos: Optional[List[float]]):\n        if kin_pos is None:\n            # User cancelled ManualProbeHelper\n            self._z_not_homed()\n            return\n\n        debug = 1 if self.params.debug else 0\n        debug = gcmd.get_int(\"DEBUG\", debug) == 1\n\n        # We just did a ManualProbeHelper, so we're going to zero the z-axis\n        # to make the following code easier, so it can assume z=0 is actually real zero.\n        th = self._printer.lookup_object(\"toolhead\")\n        th_pos = th.get_position()\n        th_pos[2] = 0.0\n        self._set_toolhead_position(th_pos, [2])\n\n        # Note that the default is the default drive current\n        drive_current: int = gcmd.get_int(\n            \"DRIVE_CURRENT\",\n            self._sensor._default_drive_current,\n            minval=0,\n            maxval=31,\n        )\n\n        max_dc_increase = 0\n        if self._sensor_type == \"ldc1612\" or self._sensor_type == \"btt_eddy\" or self._sensor_type == \"ldc1612_internal_clk\":\n            max_dc_increase = 5\n        max_dc_increase = gcmd.get_int(\"MAX_DC_INCREASE\", max_dc_increase, minval=0, maxval=30)\n\n        # lift up above cal_z_max, and then move over so the probe\n        # is over the nozzle position\n        th.manual_move(\n            [None, None, self.params.calibration_z_max + 3.0],\n            self.params.lift_speed,\n        )\n        th.manual_move(\n            [\n                th_pos[0] - self.offset[\"x\"],\n                th_pos[1] - self.offset[\"y\"],\n                None,\n            ],\n            self.params.move_speed,\n        )\n\n        # This is going to automate setup.\n        # The setup state machine looks like this:\n        # 1. Finding homing drive current\n        # 2. Finding tapping drive current\n        FINDING_HOMING = 1\n        FINDING_TAP = 2\n        DONE = 3\n\n        start_drive_current = drive_current\n        result_msg = None\n\n        self._log_msg(\"setup: calibrating homing\")\n        state = FINDING_HOMING\n        while state < DONE:\n            mapping, fth_rms, htf_rms = self._create_mapping(\n                self.params.calibration_z_max,\n                0.0,  # z_target\n                self.params.probe_speed,\n                self.params.lift_speed,\n                drive_current,\n                report_errors=debug,\n                write_debug_files=debug,\n            )\n\n            homing_req_min = 0.5\n            homing_req_max = 5.0\n            tap_req_min = 0.025\n            tap_req_max = 3.0\n\n            ok_for_homing = mapping is not None\n            ok_for_tap = mapping is not None\n\n            if ok_for_homing and (mapping.height_range[0] > homing_req_min or mapping.height_range[1] < homing_req_max):\n                ok_for_homing = False\n            if ok_for_tap and (mapping.height_range[0] > tap_req_min or mapping.height_range[1] < tap_req_max):\n                ok_for_tap = False\n\n            if ok_for_homing or ok_for_tap:\n                self._log_info(f\"dc {drive_current} homing {ok_for_homing} tap {ok_for_tap}, {fth_rms} {htf_rms}\")\n                if mapping.freq_spread() < 0.30:\n                    self._log_warning(\n                        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.)\"\n                    )\n                    ok_for_homing = ok_for_tap = False\n                if fth_rms is None or fth_rms > 0.025:\n                    self._log_msg(f\"calibration error rate is too high ({fth_rms}) at drive current {drive_current}.\")\n                    ok_for_homing = ok_for_tap = False\n\n            if state == FINDING_HOMING and ok_for_homing:\n                self._dc_to_fmap[drive_current] = mapping\n                self._reg_drive_current = drive_current\n                self._log_msg(f\"using {drive_current} for homing.\")\n                state = FINDING_TAP\n\n            if state == FINDING_TAP and ok_for_tap:\n                self._dc_to_fmap[drive_current] = mapping\n                self._tap_drive_current = drive_current\n                self._log_msg(f\"using {drive_current} for tap.\")\n                state = DONE\n\n            if state == DONE:\n                result_msg = \"Setup success. Please check whether homing works with G28 Z, then check if tap works with PROBE_EDDY_NG_TAP.\"\n                break\n\n            if drive_current - start_drive_current >= max_dc_increase:\n                # we've failed completely\n                if state == FINDING_HOMING:\n                    result_msg = \"Failed to find homing drive current. (Have you checked the sensor height?)\"\n                elif state == FINDING_TAP:\n                    result_msg = \"Failed to find tap drive current, but homing is set up. (Have you checked the sensor height?)\"\n                else:\n                    result_msg = \"Unknown state?\"\n                break\n\n            # increase DC and keep going\n            drive_current += 1\n\n        if state == DONE:\n            self._log_msg(result_msg)\n        else:\n            self._log_error(result_msg)\n\n        if state > FINDING_HOMING:\n            self.reset_drive_current()\n            self.save_config()\n\n        self._z_not_homed()\n\n    cmd_CALIBRATE_help = (\n        \"Calibrate the eddy current sensor. Specify DRIVE_CURRENT to calibrate for a different drive current \"\n        + \"than the default. Specify START_Z to set a different calibration start point.\"\n    )\n\n    def cmd_CALIBRATE(self, gcmd: GCodeCommand):\n        if not self._xy_homed():\n            raise self._printer.command_error(\"X and Y must be homed before calibrating\")\n\n        if self._z_homed():\n            # z-hop so that manual probe helper doesn't complain if we're already\n            # at the right place\n            self._z_hop()\n\n        # Now reset the axis so that we have a full range to calibrate with\n        th = self._printer.lookup_object(\"toolhead\")\n        th_pos = th.get_position()\n        # XXX This is proably not correct for some printers?\n        zrange = th.get_kinematics().rails[2].get_range()\n        th_pos[2] = zrange[1] - 20.0\n        self._set_toolhead_position(th_pos, [2])\n\n        manual_probe.ManualProbeHelper(\n            self._printer,\n            gcmd,\n            lambda kin_pos: self.cmd_CALIBRATE_next(gcmd, kin_pos),\n        )\n\n    def cmd_CALIBRATE_next(self, gcmd: GCodeCommand, kin_pos: Optional[List[float]]):\n        th = self._printer.lookup_object(\"toolhead\")\n        if kin_pos is None:\n            # User cancelled ManualProbeHelper\n            self._z_not_homed()\n            return\n\n        old_drive_current = self.current_drive_current()\n        drive_current: int = gcmd.get_int(\"DRIVE_CURRENT\", old_drive_current, minval=0, maxval=31)\n        cal_z_max: float = gcmd.get_float(\"START_Z\", self.params.calibration_z_max, above=2.0)\n        z_target: float = gcmd.get_float(\"TARGET_Z\", 0.0)\n\n        probe_speed: float = gcmd.get_float(\"SPEED\", self.params.probe_speed, above=0.0)\n        lift_speed: float = gcmd.get_float(\"LIFT_SPEED\", self.params.lift_speed, above=0.0)\n\n        # We just did a ManualProbeHelper, so we're going to zero the z-axis\n        # to make the following code easier, so it can assume z=0 is actually real zero.\n        # The Eddy sensor calibration is done to nozzle height (not sensor or trigger height).\n        th_pos = th.get_position()\n        th_pos[2] = 0.0\n        self._set_toolhead_position(th_pos, [2])\n\n        th.wait_moves()\n\n        self._log_debug(f\"calibrating from {kin_pos}, {th_pos}\")\n\n        # lift up above cal_z_max, and then move over so the probe\n        # is over the nozzle position\n        th.manual_move([None, None, cal_z_max + 3.0], lift_speed)\n        th.manual_move(\n            [\n                th_pos[0] - self.offset[\"x\"],\n                th_pos[1] - self.offset[\"y\"],\n                None,\n            ],\n            self.params.move_speed,\n        )\n\n        mapping, fth_fit, htf_fit = self._create_mapping(\n            cal_z_max,\n            z_target,\n            probe_speed,\n            lift_speed,\n            drive_current,\n            report_errors=True,\n            write_debug_files=True,\n        )\n        if mapping is None or fth_fit is None or htf_fit is None:\n            self._log_error(\"Calibration failed\")\n            return\n\n        self._dc_to_fmap[drive_current] = mapping\n        self.save_config()\n\n        # reset the Z homing state after alibration\n        self._z_not_homed()\n\n    def _create_mapping(\n        self,\n        z_start: float,\n        z_target: float,\n        probe_speed: float,\n        lift_speed: float,\n        drive_current: int,\n        report_errors: bool,\n        write_debug_files: bool,\n    ) -> Tuple[ProbeEddyFrequencyMap, float, float]:\n        th = self._printer.lookup_object(\"toolhead\")\n        th_pos = th.get_position()\n\n        # move to the start z of the mapping, going up first if we need to for backlash\n        if th_pos[2] < z_start:\n            th.manual_move([None, None, z_start + 3.0], lift_speed)\n        th.manual_move([None, None, z_start], lift_speed)\n\n        old_drive_current = self.current_drive_current()\n        try:\n            self._sensor.set_drive_current(drive_current)\n            times, freqs, heights, vels = self._capture_samples_down_to(z_target, probe_speed)\n            th.manual_move([None, None, z_start + 3.0], lift_speed)\n        finally:\n            self._sensor.set_drive_current(old_drive_current)\n\n        if times is None:\n            if report_errors:\n                self._log_error(f\"Drive current {drive_current}: No samples collected. This could be a hardware issue or an incorrect drive current.\")\n            else:\n                self._log_warning(f\"Drive current {drive_current}: Warning: no samples collected.\")\n            return None, None, None\n\n        # and build a map\n        mapping = ProbeEddyFrequencyMap(self)\n        fth_fit, htf_fit = mapping.calibrate_from_values(\n            drive_current,\n            times,\n            freqs,\n            heights,\n            vels,\n            report_errors,\n            write_debug_files,\n        )\n\n        return mapping, fth_fit, htf_fit\n\n    def _capture_samples_down_to(self, z_target: float, probe_speed: float) -> tuple[List[float], List[float], List[float], List[float]]:\n        th = self._printer.lookup_object(\"toolhead\")\n        th.dwell(0.500)  # give the sensor a bit to settle\n        th.wait_moves()\n\n        with self.start_sampler(calculate_heights=False) as sampler:\n            first_sample_time = th.get_last_move_time()\n            th.manual_move([None, None, z_target], probe_speed)\n            last_sample_time = th.get_last_move_time()\n            # Can't use wait_for_sample_at_time here, because the tail end of\n            # samples might be errors so they won't be passed to the sampler.\n            # Should fix that, but for now just wait an extra half second which\n            # should be more than enough.\n            # sampler.wait_for_sample_at_time(last_sample_time)\n            th.dwell(0.500)\n            th.wait_moves()\n            sampler.finish()\n\n        # the samples are a list of [print_time, freq, dummy_height] tuples\n        if sampler.raw_count == 0:\n            return None, None, None, None\n\n        freqs = []\n        heights = []\n        times = []\n        vels = []\n\n        for i in range(sampler.raw_count):\n            s_t = sampler.times[i]\n            s_freq = sampler.freqs[i]\n            s_pos, s_v = self._get_trapq_position(s_t)\n            s_z = s_pos[2]\n            if first_sample_time < s_t < last_sample_time and s_z >= z_target:\n                times.append(s_t)\n                freqs.append(s_freq)\n                heights.append(s_z)\n                vels.append(s_v)\n\n        return times, freqs, heights, vels\n\n    def cmd_TEST_DRIVE_CURRENT(self, gcmd: GCodeCommand):\n        drive_current: int = gcmd.get_int(\"DRIVE_CURRENT\", self._reg_drive_current, minval=1, maxval=31)\n        z_start: float = gcmd.get_float(\"START_Z\", self.params.calibration_z_max, above=2.0)\n        z_end: float = gcmd.get_float(\"TARGET_Z\", 0.0)\n        debug: bool = gcmd.get_int(\"DEBUG\", 0) == 1\n        self._log_msg(f\"Testing Z={z_start:.3f} to Z={z_end:.3f}\")\n\n        mapping, fth, htf = self._create_mapping(\n            z_start,\n            z_end,\n            self.params.probe_speed,\n            self.params.lift_speed,\n            drive_current,\n            report_errors=False,\n            write_debug_files=debug,\n        )\n        if mapping is None or fth is None or htf is None:\n            self._log_error(f\"Test failed: drive current {drive_current} is not usable.\")\n\n    #\n    # PrinterProbe interface\n    #\n\n    def get_offsets(self, *args, **kwargs):\n        # the z offset is the trigger height, because the probe will trigger\n        # at z=trigger_height (not at z=0)\n        return (\n            self.offset[\"x\"],\n            self.offset[\"y\"],\n            self.params.home_trigger_height,\n        )\n\n    def get_probe_params(self, gcmd=None):\n        return {\n            \"probe_speed\": self.params.probe_speed,\n            \"lift_speed\": self.params.lift_speed,\n            \"sample_retract_dist\": 0.0,\n        }\n\n    def start_probe_session(self, gcmd):\n        session = ProbeEddyScanningProbe(self, gcmd)\n        session._start_session()\n        return session\n        # method = gcmd.get('METHOD', 'automatic').lower()\n        # if method in ('scan', 'rapid_scan'):\n        #    session = ProbeEddyScanningProbe(self, gcmd)\n        #    session._start_session()\n        #    return session\n        #\n        # return self._probe_session.start_probe_session(gcmd)\n\n    def get_status(self, eventtime):\n        if self._cmd_helper is not None:\n            status = self._cmd_helper.get_status(eventtime)\n        else:\n            status = dict()\n        status.update(\n            {\n                \"name\": self._full_name,\n                \"home_trigger_height\": float(self.params.home_trigger_height),\n                \"tap_offset\": float(self._tap_offset),\n                \"tap_adjust_z\": float(self._tap_adjust_z),\n                \"last_probe_result\": float(self._last_probe_result),\n                \"last_tap_z\": float(self._last_tap_z),\n            }\n        )\n        return status\n\n    # Old Probe interface, for Kalico\n\n    def get_lift_speed(self, gcmd=None):\n        if gcmd is not None:\n            return gcmd.get_float(\"LIFT_SPEED\", self.params.lift_speed, above=0.0)\n        return self.params.lift_speed\n\n    def multi_probe_begin(self):\n        pass\n\n    def multi_probe_end(self):\n        pass\n\n    # This is a mishmash of cmd_PROBE and cmd_PROBE_STATIC. This run_probe\n    # is the old one, different than the scanning session run_probe.\n    def run_probe(self, gcmd=None, *args: Any, **kwargs: Any):\n        z = self.params.home_trigger_height\n        duration = 0.100\n\n        if not self._z_homed():\n            raise self._printer.command_error(\"Must home Z before PROBE\")\n\n        if not self.calibrated():\n            raise self._printer.command_error(\"Eddy probe not calibrated!\")\n\n        th = self._printer.lookup_object(\"toolhead\")\n        th_pos = th.get_position()\n        if th_pos[2] < z:\n            th.manual_move([None, None, z + 3.0], self.params.lift_speed)\n        th.manual_move([None, None, z], self.params.lift_speed)\n        th.dwell(0.100)\n        th.wait_moves()\n\n        r = self.probe_static_height(duration)\n        if not r.valid:\n            raise self._printer.command_error(\"Probe captured no samples!\")\n\n        height = r.value\n        height += self._tap_offset\n\n        # At what Z position would the toolhead be at for the probe to read\n        # _home_trigger_height? In other words, if the probe tells us\n        # the height is 1.5 when the toolhead is at z=2.0, if the toolhead\n        # was moved up to 2.5, then the probe should read 2.0.\n        probe_z = z + (z - height)\n\n        return [th_pos[0], th_pos[1], probe_z]\n\n    #\n    # Moving the sensor to the correct position\n    #\n    def _probe_to_start_position_unhomed(self, move_home=False):\n        if not self._xy_homed():\n            raise self._printer.command_error(\"xy must be homed\")\n        if not self.sampler_is_active():\n            raise self._printer.command_error(\"probe_to_start_position_unhomed: no sampler active\")\n        if not self.calibrated():\n            raise self._printer.command_error(\"EDDYng not calibrated!\")\n\n        th = self._printer.lookup_object(\"toolhead\")\n        th_pos = th.get_position()\n\n        # debug logging\n        th_kin = th.get_kinematics()\n        zlim = th_kin.limits[2]\n        rail_range = th_kin.rails[2].get_range()\n        self._log_debug(\n            f\"probe to start unhomed: before movement: Z pos {th_pos[2]:.3f}, \"\n            f\"Z limits {zlim[0]:.2f}-{zlim[1]:.2f}, \"\n            f\"rail range {rail_range[0]:.2f}-{rail_range[1]:.2f}\"\n        )\n\n        start_height_ok_factor = 0.100\n\n        # This is where we want to get to\n        start_height = self._home_start_height\n        # This is where the probe thinks we are\n        now_height = self._sampler.get_height_now()\n\n        # If we can't get a value at all for right now, for safety, just abort.\n        if now_height is None:\n            raise self._printer.command_error(\"Couldn't get any valid samples from sensor.\")\n\n        self._log_debug(f\"probe_to_start_position_unhomed: now: {now_height} (start {start_height})\")\n        if abs(now_height - start_height) <= start_height_ok_factor:\n            return\n\n        th = self._printer.lookup_object(\"toolhead\")\n        th_pos = th.get_position()\n\n        # If the sensor thinks we're too low we need to move back up before homing\n        if now_height < start_height:\n            move_up_by = min(start_height, start_height - now_height)\n            # give ourselves some room to do so, homing typically doesn't move up,\n            # and we should know that we have this room because the sensor tells us we're too low\n            th_pos[2] = rail_range[1] - (move_up_by + 10.0)\n            self._log_debug(f\"probe_to_start_position_unhomed: resetting toolhead to z {th_pos[2]:.3f}\")\n            self._set_toolhead_position(th_pos, [2])\n\n            n_pos = th.get_position()\n\n            zlim = th_kin.limits[2]\n            rail_range = th_kin.rails[2].get_range()\n            self._log_debug(\n                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}\"\n            )\n\n            th_pos[2] += move_up_by\n            self._log_debug(f\"probe_to_start_position_unhomed: moving toolhead up by {move_up_by:.3f} to {th_pos[2]:.3f}\")\n            th.manual_move([None, None, th_pos[2]], self.params.probe_speed)\n            # TODO: this should just be th.wait_moves()\n            self._sampler.wait_for_sample_at_time(th.get_last_move_time())\n\n    def probe_to_start_position(self, z_pos=None):\n        self._log_debug(f\"probe_to_start_position (tt: {self.params.tap_threshold}, z-homed: {self._z_homed()})\")\n\n        # If we're not homed at all, rely on the sensor values to bring us to\n        # a good place to start a diving probe from\n        if not self._z_homed():\n            if z_pos is not None:\n                raise self._printer.command_error(\"Can't probe_to_start_position with an explicit Z without homed Z\")\n            self._probe_to_start_position_unhomed()\n            return\n\n        th = self._printer.lookup_object(\"toolhead\")\n        th.wait_moves()\n        th_pos = th.get_position()\n\n        # Note home_trigger_height and not home_start_height: if we're homed,\n        # we don't need to do another dive and we just want to move to\n        # the right position for probing.\n        if z_pos is not None:\n            start_z = z_pos\n        else:\n            start_z = self.params.home_trigger_height\n\n        # If we're below, move up a bit beyond and the back down\n        # to compensate for backlash\n        if th_pos[2] < start_z:\n            self._log_debug(f\"probe_to_start_position: moving toolhead from {th_pos[2]:.3f} to {(start_z + 1.0):.3f}\")\n            th_pos[2] = start_z + 1.0\n            th.manual_move(th_pos, self.params.lift_speed)\n\n        self._log_debug(f\"probe_to_start_position: moving toolhead from {th_pos[2]:.3f} to {start_z:.3f}\")\n        th_pos[2] = start_z\n        th.manual_move(th_pos, self.params.probe_speed)\n\n        th.wait_moves()\n\n    #\n    # Tap probe\n    #\n    cmd_TAP_help = \"Calculate a z-offset by touching the build plate.\"\n\n    def cmd_TAP(self, gcmd: GCodeCommand):\n        drive_current = self._sensor.get_drive_current()\n        try:\n            self.cmd_TAP_next(gcmd)\n        finally:\n            self._sensor.set_drive_current(drive_current)\n\n    @dataclass\n    class TapResult:\n        error: Optional[Exception]\n        probe_z: float\n        toolhead_z: float\n        overshoot: float\n        tap_time: float\n        tap_start_time: float\n        tap_end_time: float\n\n    @dataclass\n    class TapConfig:\n        mode: str\n        threshold: float\n        sos: Optional[List[List[float]]] = None\n\n    def do_one_tap(\n        self,\n        start_z: float,\n        target_z: float,\n        tap_speed: float,\n        lift_speed: float,\n        tapcfg: ProbeEddy.TapConfig,\n    ) -> TapResult:\n        self.probe_to_start_position(start_z)\n\n        th = self._printer.lookup_object(\"toolhead\")\n\n        target_position = th.get_position()\n        target_position[2] = target_z\n\n        error = None\n\n        try:\n            # configure the endstop for tap (gets reset at the end of a tap sequence,\n            # also in finally just in case\n            self._endstop_wrapper.tap_config = tapcfg\n\n            endstops = [(self._endstop_wrapper, \"probe\")]\n            hmove = HomingMove(self._printer, endstops)\n\n            try:\n                probe_position = hmove.homing_move(target_position, tap_speed, probe_pos=True)\n\n                # raise toolhead as soon as tap ends\n                finish_z = th.get_position()[2]\n                if finish_z < 1.0:\n                    th.manual_move([None, None, start_z], lift_speed)\n\n                if hmove.check_no_movement() is not None:\n                    raise self._printer.command_error(\"Probe triggered prior to movement\")\n\n                probe_z = probe_position[2]\n\n                self._log_debug(f\"tap: probe_z: {probe_z:.3f} finish_z: {finish_z:.3f} moved up to {start_z:.3f}\")\n\n                if probe_z - target_z < 0.050:\n                    # we detected a tap but it was too close to our target z\n                    # to be trusted\n                    # TODO: use velocity to determine this\n                    return ProbeEddy.TapResult(\n                        error=Exception(\"Tap detected too close to target z\"),\n                        toolhead_z=finish_z,\n                        probe_z=probe_z,\n                        overshoot=0.0,\n                        tap_time=0.0,\n                        tap_start_time=0.0,\n                        tap_end_time=0.0,\n                    )\n\n            except self._printer.command_error as err:\n                if self._printer.is_shutdown():\n                    raise self._printer.command_error(\"Probing failed due to printer shutdown\")\n\n                # in case of failure don't leave the toolhead in a bad spot (i.e. in bed)\n                finish_z = th.get_position()[2]\n                if finish_z < 1.0:\n                    th.manual_move([None, None, start_z], lift_speed)\n\n                # If just sensor errors, let the caller handle it\n                self._log_error(f\"Tap failed with Z at {finish_z:.3f}: {err}\")\n                if \"Sensor error\" or \"Probe completed movement\" or \"Probe triggered prior\" in str(err):\n                    return ProbeEddy.TapResult(\n                        error=err,\n                        toolhead_z=finish_z,\n                        probe_z=0.0,\n                        overshoot=0.0,\n                        tap_time=0.0,\n                        tap_start_time=0.0,\n                        tap_end_time=0.0,\n                    )\n                else:\n                    raise\n        finally:\n            self._endstop_wrapper.tap_config = None\n\n        # The toolhead ended at finish_z, but probe_z is the actual zero.\n        # finish_z should be below or equal to probe_z because there will always be\n        # a bit of overshoot due to trigger delay, and because we actually\n        # fire the trigger later than when the tap starts (and the tap start\n        # time is what's used to compute probe_position)\n        if finish_z > probe_z:\n            raise self._printer.command_error(f\"Unexpected: finish_z {finish_z:.3f} is above probe_z {probe_z:.3f} after tap\")\n\n        # How much the toolhead overshot the real z=0 position. This is the amount\n        # the toolhead is pushing into the build plate.\n        overshoot = probe_z - finish_z\n\n        tap_start_time = self._endstop_wrapper.last_tap_start_time\n        tap_end_time = self._endstop_wrapper.last_trigger_time\n        tap_time = tap_start_time + (tap_end_time - tap_start_time) * self.params.tap_time_position\n\n        return ProbeEddy.TapResult(\n            error=error,\n            probe_z=probe_z,\n            toolhead_z=finish_z,\n            overshoot=overshoot,\n            tap_time=tap_time,\n            tap_start_time=tap_start_time,\n            tap_end_time=tap_end_time,\n        )\n\n    def _compute_butter_tap(self, sampler):\n        if not scipy:\n            return None, None\n\n        trigger_freq = self.height_to_freq(self.params.home_trigger_height)\n\n        s_f = np.asarray(sampler.freqs)\n        first_one = np.argmax(s_f >= trigger_freq)\n        s_t = np.asarray(sampler.times[first_one:])\n        s_f = np.asarray(sampler.freqs[first_one:])\n\n        lowcut = self.params.tap_butter_lowcut\n        highcut = self.params.tap_butter_highcut\n        order = self.params.tap_butter_order\n\n        sos = scipy.signal.butter(\n            order,\n            [lowcut, highcut],\n            btype=\"bandpass\",\n            fs=self._sensor._data_rate,\n            output=\"sos\",\n        )\n        filtered = scipy.signal.sosfilt(sos, s_f - s_f[0])\n\n        return s_t, filtered\n\n    def cmd_TAP_next(self, gcmd: Optional[GCodeCommand] = None):\n        self._log_debug(\"\\nEDDYng Tap begin\")\n\n        if gcmd is None:\n            gcmd = self._dummy_gcode_cmd\n\n        orig_drive_current: int = self._sensor.get_drive_current()\n        tap_drive_current: int = gcmd.get_int(\n            name=\"DRIVE_CURRENT\",\n            default=self._tap_drive_current,\n            minval=1,\n            maxval=31,\n        )\n        tap_speed: float = gcmd.get_float(\"SPEED\", self.params.tap_speed, above=0.0)\n        lift_speed: float = gcmd.get_float(\"RETRACT_SPEED\", self.params.lift_speed, above=0.0)\n        tap_start_z: float = gcmd.get_float(\"START_Z\", self.params.tap_start_z, above=2.0)\n        target_z: float = gcmd.get_float(\"TARGET_Z\", self.params.tap_target_z)\n        tap_threshold: float = gcmd.get_float(\"THRESHOLD\", None)  # None so we have a sentinel value\n        tap_threshold = gcmd.get_float(\"TT\", tap_threshold)  # alias for THRESHOLD\n        tap_adjust_z = gcmd.get_float(\"ADJUST_Z\", self._tap_adjust_z)\n        do_retract = gcmd.get_int(\"RETRACT\", 1) == 1\n        samples = gcmd.get_int(\"SAMPLES\", self.params.tap_samples, minval=1)\n        max_samples = gcmd.get_int(\"MAX_SAMPLES\", self.params.tap_max_samples, minval=samples)\n        samples_stddev = gcmd.get_float(\"SAMPLES_STDDEV\", self.params.tap_samples_stddev, above=0.0)\n        use_median: bool = gcmd.get_int(\"USE_MEDIAN\", 1 if self.params.tap_use_median else 0) == 1\n        home_z: bool = gcmd.get_int(\"HOME_Z\", 1) == 1\n        write_plot_arg: int = gcmd.get_int(\"PLOT\", None)\n\n        mode = gcmd.get(\"MODE\", self.params.tap_mode).lower()\n        if mode not in (\"wma\", \"butter\"):\n            raise self._printer.command_error(f\"Invalid mode: {mode}\")\n\n        # if the mode is different than the params, then require\n        # specifying threshold\n        if tap_threshold is None:\n            if mode != self.params.tap_mode:\n                raise self._printer.command_error(\n                    f\"THRESHOLD required when mode ({mode}) is different than configured default ({self.params.tap_mode})\"\n                )\n            tap_threshold = self.params.tap_threshold\n\n        if not self._z_homed():\n            raise self._printer.command_error(\"Z axis must be homed before tapping\")\n\n        write_tap_plot = self.params.write_tap_plot\n        write_every_tap_plot = self.params.write_every_tap_plot and write_tap_plot\n        if write_plot_arg is not None:\n            write_tap_plot = write_plot_arg > 0\n            write_every_tap_plot = write_plot_arg > 1\n\n        tapcfg = ProbeEddy.TapConfig(mode=mode, threshold=tap_threshold)\n        # fmt: off\n        if mode == \"butter\":\n            if self.params.is_default_butter_config() and self._sensor._data_rate == 250:\n                sos = [\n                    [ 0.046131802093312926, 0.09226360418662585, 0.046131802093312926, 1.0, -1.3297767184682712, 0.5693902189294331, ],\n                    [ 1.0, -2.0, 1.0, 1.0, -1.845000600983779, 0.8637525213328747, ],\n                ]\n            elif self.params.is_default_butter_config() and self._sensor._data_rate == 500:\n                sos = [\n                    [ 0.013359200027856505, 0.02671840005571301, 0.013359200027856505, 1.0, -1.686278256753083, 0.753714473246724, ],\n                    [ 1.0, -2.0, 1.0, 1.0, -1.9250515947328444, 0.9299234737648037, ],\n                ]\n            elif scipy:\n                sos = scipy.signal.butter(\n                    self.params.tap_butter_order,\n                    [ self.params.tap_butter_lowcut, self.params.tap_butter_highcut, ],\n                    btype=\"bandpass\",\n                    fs=self._sensor._data_rate,\n                    output=\"sos\",\n                ).tolist()\n            else:\n                raise self._printer.command_error(\"Scipy is not available, cannot use custom filter, or data rate is not 250 or 500\")\n            tapcfg.sos = sos\n        # fmt: on\n\n        results = []\n        tap_z = None\n        tap_stddev = None\n        tap_overshoot = None\n        sample_err_count = 0\n        tap = None\n\n        try:\n            self._sensor.set_drive_current(tap_drive_current)\n\n            sample_last_err = None\n\n            for sample_i in range(max_samples):\n                if self.params.debug:\n                    self.save_samples_path = f\"/tmp/tap-samples-{sample_i+1}.csv\"\n\n                tap = self.do_one_tap(\n                    start_z=tap_start_z,\n                    target_z=target_z,\n                    tap_speed=tap_speed,\n                    lift_speed=lift_speed,\n                    tapcfg=tapcfg,\n                )\n\n                if write_every_tap_plot:\n                    try:\n                        self._write_tap_plot(tap, sample_i)\n                    except Exception as e:\n                        self._log_error(f\"Failed to write tap plot: {e}\")\n\n                if tap.error:\n                    if \"too close to target z\" in str(tap.error):\n                        self._log_msg(f\"Tap {sample_i+1}: failed: try lowering TARGET_Z by 0.100 (to {target_z - 0.100:.3f})\")\n                    else:\n                        self._log_msg(f\"Tap {sample_i+1}: failed ({tap.error})\")\n                    sample_err_count += 1\n                    sample_last_err = tap\n                    continue\n\n                results.append(tap)\n\n                self._log_msg(f\"Tap {sample_i+1}: z={tap.probe_z:.3f}\")\n                self._log_debug(\n                    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\"\n                )\n\n                if samples == 1:\n                    # only one sample, we're done\n                    tap_z = tap.probe_z\n                    tap_stddev = 0.0\n                    tap_overshoot = tap.overshoot\n                    break\n\n                if len(results) >= samples:\n                    tap_z, tap_stddev, tap_overshoot = self._compute_tap_z(results, samples, samples_stddev, use_median)\n                    if tap_z is not None:\n                        break\n        finally:\n            self.reset_drive_current()\n            if write_tap_plot and not write_every_tap_plot and tap:\n                try:\n                    self._write_tap_plot(tap)\n                except Exception as e:\n                    self._log_error(f\"Failed to write tap plot: {e}\")\n\n        th = self._toolhead\n\n        # If we didn't compute a tap_z report the error\n        if tap_z is None:\n            # raise toolhead on failed tap\n            th.manual_move([None, None, tap_start_z], lift_speed)\n            err_msg = \"Tap failed:\"\n            if tap_stddev is not None:\n                err_msg += f\" stddev {tap_stddev:.3f} > {samples_stddev:.3f}.\"\n                err_msg += \" Consider adjusting tap_samples, tap_max_samples, or tap_samples_stddev.\"\n            if sample_err_count > 0:\n                err_msg += f\" {sample_err_count} errors, last: {sample_last_err.error} at toolhead z={sample_last_err.toolhead_z:.3f}\"\n            self._log_error(err_msg)\n            raise self._printer.command_error(\"Tap failed\")\n\n        # Adjust the computed tap_z by the user's tap_adjust_z, typically to raise\n        # it to account for flex in the system (otherwise the Z would be too low)\n        computed_tap_z = adjusted_tap_z = tap_z + tap_adjust_z\n        self._last_tap_z = float(tap_z)\n\n        homed_to_str = \"\"\n        if home_z:\n            th_pos = th.get_position()\n            th_z = th_pos[2]\n            #true_z_zero = - (tap_adjust_z + tap_overshoot)\n            true_z_zero = - computed_tap_z\n            th_pos[2] = th_pos[2] + true_z_zero\n            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}, \"\n            self._set_toolhead_position(th_pos, [2])\n            self._last_tap_gcode_adjustment = 0.0\n            adjusted_tap_z = 0.0\n\n        gcode_move = self._printer.lookup_object(\"gcode_move\")\n        gcode_delta = adjusted_tap_z - gcode_move.homing_position[2]\n        gcode_move.base_position[2] += gcode_delta\n        gcode_move.homing_position[2] = adjusted_tap_z\n        self._last_tap_gcode_adjustment = adjusted_tap_z\n\n        #\n        # Figure out the offset to apply to sensor readings at the home trigger height\n        # for future probes.\n        #\n        # This is actually unrelated to tap, but is related to temperature compensation.\n        # Bed mesh is going to read values relative to the probe's z_offset (home_trigger_height).\n        # But we can't trust the probe's values directly, because of temperature effects.\n        #\n        # What we can do though is move the toolhead to that height, take a probe reading,\n        # then save the delta there to apply as an offset for bed mesh in the future.\n        # That makes this bed height effectively \"0\", which is fine, because this is\n        # what we did tap at to get a height zero reading.\n        #\n        # Toolhead moves are absolute; they don't take into account the gcode offset.\n        # Probes happen at absolute z=z_offset, so this doesn't take into account the\n        # tap_z computed above. This does mean that the actual physical height probing happens at\n        # is not likely to be exactly the same as the Z position, but all we care about is\n        # variance from that position so this should be fine.\n        self._sensor.set_drive_current(orig_drive_current)\n        th_now = th.get_position()\n        th.manual_move([None, None, self.params.home_trigger_height + 1.0], lift_speed)\n        th.manual_move([th_now[0] - self.params.x_offset, th_now[1] - self.params.y_offset, None], self.params.move_speed)\n        th.manual_move([None, None, self.params.home_trigger_height], self.params.probe_speed)\n        th.dwell(0.500)\n        th.wait_moves()\n\n        result = self.probe_static_height()\n        self._tap_offset = float(self.params.home_trigger_height - result.value)\n\n        self._log_msg(\n            f\"Probe computed tap at {computed_tap_z:.3f} (tap at z={tap_z:.3f}, \"\n            f\"stddev {tap_stddev:.3f}) with {samples} samples, {homed_to_str}\"\n            f\"sensor offset {self._tap_offset:.3f} at z={self.params.home_trigger_height:.3f}\"\n        )\n\n        if do_retract:\n            th.manual_move([None, None, self._home_start_height], lift_speed)\n            th.wait_moves()\n            th.flush_step_generation()\n\n        self._log_debug(\"EDDYng Tap end\\n\")\n\n    # Compute the average tap_z from a set of tap results, taking a cluster of samples\n    # from the result that has the lowest standard deviation\n    def _compute_tap_z(self, taps: List[ProbeEddy.TapResult], samples: int, req_stddev: float, use_median: bool) -> Tuple[float, float, float]:\n        if len(taps) < samples:\n            return None, None, None\n\n        tap_z = math.inf\n        std_min = math.inf\n        overshoot = math.inf\n        for cluster in combinations(taps, samples):\n            tap_zs = np.array([t.probe_z for t in cluster])\n            overshoots = np.array([t.overshoot for t in cluster])\n            std = np.std(tap_zs)\n            if std < std_min:\n                std_min = std\n                if use_median:\n                    # we need the corresponding overshoot as well, so\n                    # can't just use np.median().\n                    sorted_indices = np.argsort(tap_zs)\n                    idx = len(tap_zs) // 2\n                    tap_z = tap_zs[sorted_indices[idx]]\n                    overshoot = overshoots[sorted_indices[idx]]\n                else:\n                    tap_z = np.mean(tap_zs)\n                    overshoot = np.mean(overshoots)\n\n        if std_min <= req_stddev:\n            return float(tap_z), float(std_min), float(overshoot)\n        else:\n            return None, float(std_min), None\n\n    # Write a tap plot. This also has logic to compute the averages\n    # and the filter mostly-exactly how it's done on the probe MCU itself\n    # (vs using numpy or similar) to make these graphs more reprensetative\n    def _write_tap_plot(self, tap: ProbeEddy.TapResult, tapnum: int = -1):\n        if not plotly:\n            return\n\n        if tapnum == -1:\n            filename_base = \"tap\"\n        else:\n            filename_base = f\"tap-{tapnum+1}\"\n        tapplot_path_png = f\"/tmp/{filename_base}.png\"\n        tapplot_path_html = f\"/tmp/{filename_base}.html\"\n\n        # delete any old plots to avoid confusion\n        if tapplot_path_html and os.path.exists(tapplot_path_html):\n            os.remove(tapplot_path_html)\n        if tapplot_path_png and os.path.exists(tapplot_path_png):\n            os.remove(tapplot_path_png)\n\n        if not self._last_sampler or not self._last_sampler.times:\n            return\n\n        s_t = np.asarray(self._last_sampler.times)\n        s_f = np.asarray(self._last_sampler.freqs)\n        s_z = np.asarray(self._last_sampler.heights)\n        s_kinz = np.vectorize(lambda t: self._get_trapq_height(t) or -10)(s_t)\n\n        # Any values below 0.0 are suspect because they were not calibrated,\n        # and so are just extrapolated from the fit. Show them differently.\n        s_lowz = np.ma.masked_where(s_z >= 0, s_z)\n        s_z = np.ma.masked_where(s_z < 0, s_z)\n\n        time_start = s_t.min()\n\n        # normalize times to start at 0\n        s_t = s_t - time_start\n        tap_start_time = self._last_sampler.memos.get(\"tap_start_time\", time_start) - time_start\n        tap_end_time = self._last_sampler.memos.get(\"trigger_time\", time_start) - time_start\n        trigger_time = tap_start_time + (tap_end_time - tap_start_time) * self.params.tap_time_position\n        tap_threshold = self._last_sampler.memos.get(\"tap_threshold\", 0)\n\n        time_len = s_t.max()\n\n        # compute the butterworth filter, if we have scipy\n        if tap is not None and scipy:\n            butter_s_t, butter_s_v = self._compute_butter_tap(self._last_sampler)\n            butter_s_t = butter_s_t - time_start\n        else:\n            butter_s_t = butter_s_v = None\n\n        # Do this roughly how the C code does it, to keep the values identical\n        # TODO Just report the value from the mcu?\n        butter_accum = None\n        if butter_s_v is not None:\n            # Note: we don't handle freq offset or\n            # start this at same point as the C code does\n            butter_accum = np.zeros(len(butter_s_v))\n            last_value = butter_s_v[0]\n            falling = False\n            accum_val = 0.0\n            for bi, bv in enumerate(butter_s_v):\n                if bv <= last_value:\n                    falling = True\n                    accum_val += last_value - bv\n                elif falling and bv > last_value:\n                    falling = False\n                    accum_val = 0.0\n                butter_accum[bi] = accum_val\n                last_value = bv\n\n        import plotly.graph_objects as go\n\n        (c_red, c_lt_red) = ('#9e4058', '#C2697F')\n        (c_orange, c_lt_orange) = ('#d0641e', '#E68E54')\n        (c_yellow, c_lt_yellow) = ('#f9ab0e', '\"#FBC559')\n        (c_green, c_lt_green) = ('#589e40', '#7FC269')\n        (c_blue, c_lt_blue) = ('#2c3778', '#4151B0')\n        (c_purple, c_lt_purple) = ('#513965', '#785596')\n\n        fig = go.Figure()\n\n        # fmt: off\n        if tap_start_time > 0:\n            fig.add_shape(type=\"line\", x0=tap_start_time, x1=tap_start_time, y0=0, y1=1,\n                          xref=\"x\", yref=\"paper\", line=dict(color=c_purple, width=2),)\n        if trigger_time > 0:\n            fig.add_shape(type=\"line\", x0=trigger_time, x1=trigger_time, y0=0, y1=1,\n                          xref=\"x\", yref=\"paper\", line=dict(color=c_lt_orange, width=2),)\n        if tap_end_time > 0:\n            fig.add_shape(type=\"line\", x0=tap_end_time, x1=tap_end_time, y0=0, y1=1,\n                          xref=\"x\", yref=\"paper\", line=dict(color=c_purple, width=2),)\n        if tap_threshold > 0:\n            fig.add_shape(type=\"line\", x0=0, x1=1, y0=tap_threshold, y1=tap_threshold,\n                          xref=\"paper\", yref=\"y3\", line=dict(color=\"gray\", width=1, dash=\"dash\"),)\n\n        fig.add_shape(type=\"line\", x0=0, x1=1, y0=tap.probe_z, y1=tap.probe_z,\n                      xref=\"paper\", yref=\"y\", line=dict(color=c_lt_orange, width=1),)\n\n        # Computed Z, Toolhead Z, Sensor F\n        fig.add_trace(go.Scatter(x=s_t, y=s_z, mode=\"lines\", name=\"Z\", line=dict(color=c_blue)))\n        fig.add_trace(go.Scatter(x=s_t, y=s_lowz, mode=\"lines\", name=\"Z (low)\", line=dict(color=c_lt_blue, dash=\"dash\")))\n        fig.add_trace(go.Scatter(x=s_t, y=s_kinz, mode=\"lines\", name=\"KinZ\", line=dict(color=c_lt_red)))\n        fig.add_trace(go.Scatter(x=s_t, y=s_f, mode=\"lines\", name=\"Freq\", yaxis=\"y2\", line=dict(color=c_orange)))\n\n        # the butter tap if we have the data\n        if butter_s_t is not None:\n            fig.add_trace(go.Scatter(x=butter_s_t, y=butter_s_v, mode=\"lines\", name=\"signal\", yaxis=\"y4\", line=dict(color=c_green)))\n            fig.add_trace(go.Scatter(x=butter_s_t, y=butter_accum, mode=\"lines\", name=\"threshold\", yaxis=\"y3\", line=dict(color=\"#626b73\")))\n\n        fig.update_xaxes(range=[max(0.0, time_len - 0.60), time_len], autorange=False)\n\n        fig.update_layout(\n            hovermode=\"x unified\",\n            title=dict(text=f\"Tap {tapnum+1}: {tap.probe_z:.3f}\"),\n            yaxis=dict(title=\"Z\", side=\"right\"),  # Z axis\n            yaxis2=dict(overlaying=\"y\", title=\"Freq\", tickformat=\"d\", side=\"left\"),  # Freq + WMA\n            yaxis3=dict(overlaying=\"y\", side=\"left\", tickformat=\"d\", position=0.2),  # derivatives, tap accum\n            yaxis4=dict(overlaying=\"y\", side=\"right\", showticklabels=False),  # filter\n            height=800,\n        )\n        # fmt: on\n\n        timg = 0.0\n        thtml = 0.0\n        if tapplot_path_png:\n            t0 = time.time()\n            try:\n                fig.write_image(tapplot_path_png)\n            except:\n                tapplot_path_png = None\n            timg = time.time() - t0\n        if tapplot_path_html:\n            t0 = time.time()\n            fig.write_html(tapplot_path_html, include_plotlyjs=\"cdn\")\n            thtml = time.time() - t0\n        self._log_info(f\"Wrote tap plot to {tapplot_path_png or ''} {tapplot_path_html or ''}  [took {timg:.1f}, {thtml:.1f}]\")\n\n    def cmd_START_STREAM(self, gcmd):\n        self.save_samples_path = \"/tmp/stream.csv\"\n        self._log_info(\"Eddy sampling enabled\")\n        self.start_sampler()\n\n    def cmd_STOP_STREAM(self, gcmd):\n        self._log_info(\"Eddy sampling finished\")\n        self._sampler.finish()\n        self._sampler = None\n\n\n\n# Probe interface that does only scanning, no up/down movement.\n# It scans at whatever height the probe is, but returns values\n# as if the probing happened (i.e. relative to\n# z_offset/home_trigger_height).\n@final\nclass ProbeEddyScanningProbe:\n    def __init__(self, eddy: ProbeEddy, gcmd: GCodeCommand):\n        self.eddy = eddy\n        self._printer = eddy._printer\n        self._toolhead = self._printer.lookup_object(\"toolhead\")\n        self._toolhead_kin = self._toolhead.get_kinematics()\n\n        # we're going to scan at this height; pull_probed_results\n        # also expects to return values based on this height\n        self._scan_z = eddy.params.home_trigger_height\n\n        # sensor thinks is _home_trigger_height vs. what it actually is.\n        # For example, if we do a tap, adjust, and then we move the toolhead up\n        # to 2.0 but the sensor says 1.950, then this would be +0.050.\n        self._tap_offset = eddy._tap_offset\n\n        # how much to dwell at each sample position in addition to sample_time\n        self._sample_time_delay = self.eddy.params.scan_sample_time_delay\n        self._sample_time: float = gcmd.get_float(\"SAMPLE_TIME\", self.eddy.params.scan_sample_time, above=0.0)\n        self._is_rapid = gcmd.get(\"METHOD\", \"automatic\").lower() == \"rapid_scan\"\n\n        self._sampler: ProbeEddySampler = None\n\n        self._notes = []\n\n    def get_probe_params(self, gcmd):\n        # this seems to be all that external users of get_probe_params\n        # use (bed_mesh, axis_twist_compensation)\n        return {\n            \"lift_speed\": self.eddy.params.lift_speed,\n            \"probe_speed\": self.eddy.params.probe_speed,\n        }\n\n    def _start_session(self):\n        if not self.eddy._z_homed():\n            raise self._printer.command_error(\"Z axis must be homed before probing\")\n\n        self.eddy.probe_to_start_position()\n        self._sampler = self.eddy.start_sampler()\n\n    def end_probe_session(self):\n        self._sampler.finish()\n        self._sampler = None\n\n    def _rapid_lookahead_cb(self, time, th_pos):\n        # The time passed here is the time when the move finishes;\n        # but this is super obnoxious because we don't get any info\n        # here about _where_ the move is to. So we explicitly pass\n        # in the last position in run_probe\n        start_time = time - self._sample_time / 2.0\n        self._notes.append([start_time, time, th_pos])\n\n    def run_probe(self, gcmd, *args: Any, **kwargs: Any):\n        th = self._toolhead\n        th_pos = th.get_position()\n\n        if self._is_rapid:\n            # this callback is attached to the last move in the queue, so that\n            # we can grab the toolhead position when the toolhead actually hits it\n\n            self._toolhead.register_lookahead_callback(lambda time: self._rapid_lookahead_cb(time, th_pos))\n            return\n\n        th.dwell(self._sample_time_delay)\n        start_time = th.get_last_move_time()\n        self._toolhead.dwell(self._sample_time + self._sample_time_delay)\n        self._notes.append((start_time, start_time + self._sample_time / 2.0, th_pos))\n\n    def pull_probed_results(self):\n        if self._is_rapid:\n            # Flush lookahead (so all lookahead callbacks are invoked)\n            self._toolhead.get_last_move_time()\n\n        # make sure we get the sample for the final move\n        self._sampler.wait_for_sample_at_time(self._notes[-1][0] + self._sample_time)\n\n        # note: we can't call finish() here! this session can continue to be used\n        # to probe additional points and pull them, because that's what QGL does.\n\n        results = []\n\n        logging.info(f\"ProbeEddyScanningProbe: pulling {len(self._notes)} results\")\n        for start_time, sample_time, th_pos in self._notes:\n            if th_pos is None:\n                th_pos, _ = self.eddy._get_trapq_position(sample_time)\n                if th_pos is None:\n                    raise self._printer.command_error(f\"No trapq history found for {sample_time:.3f} and no position!\")\n\n            end_time = start_time + self._sample_time\n            height = self._sampler.find_height_at_time(start_time, end_time)\n\n            if not math.isclose(th_pos[2], self._scan_z, rel_tol=1e-3):\n                logging.info(\n                    f\"ProbeEddyScanningProbe warning: toolhead not at home_trigger_height ({self._scan_z:.3f}) during probes (saw {th_pos[2]:.3f})\"\n                )\n\n            h_orig = height\n            tz_orig = th_pos[2]\n\n            # adjust the sensor height value based on the fine-tuned tap offset amount\n            height += self._tap_offset\n\n            # the delta between where the toolhead thinks it should be (since it\n            # should be homed), and the actual physical offset (height)\n            z_deviation = th_pos[2] - height\n\n            # what callers want to know is \"what Z would the toolhead be at, if it was at the height\n            # the probe would 'trigger'\", because this is all done in terms of klicky-type probes\n            z = float(self._scan_z + z_deviation)\n\n            if HAS_PROBE_RESULT_TYPE:\n                bed_x = th_pos[0] + self.eddy.params.x_offset\n                bed_y = th_pos[1] + self.eddy.params.y_offset\n                res = manual_probe.ProbeResult(bed_x, bed_y, z_deviation,\n                                               th_pos[0], th_pos[1], th_pos[2])\n                result_wrapper = [res]\n                self._printer.send_event(\"probe:update_results\", result_wrapper)\n                res = result_wrapper[0]\n            else:\n                res = [th_pos[0], th_pos[1], z]\n                self._printer.send_event(\"probe:update_results\", res)\n\n            results.append(res)\n\n        # reset notes so that this session can continue to be used\n        self._notes = []\n\n        return results\n\n\n# This is a ProbeEndstopWrapper-compatible class,\n# which also forwards the \"mcu_probe\" methods.\n@final\nclass ProbeEddyEndstopWrapper:\n    REASON_BASE = mcu.MCU_trsync.REASON_COMMS_TIMEOUT + 1\n    REASON_ERROR_SENSOR = REASON_BASE + 0\n    REASON_ERROR_PROBE_TOO_LOW = REASON_BASE + 1\n    REASON_ERROR_TOO_EARLY = REASON_BASE + 2\n\n    def __init__(self, eddy: ProbeEddy):\n        self.eddy = eddy\n        self._sensor = eddy._sensor\n        self._printer = eddy._printer\n        self._mcu = eddy._mcu\n        self._reactor = eddy._reactor\n\n        # these two are filled in by the outside.\n        self.tap_config: Optional[ProbeEddy.TapConfig] = None\n        # if not None, after a probe session is finished we'll\n        # write all samples here\n        self.save_samples_path: Optional[str] = None\n\n        self._multi_probe_in_progress = False\n\n        self._dispatch = mcu.TriggerDispatch(self._mcu)\n\n        # the times of the last successful endstop home_wait\n        self.last_trigger_time = 0.0\n        self.last_tap_start_time = 0.0\n\n        self._homing_in_progress = False\n        self._sampler: ProbeEddySampler = None\n\n        # Register z_virtual_endstop pin\n        self._printer.lookup_object(\"pins\").register_chip(\"probe\", self)\n        # Register event handlers\n        self._printer.register_event_handler(\"klippy:mcu_identify\", self._handle_mcu_identify)\n        self._printer.register_event_handler(\"homing:homing_move_begin\", self._handle_homing_move_begin)\n        self._printer.register_event_handler(\"homing:homing_move_end\", self._handle_homing_move_end)\n        self._printer.register_event_handler(\"homing:home_rails_begin\", self._handle_home_rails_begin)\n        self._printer.register_event_handler(\"homing:home_rails_end\", self._handle_home_rails_end)\n        self._printer.register_event_handler(\"gcode:command_error\", self._handle_command_error)\n\n        # copy some things in for convenience\n        self._home_trigger_height = self.eddy.params.home_trigger_height\n        self._home_trigger_safe_start_offset = self.eddy.params.home_trigger_safe_start_offset\n        self._home_start_height = self.eddy._home_start_height  # this is trigger + safe_start + 1.0\n        self._probe_speed = self.eddy.params.probe_speed\n        self._lift_speed = self.eddy.params.lift_speed\n\n    def _handle_mcu_identify(self):\n        kin = self._printer.lookup_object(\"toolhead\").get_kinematics()\n        for stepper in kin.get_steppers():\n            if stepper.is_active_axis(\"z\"):\n                self.add_stepper(stepper)\n\n    def _handle_home_rails_begin(self, homing_state, rails):\n        endstops = [es for rail in rails for es, name in rail.get_endstops()]\n        if self not in endstops:\n            return\n        # Nothing to do\n        pass\n\n    def _handle_homing_move_begin(self, hmove):\n        if self not in hmove.get_mcu_endstops():\n            return\n        self._sampler = self.eddy.start_sampler()\n        self._homing_in_progress = True\n        # if we're doing a tap, we're already in the right position;\n        # otherwise move there\n        if self.tap_config is None:\n            self.eddy._probe_to_start_position_unhomed(move_home=True)\n\n    def _handle_homing_move_end(self, hmove):\n        if self not in hmove.get_mcu_endstops():\n            return\n        self._sampler.finish()\n        self._homing_in_progress = False\n\n    def _handle_home_rails_end(self, homing_state, rails):\n        endstops = [es for rail in rails for es, name in rail.get_endstops()]\n        if self not in endstops:\n            return\n        # Nothing to do\n        pass\n\n    def _handle_command_error(self, gcmd=None):\n        if self._homing_in_progress:\n            self._homing_in_progress = False\n        try:\n            if self._sampler is not None:\n                self._sampler.finish()\n        except:\n            logging.exception(\"EDDYng handle_command_error: sampler.finish() failed\")\n\n    def setup_pin(self, pin_type, pin_params):\n        if pin_type != \"endstop\" or pin_params[\"pin\"] != \"z_virtual_endstop\":\n            raise pins.error(\"Probe virtual endstop only useful as endstop pin\")\n        if pin_params[\"invert\"] or pin_params[\"pullup\"]:\n            raise pins.error(\"Can not pullup/invert probe virtual endstop\")\n        return self\n\n    # these are the \"MCU Probe\" methods\n    def get_mcu(self):\n        return self._mcu\n\n    def add_stepper(self, stepper):\n        self._dispatch.add_stepper(stepper)\n\n    def get_steppers(self):\n        return self._dispatch.get_steppers()\n\n    def get_position_endstop(self):\n        if self.tap_config is None:\n            return self._home_trigger_height\n        else:\n            return 0.0\n\n    def home_start(self, print_time, sample_time, sample_count, rest_time, triggered=True):\n        if not self._sampler.active():\n            raise self._printer.command_error(\"home_start called without a sampler active\")\n\n        self.last_trigger_time = 0.0\n        self.last_tap_start_time = 0.0\n\n        trigger_height = self._home_trigger_height\n        safe_height = trigger_height + self._home_trigger_safe_start_offset\n\n        if self.tap_config is None:\n            safe_time = print_time + self.eddy.params.home_trigger_safe_time_offset\n            trigger_freq = self.eddy.height_to_freq(trigger_height)\n            safe_freq = self.eddy.height_to_freq(safe_height)\n        else:\n            # TODO: the home trigger safe time won't work, because we'll pass\n            # the home_trigger_height maybe by default given where tap might\n            # start\n            safe_time = 0\n            # initial freq to pass through\n            safe_freq = self.eddy.height_to_freq(self._home_trigger_height)\n            # second freq to pass through; toolhead acceleration\n            # must be smooth after this point\n            trigger_freq = self.eddy.height_to_freq(self.eddy.params.tap_trigger_safe_start_height)\n\n        trigger_completion = self._dispatch.start(print_time)\n\n        if self.tap_config is not None:\n            if self.tap_config.mode == \"butter\":\n                sos = self.tap_config.sos\n                assert sos\n                for i in range(len(sos)):\n                    self.eddy._sensor.set_sos_section(i, sos[i])\n                mode = \"sos\"\n            elif self.tap_config.mode == \"wma\":\n                mode = \"wma\"\n            else:\n                raise self._printer.command_error(f\"Invalid tap mode: {self.tap_config.mode}\")\n            tap_threshold = self.tap_config.threshold\n        else:\n            mode = \"home\"\n            tap_threshold = None\n\n        self.eddy._log_debug(\n            f\"EDDYng home_start {mode}: {print_time:.3f} freq: {trigger_freq:.2f} safe-start: {safe_freq:.2f} @ {safe_time:.3f}\"\n        )\n        # setup homing -- will start scanning and trigger when we hit\n        # trigger_freq\n        self._sensor.setup_home(\n            self._dispatch.get_oid(),\n            mcu.MCU_trsync.REASON_ENDSTOP_HIT,\n            self.REASON_BASE,\n            trigger_freq,\n            safe_freq,\n            safe_time,\n            mode=mode,\n            tap_threshold=tap_threshold,\n            max_errors=self.eddy.params.max_errors,\n        )\n\n        return trigger_completion\n\n    def home_wait(self, home_end_time):\n        self.eddy._log_debug(f\"home_wait until {home_end_time:.3f}\")\n        # logging.info(f\"EDDYng home_wait {home_end_time} cur {curtime} ept {est_print_time} ehe {est_he_time}\")\n        self._dispatch.wait_end(home_end_time)\n\n        # make sure homing is stopped, and grab the trigger_time from the mcu\n        home_result = self._sensor.finish_home()\n        trigger_time = home_result.trigger_time\n        tap_start_time = home_result.tap_start_time\n        error = self._sensor.data_error_to_str(home_result.error) if home_result.error != 0 else \"\"\n\n        is_tap = self.tap_config is not None\n\n        self._sampler.memo(\"trigger_time\", trigger_time)\n        if is_tap:\n            self._sampler.memo(\"tap_start_time\", tap_start_time)\n            self._sampler.memo(\"tap_threshold\", self.tap_config.threshold)\n\n        self.eddy._log_debug(\n            f\"trigger_time {trigger_time} (mcu: {self._mcu.print_time_to_clock(trigger_time)}) tap time: {tap_start_time}-{trigger_time} {error}\"\n        )\n\n        # nb: _dispatch.stop() will treat anything >= REASON_COMMS_TIMEOUT as an error,\n        # and will only return those results. Fine for us since we only have one trsync,\n        # but annoying in general.\n        res = self._dispatch.stop()\n\n        # clean these up, and only update them if successful\n        self.last_trigger_time = 0.0\n        self.last_tap_start_time = 0.0\n\n        # always reset this; taps are one-shot usages of the endstop wrapper\n        self.tap_config = None\n\n        # if we're doing a tap, we wait for samples for the end as well so that we can get\n        # beter data for analysis\n        self._sampler.wait_for_sample_at_time(trigger_time)\n\n        # success?\n        if res == mcu.MCU_trsync.REASON_ENDSTOP_HIT:\n            self.last_trigger_time = trigger_time\n            self.last_tap_start_time = tap_start_time\n            if is_tap:\n                return tap_start_time + (trigger_time - tap_start_time) * self.eddy.params.tap_time_position\n            return trigger_time\n\n        # various errors\n        if res == mcu.MCU_trsync.REASON_COMMS_TIMEOUT:\n            raise self._printer.command_error(\"Communication timeout during homing\")\n        if res == self.REASON_ERROR_SENSOR:\n            raise self._printer.command_error(f\"Sensor error ({error})\")\n        if res == self.REASON_ERROR_PROBE_TOO_LOW:\n            raise self._printer.command_error(\"Probe too low at start of homing, did not clear safe height.\")\n        if res == self.REASON_ERROR_TOO_EARLY:\n            raise self._printer.command_error(\"Probe cleared safe height too early.\")\n        if res == mcu.MCU_trsync.REASON_PAST_END_TIME:\n            raise self._printer.command_error(\n                \"Probe completed movement before triggering. If this is a tap, try lowering TARGET_Z or adjusting the THRESHOLD.\"\n            )\n\n        raise self._printer.command_error(f\"Unknown homing error: {res}\")\n\n    def query_endstop(self, print_time):\n        return False\n\n    def _setup_sampler(self):\n        self._sampler = self.eddy.start_sampler()\n\n    def _finish_sampler(self):\n        self._sampler.finish()\n        self._sampler = None\n\n\n# Helper to gather samples and convert them to probe positions\n@final\nclass ProbeEddySampler:\n    def __init__(\n        self,\n        eddy: ProbeEddy,\n        calculate_heights: bool = True,\n    ):\n        self.eddy = eddy\n        self._sensor = eddy._sensor\n        self._printer = self.eddy._printer\n        self._reactor = self._printer.get_reactor()\n        self._mcu = self._sensor.get_mcu()\n        self._stopped = False\n        self._started = False\n        self._errors = 0\n        self._fmap = eddy.map_for_drive_current() if calculate_heights else None\n\n        self.times = []\n        self.raw_freqs = []\n        self.freqs = []\n        self.heights = [] if self._fmap is not None else None\n\n        self.memos = dict()\n\n    @property\n    def raw_count(self):\n        return len(self.times)\n\n    @property\n    def height_count(self):\n        return len(self.heights) if self.heights else 0\n\n    # this is just a handy way to communicate values between different parts of the system,\n    # specifically to record things like trigger times for plotting\n    def memo(self, name, value):\n        self.memos[name] = value\n\n    def __enter__(self):\n        self.start()\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        self.finish()\n\n    def active(self):\n        return self._started and not self._stopped\n\n    # bulk sample callback for when new data arrives\n    # from the probe\n    def _add_hw_measurement(self, msg):\n        if self._stopped:\n            return False\n\n        self._errors += msg[\"errors\"]\n        data = msg[\"data\"]\n\n        # data is (t, fv)\n        if data:\n            times, raw_freqs = zip(*data)\n        else:\n            times, raw_freqs = [], []\n\n        self.times.extend(times)\n        self.raw_freqs.extend(raw_freqs)\n\n        return True\n\n    def start(self):\n        if self._stopped:\n            raise self._printer.command_error(\"ProbeEddySampler.start() called after finish()\")\n        if not self._started:\n            self._sensor.add_bulk_sensor_data_client(self._add_hw_measurement)\n            self._started = True\n\n    def finish(self):\n        if self._stopped:\n            return\n        if not self._started:\n            raise self._printer.command_error(\"ProbeEddySampler.finish() called without start()\")\n        if self.eddy._sampler is not self:\n            raise self._printer.command_error(\"ProbeEddySampler.finish(): eddy._sampler is not us!\")\n        self._update_samples()\n        self.eddy._sampler_finished(self)\n        self._stopped = True\n\n    def _update_samples(self):\n        if len(self.freqs) == len(self.raw_freqs):\n            return\n\n        conv_ratio = self._sensor.freqval_conversion_value()\n\n        start_idx = len(self.freqs)\n        freqs_np = np.asarray(self.raw_freqs[start_idx:]) * conv_ratio\n        self.freqs.extend(freqs_np.tolist())\n\n        if self._fmap is not None:\n            heights_np = self._fmap.freqs_to_heights_np(freqs_np)\n            self.heights.extend(heights_np.tolist())\n\n    @property\n    def error_count(self):\n        return self._errors\n\n    # get the last sampled height\n    def get_last_height(self) -> float:\n        if self.heights is None:\n            raise self._printer.command_error(\"ProbeEddySampler: no height mapping\")\n        self._update_samples()\n        if len(self.heights) == 0:\n            raise self._printer.command_error(\"ProbeEddySampler: no samples\")\n        return self.heights[-1]\n\n    # wait for a sample for the current time and get a new height\n    def get_height_now(self) -> Optional[float]:\n        now = self.eddy._print_time_now()\n        if not self.wait_for_sample_at_time(now, max_wait_time=1.000, raise_error=False):\n            return None\n        return self.get_last_height()\n\n    # Wait until a sample for the given time arrives\n    def wait_for_sample_at_time(self, sample_print_time, max_wait_time=0.250, raise_error=True) -> bool:\n        def report_no_samples():\n            if raise_error:\n                raise self._printer.command_error(f\"No samples received for time {sample_print_time:.3f} (waited for {max_wait_time:.3f})\")\n            return False\n\n        if self._stopped:\n            # if we're not getting any more samples, we can check directly\n            if len(self.times) == 0:\n                return report_no_samples()\n            return self.times[-1] >= sample_print_time\n\n        # quick check\n        if self.times and self.times[-1] >= sample_print_time:\n            return True\n\n        wait_start_time = self.eddy._print_time_now()\n\n        # if sample_print_time is in the future, make sure to wait max_wait_time\n        # past the expected time\n        if sample_print_time > wait_start_time:\n            max_wait_time = max_wait_time + (sample_print_time - wait_start_time)\n\n        # this is just a sanity check, there shouldn't be any reason to ever wait this long\n        if max_wait_time > 30.0:\n            traceback.print_stack()\n            msg = f\"ProbeEddyFrequencySampler: max_wait_time {max_wait_time:.3f} is too far into the future\"\n            raise self._printer.command_error(msg)\n\n        self.eddy._log_debug(\n            f\"EDDYng waiting for sample at {sample_print_time:.3f} (now: {wait_start_time:.3f}, max_wait_time: {max_wait_time:.3f})\"\n        )\n        now = self.eddy._print_time_now()\n        while len(self.times) == 0 or self.times[-1] < sample_print_time:\n            now = self.eddy._print_time_now()\n            if now - wait_start_time > max_wait_time:\n                return report_no_samples()\n            self._reactor.pause(self._reactor.monotonic() + 0.010)\n\n        if now - wait_start_time > 1.0:\n            self.eddy._log_info(f\"note: waited {now - wait_start_time:.3f}s for sample\")\n\n        return True\n\n    # Wait for some samples to be collected, even if errors\n    # TODO: there's a minimum wait time -- we need to fill up the buffer before data is sent, and that\n    # depends on the data rate\n    def wait_for_samples(\n        self,\n        max_wait_time=0.300,\n        count_errors=False,\n        min_samples=1,\n        new_only=False,\n        raise_error=True,\n    ):\n        # Make sure enough samples have been collected\n        wait_start_time = self.eddy._print_time_now()\n\n        start_error_count = self._errors\n        start_count = 0\n        if new_only:\n            start_count = len(self.raw_freqs) + (self._errors if count_errors else 0)\n\n        while (len(self.raw_freqs) + (self._errors if count_errors else 0)) - start_count < min_samples:\n            now = self.eddy._print_time_now()\n            if now - wait_start_time > max_wait_time:\n                if raise_error:\n                    raise self._printer.command_error(\n                        f\"probe_eddy_ng sensor outage: no samples for {max_wait_time:.2f}s (got {self._errors - start_error_count} errors)\"\n                    )\n                return False\n            self._reactor.pause(self._reactor.monotonic() + 0.010)\n\n        return True\n\n    def find_heights_at_times(self, intervals):\n        self._update_samples()\n        times = self.times\n        heights = np.asarray(self.heights)\n        num_samples = len(times)\n\n        interval_heights = []\n        i = 0\n        for iv_start, iv_end in intervals:\n            while i < num_samples and times[i] < iv_start:\n                i += 1\n            istart = i\n\n            while i < num_samples and times[i] < iv_end:\n                i += 1\n            iend = i\n\n            if istart == iend:\n                # no samples in this range\n                raise self._printer.command_error(f\"No samples in time range {iv_start}-{iv_end}\")\n\n            median = np.median(heights[istart:iend])\n            interval_heights.append(float(median))\n\n        return interval_heights\n\n    def find_height_at_time(self, start_time, end_time):\n        if end_time < start_time:\n            raise self._printer.command_error(\"find_height_at_time: end_time is before start_time\")\n\n        self._update_samples()\n\n        if len(self.times) == 0:\n            raise self._printer.command_error(\"No samples at all, so none in time range\")\n\n        if not self.heights:\n            raise self._printer.command_error(\"Update samples didn't compute heights\")\n\n        self.eddy._log_debug(\n                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\"\n        )\n\n        # find the first sample that is >= start_time\n        start_idx = bisect.bisect_left(self.times, start_time)\n        if start_idx >= len(self.times):\n            raise self._printer.command_error(\"Nothing after start_time?\")\n\n        # find the last sample that is < end_time\n        end_idx = start_idx\n        while end_idx < len(self.times) and self.times[end_idx] < end_time:\n            end_idx += 1\n\n        # average the heights of the samples in the range\n        heights = self.heights[start_idx:end_idx]\n        if len(heights) == 0:\n            raise self._printer.command_error(f\"no samples between time {start_time:.1f} and {end_time:.1f}!\")\n        hmin, hmax = np.min(heights), np.max(heights)\n        mean = np.mean(heights)\n        median = np.median(heights)\n        self.eddy._log_debug(\n            f\"find_height_at_time: {len(heights)} samples, median: {median:.3f}, mean: {mean:.3f} (range {hmin:.3f}-{hmax:.3f})\"\n        )\n\n        return float(median)\n\n\n@final\nclass ProbeEddyFrequencyMap:\n    calibration_version = 5\n    low_z_threshold = 5.0\n\n    def __init__(self, eddy: ProbeEddy):\n        self._eddy = eddy\n        self._sensor = eddy._sensor\n\n        self.drive_current = 0\n        self.height_range = (math.inf, -math.inf)\n        self.freq_range = (math.inf, -math.inf)\n        self._ftoh: Optional[npp.Polynomial] = None\n        self._ftoh_high: Optional[npp.Polynomial] = None\n        self._htof: Optional[npp.Polynomial] = None\n\n    def _str_to_exact_floatlist(self, str):\n        return [float.fromhex(v) for v in str.split(\",\")]\n\n    def _exact_floatlist_to_str(self, vals):\n        return str.join(\", \", [float.hex(v) for v in vals])\n\n    def _coefs_to_str(self, coefs):\n        return \", \".join([format(c, \".3f\") for c in coefs])\n\n    def freq_spread(self) -> float:\n        return ((self.freq_range[1] / self.freq_range[0]) - 1.0) * 100.0\n\n    def load_from_config(self, config: ConfigWrapper, drive_current: int):\n        calibstr = config.get(f\"calibration_{drive_current}\", None)\n        if calibstr is None:\n            self.drive_current = 0\n            self._ftoh = None\n            self._htof = None\n            self.height_range = (math.inf, -math.inf)\n            self.freq_range = (math.inf, -math.inf)\n            return\n\n        data = pickle.loads(base64.b64decode(calibstr))\n        v = data.get(\"v\", None)\n        if v is None or v < self.calibration_version:\n            self._eddy._log_info(f\"Calibration for dc {drive_current} is old ({v}), needs recalibration\")\n            return False\n\n        ftoh = data.get(\"ftoh\", None)\n        ftoh_high = data.get(\"ftoh_high\", None)\n        htof = data.get(\"htof\", None)\n        dc = data.get(\"dc\", None)\n        h_range = data.get(\"h_range\", (math.inf, -math.inf))\n        f_range = data.get(\"f_range\", (math.inf, -math.inf))\n\n        if dc != drive_current:\n            raise configerror(f\"ProbeEddyFrequencyMap: drive current mismatch: loaded {dc} != requested {drive_current}\")\n\n        self._ftoh = ftoh\n        self._ftoh_high = ftoh_high\n        self._htof = htof\n        self.height_range = h_range\n        self.freq_range = f_range\n        self.drive_current = drive_current\n\n        self._eddy._log_info(f\"Loaded calibration for drive current {drive_current}\")\n        return True\n\n    def save_calibration(self):\n        if self._ftoh is None or self._htof is None:\n            return\n\n        configfile = self._eddy._printer.lookup_object(\"configfile\")\n        data = {\n            \"v\": self.calibration_version,\n            \"ftoh\": self._ftoh,\n            \"ftoh_high\": self._ftoh_high,\n            \"htof\": self._htof,\n            \"h_range\": self.height_range,\n            \"f_range\": self.freq_range,\n            \"dc\": self.drive_current,\n        }\n        calibstr = base64.b64encode(pickle.dumps(data)).decode()\n        configfile.set(self._eddy._full_name, f\"calibration_{self.drive_current}\", calibstr)\n\n    def calibrate_from_values(\n        self,\n        drive_current: int,\n        raw_times: List[float],\n        raw_freqs_list: List[float],\n        raw_heights_list: List[float],\n        raw_vels_list: List[float],\n        report_errors: bool,\n        write_debug_files: bool,\n    ):\n        if len(raw_freqs_list) != len(raw_heights_list):\n            raise ValueError(\"freqs and heights must be the same length\")\n\n        if len(raw_freqs_list) == 0:\n            self._eddy._log_info(\"calibrate_from_values: empty list\")\n            return None, None\n\n        # everything must be a np.array or things get confused below\n        times = np.asarray(raw_times)\n        freqs = np.asarray(raw_freqs_list)\n        heights = np.asarray(raw_heights_list)\n        vels = np.asarray(raw_vels_list) if raw_vels_list else None\n\n        if write_debug_files:\n            with open(\"/tmp/eddy-calibration.csv\", \"w\") as data_file:\n                data_file.write(\"time,frequency,avg_freq,z,avg_z,v\\n\")\n                for i in range(len(freqs)):\n                    s_t = times[i]\n                    s_f = freqs[i]\n                    s_z = heights[i]\n                    s_v = vels[i] if vels is not None else 0.0\n                    data_file.write(f\"{s_t},{s_f},{s_z},,{s_v}\\n\")\n                self._eddy._log_info(f\"Wrote {len(freqs)} samples to /tmp/eddy-calibration.csv\")\n\n        if len(freqs) == 0 or len(heights) == 0:\n            if report_errors:\n                self._eddy._log_error(\n                    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.\"\n                )\n            return None, None\n\n        max_height = float(heights.max())\n        min_height = float(heights.min())\n        min_freq = float(freqs.min())\n        max_freq = float(freqs.max())\n        freq_spread = ((max_freq / min_freq) - 1.0) * 100.0\n\n        # Check if our calibration is good enough\n        if report_errors:\n            if max_height < 2.5:  # we really can't do anything with this\n                self._eddy._log_error(\n                    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.\"\n                )\n                if not self._eddy.params.allow_unsafe:\n                    return None, None\n\n            if min_height > 0.65:  # this is a bit arbitrary; but if it's this far off we shouldn't trust it\n                self._eddy._log_error(\n                    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.\"\n                )\n                if not self._eddy.params.allow_unsafe:\n                    return None, None\n\n            if min_height > 0.025:\n                self._eddy._log_msg(\n                    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.\"\n                )\n\n            # somewhat arbitrary spread\n            if freq_spread < 0.30:\n                extremely = \"EXTREMELY \" if freq_spread < 0.15 else \"\"\n                self._eddy._log_warning(\n                    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.\"\n                )\n\n        low_samples = heights <= ProbeEddyFrequencyMap.low_z_threshold\n        high_samples = heights >= ProbeEddyFrequencyMap.low_z_threshold - 0.5\n\n        ftoh_low_fn = npp.Polynomial.fit(1.0 / freqs[low_samples], heights[low_samples], deg=9)\n        htof_low_fn = npp.Polynomial.fit(heights[low_samples], 1.0 / freqs[low_samples], deg=9)\n\n        if np.count_nonzero(high_samples) > 50:\n            ftoh_high_fn = npp.Polynomial.fit(1.0 / freqs[high_samples], heights[high_samples], deg=9)\n        else:\n            self._eddy._log_debug(f\"not computing ftoh_high, not enough high samples\")\n            ftoh_high_fn = None\n\n        # Calculate rms, only for the low values (where error is most relevant)\n        rmse_fth = np_rmse(\n            ftoh_low_fn,\n            1.0 / freqs[low_samples],\n            heights[low_samples],\n        )\n        rmse_htf = np_rmse(\n            htof_low_fn,\n            heights[low_samples],\n            1.0 / freqs[low_samples],\n        )\n\n        if report_errors:\n            if rmse_fth > 0.050:\n                self._eddy._log_error(\n                    f\"Drive current {drive_current} error: calibration error margin is too high ({rmse_fth:.3f}). Possible causes: bad drive current, bad sensor mount height.\"\n                )\n                if not self._eddy.params.allow_unsafe:\n                    return None, None\n\n        self._ftoh = ftoh_low_fn\n        self._htof = htof_low_fn\n        self._ftoh_high = ftoh_high_fn\n        self.drive_current = drive_current\n        self.height_range = [min_height, max_height]\n        self.freq_range = [min_freq, max_freq]\n\n        self._eddy._log_msg(\n            f\"Drive current {drive_current}: valid height: {min_height:.3f} to {max_height:.3f}, \"\n            f\"freq spread {freq_spread:.2f}% ({min_freq:.1f} - {max_freq:.1f}), \"\n            f\"Fit {rmse_fth:.4f} ({rmse_htf:.2f})\"\n        )\n\n        if write_debug_files:\n            self._write_calibration_plot(\n                times,\n                freqs,\n                heights,\n                rmse_fth,\n                rmse_htf,\n                vels=vels,\n            )\n\n        return rmse_fth, rmse_htf\n\n    def _write_calibration_plot(\n        self,\n        times,\n        freqs,\n        heights,\n        rmse_fth,\n        rmse_htf,\n        vels=None,\n    ):\n        if not plotly:\n            return\n\n        if self._ftoh is None or self._htof is None:\n            logging.warning(f\"write_calibration_plot: null calibration?\")\n            return\n\n        import plotly.graph_objects as go\n\n        low_samples = heights <= ProbeEddyFrequencyMap.low_z_threshold\n        high_samples = heights >= ProbeEddyFrequencyMap.low_z_threshold - 0.5\n\n        f_to_z_low_err = heights[low_samples] - self._ftoh(1.0 / freqs[low_samples])\n\n        if self._ftoh_high is not None:\n            f_to_z_high_err = heights[high_samples] - self._ftoh_high(1.0 / freqs[high_samples])\n        else:\n            f_to_z_high_err = None\n\n        fig = go.Figure()\n        fig.add_trace(go.Scatter(x=times, y=heights, mode=\"lines\", name=\"Z\"))\n\n        fig.add_trace(\n            go.Scatter(\n                x=times[low_samples],\n                y=self._ftoh(1.0 / freqs[low_samples]),\n                mode=\"lines\",\n                name=f\"Z {rmse_fth:.4f}\",\n            )\n        )\n\n        if self._ftoh_high is not None:\n            fig.add_trace(\n                go.Scatter(\n                    x=times[high_samples],\n                    y=self._ftoh_high(1.0 / freqs[high_samples]),\n                    mode=\"lines\",\n                    name=f\"Z (high)\",\n                )\n            )\n\n        fig.add_trace(go.Scatter(x=times, y=freqs, mode=\"lines\", name=\"F\", yaxis=\"y2\"))\n\n        fig.add_trace(\n            go.Scatter(\n                x=times[low_samples],\n                y=1.0 / self._htof(heights[low_samples]),\n                mode=\"lines\",\n                name=f\"F ({rmse_htf:.2f})\",\n                yaxis=\"y2\",\n            )\n        )\n\n        fig.add_trace(\n            go.Scatter(\n                x=times[low_samples],\n                y=f_to_z_low_err,\n                mode=\"lines\",\n                name=\"Err\",\n                yaxis=\"y3\",\n            )\n        )\n        if f_to_z_high_err is not None:\n            fig.add_trace(\n                go.Scatter(\n                    x=times[high_samples],\n                    y=f_to_z_high_err,\n                    mode=\"lines\",\n                    name=\"Err (high)\",\n                    yaxis=\"y3\",\n                )\n            )\n\n        if vels is not None:\n            fig.add_trace(go.Scatter(x=times, y=vels, mode=\"lines\", name=\"V\", yaxis=\"y4\"))\n\n        fig.update_layout(\n            hovermode=\"x unified\",\n            title=f\"Calibration for drive current {self.drive_current}\",\n            yaxis2=dict(title=\"Freq\", overlaying=\"y\", tickformat=\"d\", side=\"right\"),\n            yaxis3=dict(overlaying=\"y\", side=\"right\", position=0.1),\n            yaxis4=dict(overlaying=\"y\", side=\"right\", position=0.2),\n        )\n        fig.write_html(\"/tmp/eddy-calibration.html\")\n\n    def freq_to_height(self, freq: float) -> float:\n        if self._ftoh is None:\n            raise self._eddy._printer.command_error(\"Calling freq_to_height on uncalibrated map\")\n        invfreq = 1.0 / freq\n        if self._ftoh_high is not None and invfreq < self._ftoh.domain[0]:\n            return float(self._ftoh_high(invfreq))\n        return float(self._ftoh(invfreq))\n\n    def freqs_to_heights_np(self, freqs: np.array) -> np.array:\n        if self._ftoh is None:\n            raise self._eddy._printer.command_error(\"Calling freqs_to_heights on uncalibrated map\")\n        invfreqs = 1.0 / freqs\n        if self._ftoh_high is not None:\n            heights = np.zeros(len(invfreqs))\n            low_freq_vals = invfreqs > self._ftoh.domain[1]\n            heights[low_freq_vals] = np.vectorize(self._ftoh_high, otypes=[float])(invfreqs[low_freq_vals])\n            heights[~low_freq_vals] = np.vectorize(self._ftoh, otypes=[float])(invfreqs[~low_freq_vals])\n        else:\n            heights = self._ftoh(invfreqs)\n        return heights\n\n    def height_to_freq(self, height: float) -> float:\n        if self._htof is None:\n            raise self._eddy._printer.command_error(\"Calling height_to_freq on uncalibrated map\")\n        return 1.0 / float(self._htof(height))\n\n    def calibrated(self) -> bool:\n        return self._ftoh is not None and self._htof is not None\n\n\n@final\nclass BedMeshScanHelper:\n    def __init__(self, eddy, config):\n        self._eddy = eddy\n        self._printer = eddy._printer\n\n        bmc = config.getsection(\"bed_mesh\")\n        self._bed_mesh = eddy._printer.load_object(bmc, \"bed_mesh\")\n        self._x_points, self._y_points = bmc.getintlist(\"probe_count\", count=2, note_valid=False)\n        self._x_min, self._y_min = bmc.getfloatlist(\"mesh_min\", count=2, note_valid=False)\n        self._x_max, self._y_max = bmc.getfloatlist(\"mesh_max\", count=2, note_valid=False)\n        self._speed = bmc.getfloat(\"speed\", 100.0, above=0.0, note_valid=False)\n        self._scan_z = bmc.getfloat(\"horizontal_move_z\", self._eddy.params.home_trigger_height, above=0.0, note_valid=False)\n\n        self._x_offset = self._eddy.params.x_offset\n        self._y_offset = self._eddy.params.y_offset\n\n        self._mesh_points, self._mesh_path = self._generate_path()\n\n\n    def _generate_path(self):\n        x_vals = np.linspace(self._x_min, self._x_max, self._x_points)\n        y_vals = np.linspace(self._y_min, self._y_max, self._y_points)\n        path = []\n        reverse = False\n\n        for y in y_vals:\n            row = [(x, y, True) for x in (reversed(x_vals) if reverse else x_vals)]\n            path.extend(row)\n            reverse = not reverse\n        return path, path\n\n    def _scan_path(self):\n        th = self._eddy._toolhead\n        times = []\n\n        for pt in self._mesh_path:\n            # TODO bounds\n            th.manual_move([pt[0] - self._x_offset, pt[1] - self._y_offset, None], self._speed)\n            th.register_lookahead_callback(lambda t: times.append(t))\n\n        th.wait_moves()\n\n        return times\n\n    def _set_bed_mesh(self, heights):\n        # heights is in the order of the _mesh_path points; convert to\n        # be ordered min_y..max_y, min_x..max_x, then pull out the heights\n        indexed_points = []\n        i = 0\n        for x, y, include in self._mesh_path:\n            if not include:\n                continue\n            indexed_points.append((x, y, i))\n            i += 1\n\n        def sort_points(a, b):\n            if a[1] < b[1]: # y first\n                return -1\n            if a[1] > b[1]:\n                return 1\n            if a[0] < b[0]: # then x\n                return -1\n            if a[0] > b[0]:\n                return 1\n            return 0\n\n        indices = [ki for _, _, ki in sorted(indexed_points, key=cmp_to_key(sort_points))]\n\n        ki = 0\n        matrix = []\n        for _ in range(self._y_points):\n            row = []\n            for _ in range(self._x_points):\n                v = heights[indices[ki]]\n                row.append(self._scan_z - v)\n                ki += 1\n            matrix.append(row)\n\n        params = self._bed_mesh.bmc.mesh_config.copy()\n        params.update({\n            \"min_x\": self._x_min,\n            \"max_x\": self._x_max,\n            \"min_y\": self._y_min,\n            \"max_y\": self._y_max,\n            \"x_count\": self._x_points,\n            \"y_count\": self._y_points,\n        })\n        mesh = bed_mesh.ZMesh(params, None)\n        try:\n            mesh.build_mesh(matrix)\n        except bed_mesh.BedMeshError as e:\n            raise self._printer.command_error(str(e))\n        self._bed_mesh.set_mesh(mesh)\n        self._eddy._log_msg(\"Mesh scan complete\")\n\n    def scan(self):\n        th = self._eddy._toolhead\n\n        # move to the start point\n        v = self._mesh_path[0]\n        th.manual_move([None, None, 10.0], self._eddy.params.lift_speed)\n        th.manual_move([v[0] - self._x_offset, v[1] - self._y_offset, None], self._speed)\n        th.manual_move([None, None, self._scan_z], self._eddy.params.probe_speed)\n        th.wait_moves()\n\n        heights = []\n\n        sample_time = self._eddy.params.scan_sample_time\n\n        with self._eddy.start_sampler() as sampler:\n            path_times = self._scan_path()\n            sampler.wait_for_sample_at_time(path_times[-1] + sample_time*2.)\n            sampler.finish()\n\n            heights = sampler.find_heights_at_times([(t - sample_time/2., t + sample_time/2.) for t in path_times])\n            # Note plus tap_offset here, vs -tap_offset when probing. These are actual\n            # heights, the other is \"offset from real\"\n            heights = [h + self._eddy._tap_offset for h in heights]\n\n            with open(\"/tmp/mesh.csv\", \"w\") as mfile:\n                mfile.write(\"time,x,y,z\\n\")\n                for i in range(len(self._mesh_points)):\n                    t = path_times[i]\n                    x = self._mesh_points[i][0]\n                    y = self._mesh_points[i][1]\n                    z = heights[i]\n                    mfile.write(f\"{t},{x},{y},{z}\\n\")\n\n            self._set_bed_mesh(heights)\n\n\ndef np_rmse(p, x, y):\n    y_hat = p(x)\n    return np.sqrt(np.mean((y - y_hat) ** 2))\n\n\ndef bed_mesh_ProbeManager_start_probe_override(self, gcmd):\n    method = gcmd.get(\"METHOD\", \"automatic\").lower()\n    can_scan = False\n    pprobe = self.printer.lookup_object(\"probe\", None)\n    if pprobe is not None:\n        probe_name = pprobe.get_status(None).get(\"name\", \"\")\n        can_scan = \"eddy\" in probe_name\n    if method == \"rapid_scan\" and can_scan:\n        self.rapid_scan_helper.perform_rapid_scan(gcmd)\n    else:\n        self.probe_helper.start_probe(gcmd)\n\n\ndef load_config_prefix(config: ConfigWrapper):\n    return ProbeEddy(config)\n"
  },
  {
    "path": "pyrightconfig.json",
    "content": "{\n    \"reportOptionalMemberAccess\": false\n}\n"
  }
]