From 0a4cfafc78eaf1e24a3d90e90509f77e17056f5e Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Tue, 3 Nov 2026 02:23:24 +0100 Subject: [PATCH] tth.meshcore: MeshCore repeaters as code, over RF Ansible collection that converges MeshCore repeaters through a companion radio (TCP, USB serial or BLE): admin ACL, CLI prefs, region tree, firmware facts, companion remote-CLI ACL, and the meshcore-tth extras (BLE on/off and own BLE PIN, channel-hash filter, message age, advert fairness). Every change is read, diffed, sent and read back; --check only reads. ansible-test sanity, unit tests and a galaxy build in CI. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 70 ++ .gitignore | 5 + .yamllint | 5 + AGENTS.md | 22 + CLAUDE.md | 1 + LICENSE | 674 ++++++++++++++++++ README.md | 111 +++ examples/inventory.yml | 31 + examples/repeaters.yml | 48 ++ galaxy.yml | 24 + meta/runtime.yml | 1 + plugins/module_utils/meshcore_fw.py | 78 ++ plugins/module_utils/meshcore_link.py | 256 +++++++ plugins/module_utils/meshcore_plan.py | 279 ++++++++ plugins/modules/meshcore_acl.py | 130 ++++ plugins/modules/meshcore_ble.py | 172 +++++ plugins/modules/meshcore_companion_acl.py | 217 ++++++ plugins/modules/meshcore_fairness.py | 125 ++++ plugins/modules/meshcore_filter.py | 124 ++++ plugins/modules/meshcore_filter_hash.py | 126 ++++ plugins/modules/meshcore_fw_facts.py | 106 +++ plugins/modules/meshcore_prefs.py | 105 +++ plugins/modules/meshcore_region.py | 139 ++++ requirements.txt | 4 + ruff.toml | 6 + .../plugins/module_utils/test_meshcore_fw.py | 88 +++ .../module_utils/test_meshcore_plan.py | 248 +++++++ 27 files changed, 3195 insertions(+) create mode 100644 .gitea/workflows/ci.yml create mode 100644 .gitignore create mode 100644 .yamllint create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 examples/inventory.yml create mode 100644 examples/repeaters.yml create mode 100644 galaxy.yml create mode 100644 meta/runtime.yml create mode 100644 plugins/module_utils/meshcore_fw.py create mode 100644 plugins/module_utils/meshcore_link.py create mode 100644 plugins/module_utils/meshcore_plan.py create mode 100644 plugins/modules/meshcore_acl.py create mode 100644 plugins/modules/meshcore_ble.py create mode 100644 plugins/modules/meshcore_companion_acl.py create mode 100644 plugins/modules/meshcore_fairness.py create mode 100644 plugins/modules/meshcore_filter.py create mode 100644 plugins/modules/meshcore_filter_hash.py create mode 100644 plugins/modules/meshcore_fw_facts.py create mode 100644 plugins/modules/meshcore_prefs.py create mode 100644 plugins/modules/meshcore_region.py create mode 100644 requirements.txt create mode 100644 ruff.toml create mode 100644 tests/unit/plugins/module_utils/test_meshcore_fw.py create mode 100644 tests/unit/plugins/module_utils/test_meshcore_plan.py diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..33134d7 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,70 @@ +# Lint, ansible-test sanity, unit tests and a collection build on every push and PR. +name: ci + +"on": + push: + pull_request: + workflow_dispatch: + +env: + # renovate: datasource=pypi depName=ruff + RUFF_VERSION: "0.17.3" + # renovate: datasource=pypi depName=yamllint + YAMLLINT_VERSION: "1.38.0" + # renovate: datasource=pypi depName=ansible-core + ANSIBLE_CORE_VERSION: "2.22.0" + # renovate: datasource=pypi depName=meshcore + MESHCORE_VERSION: "2.3.17" + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - name: gitleaks + uses: https://git.rfa.cz/tth-pub/ci-actions/gitleaks@v12 + with: + mode: block + + - uses: actions/setup-python@v7 + with: + python-version: "3.14" + + - name: Install + run: | + set -euo pipefail + python -m pip install --quiet pytest "ansible-core==$ANSIBLE_CORE_VERSION" \ + "meshcore==$MESHCORE_VERSION" "ruff==$RUFF_VERSION" "yamllint==$YAMLLINT_VERSION" + + # Collection imports and ansible-test need the ansible_collections// + # layout, as a real directory (ansible-test resolves a symlinked cwd). + - name: Collection path + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/ac/ansible_collections/tth/meshcore" + cp -a . "$RUNNER_TEMP/ac/ansible_collections/tth/meshcore/" + + - name: Lint + run: | + set -euo pipefail + ruff check . + ruff format --check . + yamllint . + + - name: ansible-test sanity + run: | + set -euo pipefail + cd "$RUNNER_TEMP/ac/ansible_collections/tth/meshcore" + # the interpreter setup-python installed (ansible-test refuses others) + py=$(python -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")') + ansible-test sanity --requirements --python "$py" --local --color no + + - name: Tests + run: | + set -euo pipefail + cd "$RUNNER_TEMP/ac/ansible_collections/tth/meshcore" + PYTHONPATH="$RUNNER_TEMP/ac" python -m pytest -q -p no:cacheprovider tests/unit + + - name: Build + run: ansible-galaxy collection build --force diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..866ff62 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +__pycache__/ +.pytest_cache/ +.ruff_cache/ +*.tar.gz +tests/output/ diff --git a/.yamllint b/.yamllint new file mode 100644 index 0000000..4d38c5c --- /dev/null +++ b/.yamllint @@ -0,0 +1,5 @@ +extends: default +rules: + line-length: {max: 120} + document-start: disable + truthy: {check-keys: false} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..e3b5310 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,22 @@ +# Instructions for an AI agent using this collection + +tth.meshcore changes MeshCore repeaters over RF. They are usually part of a +community network, so a wrong run is felt by others. README.md is the +reference; these are the rules. + +1. **Always `--check --diff` first** and show the user the diff. Apply only + after the user approves that diff. +2. **Never put radio settings into `prefs`** (`freq`, `radio`, `bw`, `sf`, + `cr`) — the module refuses them anyway. They are changed on site, never + over RF: a wrong one cuts the node off for good. +3. The managing companion's pubkey must be in `admins`; keep `expect_freq` + set in the transport. +4. The admin password goes to ansible-vault, never into the inventory, + commands you print, commits or logs. +5. `serial: 1`, one repeater at a time. A lost reply is normal on RF; rerun, + do not raise timeouts blindly. +6. Done = the second run reports 0 changes. + +Developing: see README. `ansible-test sanity` must pass (it checks that +DOCUMENTATION matches argument_spec), plus `ruff check`, `ruff format --check`, +`yamllint` and the unit tests in `tests/unit`. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..e348b2b --- /dev/null +++ b/README.md @@ -0,0 +1,111 @@ +# tth.meshcore — MeshCore repeatery jako kód + +Ansible kolekce, která drží stav MeshCore repeaterů **deklarativně a na dálku +přes rádio**: kdo je admin (ACL), nastavení (`get`/`set`) a strom regionů — +to umí každý MeshCore repeater. S firmwarem +[meshcore-tth](https://git.rfa.cz/tth-pub/meshcore-tth) navíc zapínání BLE +konzole a antispamové filtry. Ke stožáru nikdo nemusí: moduly mluví +s repeaterem přes companion, který ho slyší (openHop TCP companion, nebo +companion na USB). + +Firmware kolekce **neflashuje** — jen přečte, jaká verze na uzlu běží. Jak +nahrát meshcore-tth: [návod k flashování](https://git.rfa.cz/tth-pub/meshcore-tth#flashing-a-release) +(webový flasher, Custom Firmware s `.zip`). + +``` +ansible-playbook -i inventory.yml repeaters.yml --check --diff # co by se změnilo +ansible-playbook -i inventory.yml repeaters.yml --diff # nasadit +``` + +*English: an Ansible collection that converges MeshCore repeaters (admin ACL, +CLI prefs, region tree; BLE and filters on meshcore-tth) over RF through a companion radio, +with `--check --diff` and read-back verification. Module docs are English +(`ansible-doc tth.meshcore.meshcore_acl`); this README is Czech.* + +## Instalace + +```bash +ansible-galaxy collection install git+https://git.rfa.cz/tth-pub/meshcore-ansible.git +``` + +Na hostu, kde moduly běží (ten s companionem), potřebuje Python knihovnu +[`meshcore`](https://pypi.org/project/meshcore/) (a `bleak` jen pro +`meshcore_companion_acl`), viz `requirements.txt`. Na Archu `python-meshcore` +z AUR, jinde venv a `ansible_python_interpreter` na něj. + +## Moduly + +| modul | co spravuje | firmware | +|---|---|---| +| `meshcore_acl` | admini repeateru (`setperm`), čte skutečné ACL binárním dotazem | MeshCore | +| `meshcore_prefs` | `get`/`set` klíčů; `freq`, `radio`, hesla a klíč odmítne | MeshCore | +| `meshcore_region` | strom regionů, domovský region, default scope, `region save` | MeshCore 1.10+ | +| `meshcore_fw_facts` | jen čte: verze z `ver` a odchylka hodin uzlu | MeshCore | +| `meshcore_companion_acl` | "remote CLI" příznak kontaktů na companionu, přes jeho BLE | MeshCore 1.18+ | +| `meshcore_ble` | `ble on/off`, vlastní BLE PIN (`ble pin`, z vaultu, v logu zamaskovaný), výkon BLE spojení (`blepwr`) | [meshcore-tth](https://git.rfa.cz/tth-pub/meshcore-tth) | +| `meshcore_filter_hash` | zákaz přeposílání kanálů podle hashe | meshcore-tth | +| `meshcore_filter` | stáří zpráv a dry-run filtru | meshcore-tth | +| `meshcore_fairness` | okno na adverty podle původce a dry-run | meshcore-tth | + +Moduly pro meshcore-tth na běžném firmwaru skončí chybou nebo `skipped` +(`Unknown command`), nic jiného nepošlou. + +## Jak to funguje + +- Každý repeater je host v inventáři, úlohy běží na hostu s companionem + (`delegate_to: mc_via`), `transport` říká jak: `{type: tcp, host, port}`, + `{type: serial, port, baud}` nebo `{type: ble, address}`. BLE companion musí + být spárovaný na hostu, kde modul běží (`bluetoothctl pair`); PIN modul + schválně nebere, aby neskončil v logu. **Jeden repeater po druhém** + (`serial: 1`): companion obslouží jednoho klienta a víc přihlášení naráz by + se srazilo ve vzduchu. +- Každá změna je **přečíst → poslat rozdíl → přečíst znovu**. `--check` nic + nevysílá kromě čtení, druhý běh má být 0 změn. +- Odpovědi přes RF se ztrácí a chodí pozdě: každá výměna ověřuje odesílatele + a tvar odpovědi a opakuje se (`transport.retries`, `transport.reply_timeout`). +- **Pojistky:** + - `transport.expect_freq`: companion na jiném kmitočtu = nepošle se nic + (testovací běh nedoletí do ostrého meshe); + - companion, přes který se spravuje, se z ACL nikdy neodebere; + - login, který projde jen jako host (heslo = guest heslo), je chyba, ne tiché + čekání na odpovědi, které nepřijdou. + +## Příklad + +`examples/inventory.yml` a `examples/repeaters.yml`. Admin heslo patří do +ansible-vault (`vault_meshcore_admin_password`). + +## Pasti, které stály čas + +- **Uložené prefs přebíjejí výchozí hodnoty buildu.** Jiný uzel z téže várky + může mít jiné admin heslo; login pak projde jen jako host. +- **Jednotky advert intervalů:** `advert.interval` je v **minutách**, + `flood.advert.interval` v **hodinách** (3–168). Hodnotu mimo rozsah uzel + odmítne a modul selže — nikdy po něm nezůstane tiché `OK`. +- **Heslo nikdy přes heredoc s rourou** (`echo heslo | python - <- + Declarative admin of MeshCore repeaters (ACL, prefs, regions; BLE and filters + on meshcore-tth) over RF through a companion radio. +license: [GPL-3.0-or-later] +tags: [meshcore, lora, mesh, radio] +dependencies: {} +repository: https://git.rfa.cz/tth-pub/meshcore-ansible +issues: https://git.rfa.cz/tth-pub/meshcore-ansible/issues +build_ignore: + - .gitea + - .yamllint + - ruff.toml + - AGENTS.md + - CLAUDE.md + - "*.tar.gz" + - .gitignore + - .ruff_cache + - .pytest_cache + - tests/output diff --git a/meta/runtime.yml b/meta/runtime.yml new file mode 100644 index 0000000..6000ee3 --- /dev/null +++ b/meta/runtime.yml @@ -0,0 +1 @@ +requires_ansible: ">=2.15.0" diff --git a/plugins/module_utils/meshcore_fw.py b/plugins/module_utils/meshcore_fw.py new file mode 100644 index 0000000..3767e9f --- /dev/null +++ b/plugins/module_utils/meshcore_fw.py @@ -0,0 +1,78 @@ +"""Radio-free parsing of `ver` and of the BLE commands of meshcore-tth. + +Kept apart from the modules so it can be unit-tested on real replies (see +tests/unit) -- every rule here once cost time on real hardware. +""" + +import re + +# Stamp written by meshcore-tth's tools/build_version.py: -tth[+]. +# '+' = built from a dirty tree: nobody can tell what is in it, so such a node +# always counts as outdated. +# meshcore-tth v1.18.0-tth0781378; Solo v2.0-tth8345a5a, or its CI release name +# v2.0+tth.20261011195120 (two-part version, optional -rcN). +VERSION_RE = re.compile(r"v\d+(?:\.\d+)+(?:-rc\d+)?(?:-tth-?[0-9a-f]{4,}\+?|\+tth\.\d{14})") +# Stock MeshCore: `v1.18.0 (Build: ...)`. Only trusted right before "(Build:", +# a bare vX.Y.Z elsewhere in a reply or an ELF is too easy to mistake. +UPSTREAM_RE = re.compile(r"(v\d+(?:\.\d+)+(?:-rc\d+)?) \(Build: ") + + +def parse_version(text): + """First firmware stamp in a `ver` reply / board_probe line / ELF, or None.""" + m = VERSION_RE.search(text or "") + if m: + return m.group(0) + m = UPSTREAM_RE.search(text or "") + return m.group(1) if m else None + + +def fw_state(current, wanted): + """'current' | 'outdated' | 'dirty' | 'unknown' (no readable version).""" + if not wanted or wanted.endswith("+"): + raise ValueError(f"wanted version {wanted!r} is not a clean stamp -- build from a clean tree") + if not current: + return "unknown" + if current.endswith("+"): + return "dirty" + return "current" if current == wanted else "outdated" + + +# ── BLE CLI replies (examples/simple_repeater/main.cpp) ───────────────────── + + +def parse_ble(text): + """`ble` -> 'on' | 'off'. Reply: 'BLE: on (advertising)'.""" + m = re.match(r"^BLE: (on|off)\b", (text or "").strip()) + if not m: + raise ValueError(f"unexpected `ble` reply: {text!r}") + return m.group(1) + + +def parse_ble_pin(text): + """`ble` -> 'own' | 'build default', or None when the firmware predates `ble pin`. + + Reply: 'BLE: off, PIN own'. The PIN itself is never printed. + """ + m = re.search(r", PIN (own|build default)\s*$", (text or "").strip()) + return m.group(1) if m else None + + +def ble_pin_valid(pin): + return isinstance(pin, str) and len(pin) == 6 and pin.isdigit() + + +def parse_blepwr(text): + """`blepwr` -> connection tx power in dBm. Reply: 'BLE conn tx: 0 dBm, adv tx: 8 dBm'.""" + m = re.match(r"^BLE conn tx: (-?\d+) dBm", (text or "").strip()) + if not m: + raise ValueError(f"unexpected `blepwr` reply: {text!r}") + return int(m.group(1)) + + +BLE_CONN_TX_VALID = {-40, -20, -16, -12, -8, -4, 0, 2, 3, 4, 5, 6, 7, 8} + + +def blepwr_set_ok(text): + """A `blepwr ` reply proves the value is applied AND saved.""" + t = (text or "").strip() + return t.startswith("OK") and t.endswith(", saved") diff --git a/plugins/module_utils/meshcore_link.py b/plugins/module_utils/meshcore_link.py new file mode 100644 index 0000000..21d9cef --- /dev/null +++ b/plugins/module_utils/meshcore_link.py @@ -0,0 +1,256 @@ +"""RF admin link to a MeshCore repeater (or companion) through a companion radio. + +Shared by the tth.meshcore modules. The companion is either a TCP companion +(e.g. an openHop companion), a USB serial companion, or a BLE companion +bonded on the host the module runs on. Everything below was +learned the hard way: + +* subscribe to replies BEFORE sending anything -- wait_for_event only sees + events created after it is called, so a reply delivered meanwhile is lost; +* set the companion's path hash width to 2 B (its own pref, default 1 B); +* a repeater that never advertised can still be addressed: build the contact + from its full pubkey (the login secret is derived from the contact); +* use send_login_sync -- plain send_login + wait times out on a flood login; +* never echo the password: the node's `password` reply contains it. + +A COMPANION target (companion=True), fw 1.18+ / Solo 2.0+: its ACL is the +"remote CLI" flag (ContactInfo flags 0x10) on its contacts, set on the companion +itself -- the same mc_admins keys as on the repeaters, nobody else. A command +comes as TXT_TYPE_CLI_COMMAND (3), encrypted to that contact's shared secret, +so only a flagged key gets an answer; there is no password step on top. Type 1 +that send_cmd uses is a CLI *reply* there and only lands in its app. + +Plus what the RF itself does: replies get lost and occasionally arrive late, +so every CLI exchange checks that the reply came from the target and looks +like the expected kind of answer, and retries otherwise. +""" + +import asyncio +import re +import time + +try: + from meshcore import EventType, MeshCore + + HAS_MESHCORE = True +except ImportError: # reported by the module via missing_required_lib + HAS_MESHCORE = False + +HEX64 = re.compile(r"^[0-9a-f]{64}$") + + +class LinkError(Exception): + pass + + +class Link: + def __init__( + self, + transport, + target, + password="", + path_hash_mode=1, + reply_timeout=None, + retries=None, + companion=False, + name=None, + ): + self.transport = transport + self.companion = companion + self.last_reply_ts = None # node clock (sender_timestamp) of the last matched reply + self.last_reply_at = None + self.contact_name = (name or "target")[:31] + self.target_pk = target.lower() + if not HEX64.match(self.target_pk): + raise LinkError("target must be the node's full 64-hex pubkey") + self.password = password or "" + self.path_hash_mode = path_hash_mode + # A repeater with a BLE client connected lost three CLI replies in a row + # (a BLE link mutes DIRECT traffic, and CLI replies are DIRECT), so the + # default is generous; both can be set per host in mc_transport. + self.reply_timeout = float(reply_timeout or transport.get("reply_timeout", 20)) + self.retries = int(retries if retries is not None else transport.get("retries", 4)) + self.mc = None + self.contact = None + self.inbox = [] + self.log = [] # human-readable trace, returned by the modules (no secrets) + + # ── session ───────────────────────────────────────────────────────────── + + async def open(self): + t = self.transport + if t.get("type") == "serial": + self.mc = await MeshCore.create_serial(t["port"], int(t.get("baud", 115200))) + elif t.get("type") == "ble": + # No PIN here on purpose: it would end up in the task's logged + # arguments. The companion is bonded once by hand (bluetoothctl pair) + # on the host the module runs on, and the bond does the encryption. + self.mc = await MeshCore.create_ble(t["address"]) + else: + self.mc = await MeshCore.create_tcp( + host=t.get("host", "127.0.0.1"), port=int(t["port"]), auto_reconnect=False + ) + if self.mc is None: + raise LinkError(f"cannot connect to companion {t}") + # Bench guard: an inventory that says which frequency its companion must + # be on never transmits anywhere else (a bench run must not reach the + # live mesh because a cable went to the wrong board). + if t.get("expect_freq") is not None: + freq = float((self.mc.self_info or {}).get("radio_freq") or 0) + if abs(freq - float(t["expect_freq"])) > 0.01: + await self.mc.disconnect() + raise LinkError(f"companion is on {freq} MHz, inventory expects {t['expect_freq']} -- nothing sent") + self.mc.subscribe(EventType.CONTACT_MSG_RECV, lambda ev: self.inbox.append(ev.payload)) + if (await self.mc.commands.get_path_hash_mode()) != self.path_hash_mode: + await self.mc.commands.set_path_hash_mode(self.path_hash_mode) + await self.mc.ensure_contacts() + self.contact = self._find_contact() + if self.contact is None: + await self._add_contact() + await self.mc.start_auto_message_fetching() + + async def close(self): + if self.mc is not None: + await self.mc.disconnect() + + def self_pubkey(self): + return (self.mc.self_info or {}).get("public_key", "").lower() + + def _find_contact(self): + for c in (self.mc.contacts or {}).values(): + if (c.get("public_key") or "").lower() == self.target_pk: + return c + return None + + async def _add_contact(self): + contact = { + "public_key": self.target_pk, + "type": 1 if self.companion else 2, + "flags": 0, + "out_path": "", + "out_path_len": -1, + # last_advert = now: with 0 it is the "oldest" contact and the next + # eviction (table full) would pick exactly the one just created. + "out_path_hash_mode": 0, + "adv_name": self.contact_name, + "last_advert": int(time.time()), + "adv_lat": 0.0, + "adv_lon": 0.0, + } + ev = await self.mc.commands.add_contact(contact) + if ev is not None and ev.type == EventType.ERROR: + # Table full (a busy companion with auto-add sits at 1000/1000): + # make room the way the firmware's own auto-add does -- drop the + # contact heard longest ago that is not a favourite. + cands = [ + c + for c in (self.mc.contacts or {}).values() + if not (c.get("flags") or 0) & 1 and (c.get("public_key") or "").lower() != self.target_pk + ] + if not cands: + raise LinkError(f"companion refused the contact ({ev.payload}) and nothing can be evicted") + victim = min(cands, key=lambda c: c.get("last_advert") or 0) + await self.mc.commands.remove_contact(victim["public_key"]) + self.log.append(f"contact table full: evicted {victim.get('adv_name') or victim['public_key'][:12]}") + await self.mc.commands.add_contact(contact) + await asyncio.sleep(2) + fresh = await self.mc.commands.get_contacts() + for c in ((fresh.payload if fresh else None) or {}).values(): + if (c.get("public_key") or "").lower() == self.target_pk: + self.contact = c + self.log.append("contact created from pubkey") + return + raise LinkError("could not create a contact for the target") + + async def login(self): + """Admin login; blank password works for a client already in the ACL.""" + for attempt in range(1 + self.retries): + # a stale path from an earlier session would send the login nowhere + await self.mc.commands.reset_path(self.contact) + ev = await self.mc.commands.send_login_sync(self.contact, self.password, timeout=45) + if ev is not None and ev.type == EventType.LOGIN_SUCCESS: + # LOGIN_SUCCESS alone is not enough: a password that equals the + # node's GUEST password (or a blank one when guest is blank) logs + # in as guest, and the admin requests then just go unanswered. + if not (ev.payload or {}).get("is_admin"): + raise LinkError( + "logged in as GUEST, not admin -- the node's admin password differs " + "(prefs override the build) or this companion is not admin in its ACL" + ) + self.log.append(f"login ok as admin (attempt {attempt + 1})") + return True + raise LinkError("login refused or no reply (wrong password, or not in the ACL)") + + # ── CLI ───────────────────────────────────────────────────────────────── + + def _from_target(self, msg): + pfx = (msg.get("pubkey_prefix") or "").lower() + return bool(pfx) and self.target_pk.startswith(pfx) + + async def cli(self, cmd, expect): + """Send one CLI command and return the reply text that matches `expect` (regex). + + A reply that does not match (a late answer to an earlier command, or + another node) is drained and the command is resent, up to `retries`. + """ + # never log a secret the command carries (the trace is returned to Ansible) + shown = cmd + for secret_cmd in ("password ", "ble pin "): + if cmd.startswith(secret_cmd): + shown = secret_cmd + "***" + for attempt in range(1 + self.retries): + self.inbox.clear() + if self.companion: + await self.send_cli_command(cmd) + else: + await self.mc.commands.send_cmd(self.contact, cmd) + deadline = time.monotonic() + self.reply_timeout + while time.monotonic() < deadline: + for msg in list(self.inbox): + text = (msg.get("text") or "").strip() + if self._from_target(msg) and re.search(expect, text): + self.log.append(f"$ {shown} -> {self._redact(text)}") + # The reply carries the NODE's clock: what fw_facts reports as skew. + self.last_reply_ts = msg.get("sender_timestamp") + self.last_reply_at = time.time() + await asyncio.sleep(0.5) # let a straggler land before the next command + return text + await asyncio.sleep(0.3) + seen = [self._redact((m.get("text") or "").strip()) for m in self.inbox] + self.log.append(f"$ {shown} -> no matching reply (attempt {attempt + 1}, got {seen})") + raise LinkError(f"no reply matching /{expect}/ to `{shown}`") + + async def send_cli_command(self, cmd): + """CMD_SEND_TXT_MSG with txt_type 3 -- what a companion's remote CLI answers.""" + data = ( + b"\x02\x03\x00" + int(time.time()).to_bytes(4, "little") + bytes.fromhex(self.target_pk[:12]) + cmd.encode() + ) + ev = await self.mc.commands.send(data, [EventType.MSG_SENT, EventType.ERROR]) + if ev is not None and ev.type == EventType.ERROR: + raise LinkError(f"companion refused to send `{cmd}`: {ev.payload}") + + def name(self): + return (self.contact or {}).get("adv_name") or "" + + def _redact(self, text): + return text.replace(self.password, "***") if self.password else text + + async def get(self, key): + """`get ` -> the value string (reply is '> value').""" + text = await self.cli(f"get {key}", r"^(>|Err|\?)") + if not text.startswith(">"): + raise LinkError(f"`get {key}`: {text}") + return text[1:].strip() + + async def acl(self): + """Real ACL as {prefix12: perm}, via the binary access-list request.""" + for attempt in range(1 + self.retries): + res = await self.mc.commands.req_acl_sync(self.contact, timeout=40) + if res is not None: + return {e["key"].lower(): e["perm"] for e in res} + self.log.append(f"ACL request: no reply (attempt {attempt + 1})") + raise LinkError("ACL request: no reply") + + +def run(coro): + return asyncio.run(coro) diff --git a/plugins/module_utils/meshcore_plan.py b/plugins/module_utils/meshcore_plan.py new file mode 100644 index 0000000..ff4dbf0 --- /dev/null +++ b/plugins/module_utils/meshcore_plan.py @@ -0,0 +1,279 @@ +"""Pure planning logic of the tth.meshcore modules -- no radio, unit-tested.""" + +import re + +PERM_ADMIN = 3 + +# Prefs that can cut the node off (or are gated to the local console anyway). +# The prefs module refuses them; change them on site. +DANGEROUS_PREFS = {"freq", "radio", "bw", "sf", "cr", "prv.key", "password", "guest.password"} + + +# ── ACL ────────────────────────────────────────────────────────────────────── + + +def plan_acl(current, desired, exclusive=True, keep=()): + """current: {prefix12: perm} as the repeater reports it (6-byte prefixes). + desired: [64-hex pubkey]. keep: pubkeys that must never be removed. + + -> (add, remove): add = full pubkeys to setperm 3 (missing or not admin), + remove = 12-hex prefixes to setperm 0 (only when exclusive). + """ + want = {pk.lower()[:12]: pk.lower() for pk in desired} + add = [full for pfx, full in want.items() if current.get(pfx) != PERM_ADMIN] + keep_pfx = {pk.lower()[:12] for pk in keep} + remove = [pfx for pfx in current if exclusive and pfx not in want and pfx not in keep_pfx] + return sorted(add), sorted(remove) + + +# ── regions ────────────────────────────────────────────────────────────────── + +REGION_LINE = re.compile(r"^(?P *)(?P[^\s^]+)(?P\^)?(?:\s+(?P\S+))?\s*$") +# CommonCLI exports the region list into a 160-byte reply: a tree that does not +# fit is cut mid-name and cannot be managed from it. +REGION_REPLY_LIMIT = 159 + + +def parse_regions(text): + """`region` reply -> {name: {"parent": name|None, "flood": bool, "home": bool}}. + + * F + cz F + cz-ulk^ F + cs F + + One space of indent per level under the wildcard root '*'. 'F' = flood + allowed; '^' after the name = home region. + """ + regions, stack = {}, [] + for raw in text.replace("\r", "").split("\n"): + if not raw.strip(): + continue + m = REGION_LINE.match(raw) + if not m: + raise ValueError(f"unparsable region line: {raw!r}") + depth = len(m.group("indent")) + stack = stack[:depth] + name = m.group("name") + regions[name] = { + "parent": stack[-1] if stack else None, + "flood": "F" in (m.group("flags") or ""), + "home": bool(m.group("home")), + } + stack.append(name) + return regions + + +def region_reply_truncated(text): + return len(text) >= REGION_REPLY_LIMIT - 4 + + +def plan_regions(current, desired, home=None): + """desired: [{"name", "parent" (default "*"), "flood" (default True)}]. + + -> list of CLI commands, in an order the firmware accepts (parents first + on put, children first on remove), without `region save`. + """ + cmds = [] + want = {r["name"]: {"parent": r.get("parent") or "*", "flood": r.get("flood", True)} for r in desired} + # remove what is not wanted, deepest first + + def depth(name, tree): + d = 0 + while tree.get(name, {}).get("parent"): + name = tree[name]["parent"] + d += 1 + return d + + for name in sorted((n for n in current if n != "*" and n not in want), key=lambda n: -depth(n, current)): + cmds.append(f"region remove {name}") + # put new or re-parented ones, shallowest first + for name in sorted( + want, key=lambda n: depth(n, {**{k: {"parent": v["parent"]} for k, v in want.items()}, "*": {"parent": None}}) + ): + cur = current.get(name) + if cur is None or (cur["parent"] or "*") != want[name]["parent"]: + parent = want[name]["parent"] + cmds.append(f"region put {name}" + ("" if parent == "*" else f" {parent}")) + cur = None + if (cur is None and not want[name]["flood"]) or (cur is not None and cur["flood"] != want[name]["flood"]): + cmds.append(f"region {'allowf' if want[name]['flood'] else 'denyf'} {name}") + if home is not None: + cur_home = next((n for n, r in current.items() if r["home"]), None) + if cur_home != home: + cmds.append(f"region home {home}") + return cmds + + +def render_regions(tree): + """Inverse of parse_regions, in the firmware's order (children after their + parent, siblings in tree order) -- used to show the expected tree in --diff.""" + lines = [] + + def walk(name, depth): + r = tree[name] + lines.append(" " * depth + name + ("^" if r.get("home") else "") + (" F" if r.get("flood", True) else "")) + for child in [n for n, c in tree.items() if c.get("parent") == name]: + walk(child, depth + 1) + + walk("*", 0) + return "\n".join(lines) + "\n" + + +def expected_tree(current, desired, home=None): + """The tree plan_regions() is going to produce from `current`.""" + tree = { + "*": { + "parent": None, + "flood": current.get("*", {}).get("flood", True), + "home": current.get("*", {}).get("home", False), + } + } + for r in desired: + cur = current.get(r["name"], {}) + tree[r["name"]] = { + "parent": r.get("parent") or "*", + "flood": r.get("flood", True), + "home": cur.get("home", False), + } + if home is not None: + for n, node in tree.items(): + node["home"] = n == home + return tree + + +# ── prefs ──────────────────────────────────────────────────────────────────── + + +def same_value(current, desired): + """Compare a `get` reply with the desired value: numbers numerically + (869.4320068 == 869.432), on/off/true/false/1/0 as booleans, rest as text.""" + c, d = str(current).strip(), str(desired).strip() + bools = {"on": True, "true": True, "1": True, "off": False, "false": False, "0": False} + if c.lower() in bools and d.lower() in bools: + return bools[c.lower()] == bools[d.lower()] + try: + return abs(float(c) - float(d)) < 1e-3 + except ValueError: + return c == d + + +# ── channel-hash deny list (`filter hash`, MeshCore 22fa0659+) ─────────────── + +FILTER_HASH_REPLY = re.compile( + r"^filter hash: dropped (?P\d+)(?:, passed (?P\d+))?, deny:(?P.*)$" +) + + +def parse_filter_hash(text): + """`filter hash` reply -> (entries, dropped counter). An entry is `43` + (blocked) or `43/60` (throttled to one packet per 60 s, meshcore-tth firmware). + None = the firmware does not know the command (older build).""" + m = FILTER_HASH_REPLY.match(text.strip()) + if not m: + return None + items = [] if "(nic)" in m["list"] else m["list"].split() + return [norm_entry(h) for h in items], int(m["dropped"]) + + +FAIR_ADVERT_REPLY = re.compile( + r"^advert window (?P\d+)h(?P DRY-RUN)?, held (?P\d+) \((?P\d+)s air\), " + r"cache (?P\d+)/(?P\d+), evicted (?P\d+)$" +) +FAIR_DRY_REPLY = re.compile(r"^(?:OK - )?fairness dry-run (?Pon|off)$") + + +def parse_fairness_advert(text): + """`fairness advert` reply -> dict (hours, dry_run, held, air_s, cache, evicted). + None = the firmware has no advert window (before MeshCore 39031b18).""" + m = FAIR_ADVERT_REPLY.match(text.strip()) + if not m: + return None + return { + "hours": int(m["hours"]), + "dry_run": bool(m["dry"]), + "held": int(m["held"]), + "air_s": int(m["air"]), + "cache": int(m["count"]), + "evicted": int(m["evicted"]), + } + + +def parse_fairness_dry(text): + """`fairness dryrun [on|off]` reply -> bool, None = command unknown.""" + m = FAIR_DRY_REPLY.match(text.strip()) + return None if not m else m["state"] == "on" + + +FILTER_AGE_REPLY = re.compile( + r"^(?:OK - )?filter age (?:off|(?P\d+)m(?P DRY-RUN)?(?P \(clock not set, inactive\))?), " + r"dropped (?P\d+)$" +) +FILTER_DRY_REPLY = re.compile(r"^(?:OK - )?filter dry-run (?Pon|off)$") + + +def parse_filter_age(text): + """`filter age [|off]` reply -> dict (minutes 0 = off, dry_run, clock_unset, + dropped). None = the firmware has no age limit (before MeshCore a7336790).""" + m = FILTER_AGE_REPLY.match(text.strip()) + if not m: + return None + return { + "minutes": int(m["min"] or 0), + "dry_run": bool(m["dry"]), + "clock_unset": bool(m["unset"]), + "dropped": int(m["dropped"]), + } + + +def parse_filter_dry(text): + """`filter dryrun [on|off]` reply -> bool, None = command unknown.""" + m = FILTER_DRY_REPLY.match(text.strip()) + return None if not m else m["state"] == "on" + + +def norm_hash(value): + """`43`, `0x43`, 67 -> `43`.""" + if isinstance(value, int): + n = value + else: + s = str(value).strip().lower() + n = int(s.removeprefix("0x"), 16) + if not 0 <= n <= 0xFF: + raise ValueError(f"channel hash out of range: {value!r}") + return f"{n:02X}" + + +def norm_entry(value): + """`43`, `0x43`, 67 -> `43` (block); `43/60`, `0x43/60` -> `43/60` (throttle); + `43/0` is a block, so `43`.""" + if isinstance(value, int): + return norm_hash(value) + h, _sep, secs = str(value).strip().partition("/") + if not secs: + return norm_hash(h) + n = int(secs) + if not 0 <= n <= 65535: + raise ValueError(f"throttle interval out of range: {value!r}") + return norm_hash(h) if n == 0 else f"{norm_hash(h)}/{n}" + + +def entry_hash(entry): + return entry.partition("/")[0] + + +def filter_hash_cmd(entry, delete=False): + h, _sep, secs = entry.partition("/") + if delete: + return f"filter hash del {h}" + return f"filter hash add {h} {secs}" if secs else f"filter hash add {h}" + + +def plan_filter_hash(current, desired, exclusive=True): + """-> (add, remove) of entries. A listed byte whose interval changes is + re-added (firmware updates it in place), never deleted first.""" + want = list(dict.fromkeys(norm_entry(h) for h in desired)) + want_hashes = {entry_hash(e) for e in want} + add = [e for e in want if e not in current] + remove = [e for e in current if exclusive and entry_hash(e) not in want_hashes] + return add, remove diff --git a/plugins/modules/meshcore_acl.py b/plugins/modules/meshcore_acl.py new file mode 100644 index 0000000..99eab73 --- /dev/null +++ b/plugins/modules/meshcore_acl.py @@ -0,0 +1,130 @@ +# Copyright: (c) 2026, TeTeHacko +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +DOCUMENTATION = r""" +module: meshcore_acl +short_description: Admin ACL of a MeshCore repeater, over RF through a companion +author: TeTeHacko (@TeTeHacko) +description: + - Reads the repeater's real ACL with the binary access-list request (the only + way to see it remotely; `get acl` prints to the node's USB serial), then sends + `setperm 3` for missing admins and, with I(exclusive), `setperm 0` + for everything else. Reads the ACL back afterwards and fails on a mismatch. + - The companion this runs through must stay admin, otherwise the next run could + not log in. It is kept even when not listed in I(admins). +options: + transport: + description: + - "Companion to talk through: C({type: tcp, host, port}), C({type: serial, port, baud}) + or C({type: ble, address})." + - A BLE companion must already be bonded on the host the module runs on + (C(bluetoothctl pair)); there is no PIN option, so it never lands in a log. + While the module holds the link, the companion is not reachable from a phone. + - C(expect_freq) (MHz) refuses to send anything when the companion is on another + frequency; C(retries) and C(reply_timeout) tune the RF exchange. + type: dict + required: true + target: + description: Full 64-hex pubkey of the repeater. + type: str + required: true + password: + description: Admin password. Empty = blank login, works for a companion already in the ACL. + type: str + default: "" + admins: + description: Full 64-hex pubkeys that must be admin. + type: list + elements: str + required: true + exclusive: + description: Remove every ACL entry that is not in I(admins). + type: bool + default: true +""" + +EXAMPLES = r""" +- name: Exactly these admins + tth.meshcore.meshcore_acl: + transport: {type: tcp, host: 127.0.0.1, port: 5000} + target: "{{ mc_target }}" + password: "{{ vault_meshcore_admin_password }}" + admins: + - "{{ managing_companion_pubkey }}" + - "{{ my_phone_pubkey }}" +""" + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import ( + HAS_MESHCORE, + HEX64, + Link, + LinkError, + run, +) +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import PERM_ADMIN, plan_acl + + +async def work(module, link): + p = module.params + await link.open() + try: + await link.login() + before = await link.acl() + me = link.self_pubkey() + add, remove = plan_acl(before, p["admins"], p["exclusive"], keep=[me]) + add_pfx = {a[:12] for a in add} + expected = (set(before) - set(remove)) | add_pfx + result = { + "changed": bool(add or remove), + "add": add, + "remove": remove, + "diff": { + "before": "".join(f"{k} {before[k]}\n" for k in sorted(before)), + "after": "".join(f"{k} {PERM_ADMIN if k in add_pfx else before[k]}\n" for k in sorted(expected)), + }, + } + if module.check_mode or not result["changed"]: + return result + for pk in add: + await link.cli(f"setperm {pk} {PERM_ADMIN}", r"^(OK|Err)") + for pfx in remove: + # a prefix that is gone already answers "Err - invalid params": fine + await link.cli(f"setperm {pfx} 0", r"^(OK|Err)") + after = await link.acl() + left_add, left_remove = plan_acl(after, p["admins"], p["exclusive"], keep=[me]) + if left_add or left_remove: + raise LinkError(f"ACL after apply still differs: missing {left_add}, extra {left_remove}") + result["acl"] = after + return result + finally: + await link.close() + + +def main(): + module = AnsibleModule( + argument_spec={ + "transport": {"type": "dict", "required": True}, + "target": {"type": "str", "required": True}, + "password": {"type": "str", "default": "", "no_log": True}, + "admins": {"type": "list", "elements": "str", "required": True}, + "exclusive": {"type": "bool", "default": True}, + }, + supports_check_mode=True, + ) + if not HAS_MESHCORE: + module.fail_json(msg=missing_required_lib("meshcore")) + admins = [a.lower() for a in module.params["admins"]] + bad = [a for a in admins if not HEX64.match(a)] + if bad: + module.fail_json(msg=f"admins must be full 64-hex pubkeys: {bad}") + module.params["admins"] = admins + link = Link(module.params["transport"], module.params["target"], module.params["password"]) + try: + result = run(work(module, link)) + except LinkError as e: + module.fail_json(msg=str(e), log=link.log) + module.exit_json(log=link.log, **result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/meshcore_ble.py b/plugins/modules/meshcore_ble.py new file mode 100644 index 0000000..fc868bb --- /dev/null +++ b/plugins/modules/meshcore_ble.py @@ -0,0 +1,172 @@ +# Copyright: (c) 2026, TeTeHacko +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +DOCUMENTATION = r""" +module: meshcore_ble +short_description: BLE on/off, own BLE PIN and connection tx power of a MeshCore repeater, over RF +author: TeTeHacko (@TeTeHacko) +description: + - Commands of the meshcore-tth firmware (examples/simple_repeater/main.cpp), which have no + `get`/`set` form, so meshcore_prefs cannot manage them. Both are persistent on + the node (marker files in InternalFS) and survive a reboot AND a reflash. + - C(state) reads `ble` and sends `ble on|off` when it differs. The switch is + applied 1.5 s after the reply, so the RF reply still goes out. + - C(conn_tx_power) reads `blepwr` and sends `blepwr `; the reply must say + `saved`. It sets the CONNECTION power only -- advertising is fixed at 8 dBm. + A node already on the wanted value is left alone even when that value is only + the build default (not pinned); `blepwr` cannot tell the two apart. + - C(pin) sets the node's own BLE PIN with `ble pin`. The BLE console has no + login of its own, only this PIN, and a public build ships the placeholder + 123456 (it refuses `ble on` until another PIN is set). The firmware never + prints the PIN, only whether it is C(own) or C(build default), so the module + sends it only when the node reports C(build default) -- or with C(pin_force). + Every `ble pin` clears the node's bonds, so every paired device has to pair + again; that is why it is not sent on every run. + - The PIN goes over RF encrypted to the node like any admin command and is + masked in the returned log. + - Never turns BLE off as a side effect; with no option it only reports. +options: + transport: {description: Companion to talk through (see meshcore_acl)., type: dict, required: true} + target: {description: Full 64-hex pubkey of the repeater., type: str, required: true} + password: {description: Admin password (empty = blank login)., type: str, default: ""} + state: {description: Wanted BLE state., type: str, choices: ["on", "off"]} + conn_tx_power: + description: Wanted connection tx power in dBm (-40,-20,-16,-12,-8,-4,0,2..8). + type: int + pin: + description: + - Own BLE PIN, six digits. Sent when the node still has the build's PIN, + or always with I(pin_force). Keep it in ansible-vault. + - Needs meshcore-tth with `ble pin` (releases after tth-654d53f3). + type: str + pin_force: + description: + - Send I(pin) even when the node already has an own PIN (to change it). + Clears the node's bonds every time, so it is not idempotent -- use it + for one run, not in a playbook that runs regularly. + type: bool + default: false +""" + +EXAMPLES = r""" +- name: BLE console off, connection power 8 dBm + tth.meshcore.meshcore_ble: + transport: {type: tcp, host: 127.0.0.1, port: 5000} + target: "{{ mc_target }}" + password: "{{ vault_meshcore_admin_password }}" + state: "off" + conn_tx_power: 8 + +- name: Own BLE PIN first, then the console on + tth.meshcore.meshcore_ble: + transport: {type: tcp, host: 127.0.0.1, port: 5000} + target: "{{ mc_target }}" + password: "{{ vault_meshcore_admin_password }}" + pin: "{{ vault_meshcore_ble_pin }}" + state: "on" +""" + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_fw import ( + BLE_CONN_TX_VALID, + ble_pin_valid, + blepwr_set_ok, + parse_ble, + parse_ble_pin, + parse_blepwr, +) +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, Link, LinkError, run + + +async def read(link): + ble = await link.cli("ble", r"^BLE: ") + return { + "state": parse_ble(ble), + "pin": parse_ble_pin(ble), + "conn_tx_power": parse_blepwr(await link.cli("blepwr", r"^BLE conn tx: ")), + } + + +async def work(module, link): + want = {k: module.params[k] for k in ("state", "conn_tx_power") if module.params[k] is not None} + await link.open() + try: + await link.login() + before = await read(link) + changes = {k: v for k, v in want.items() if before[k] != v} + if module.params["pin"] is not None: + if before["pin"] is None: + raise LinkError("the firmware has no `ble pin` (meshcore-tth after tth-654d53f3 needed)") + if before["pin"] != "own" or module.params["pin_force"]: + # the value itself never goes into the result, only the status + changes["pin"] = "own" + result = { + "changed": bool(changes), + "before": before, + "set": changes, + "diff": { + "before": "".join(f"{k}: {before[k]}\n" for k in sorted(changes)), + "after": "".join(f"{k}: {changes[k]}\n" for k in sorted(changes)), + }, + } + if module.check_mode or not changes: + return result + if "pin" in changes: + # first, so a following `ble on` is not refused for the default PIN + reply = await link.cli(f"ble pin {module.params['pin']}", r"^(OK|ERR)") + if not reply.startswith("OK"): + raise LinkError(f"`ble pin ***`: {reply}") + if "conn_tx_power" in changes: + reply = await link.cli(f"blepwr {changes['conn_tx_power']}", r"^(OK|ERR)") + if not blepwr_set_ok(reply): + raise LinkError(f"`blepwr {changes['conn_tx_power']}`: {reply}") + if "state" in changes: + reply = await link.cli(f"ble {changes['state']}", r"^(OK|ERR|Err|\?)") + if reply.startswith("ERR - set your own PIN"): + raise LinkError("`ble on` refused: the node still has the build's placeholder PIN -- give it `pin`") + if not reply.startswith("OK"): + raise LinkError(f"`ble {changes['state']}`: {reply}") + after = await read(link) + bad = {k: after[k] for k in changes if after[k] != changes[k]} + if bad.get("pin") == "build default": + raise LinkError("`ble pin` answered OK but the node reports the build default: `pin` is the build's PIN") + if bad: + raise LinkError(f"answered OK but reads back {bad}") + result["after"] = after + return result + finally: + await link.close() + + +def main(): + module = AnsibleModule( + argument_spec={ + "transport": {"type": "dict", "required": True}, + "target": {"type": "str", "required": True}, + "password": {"type": "str", "default": "", "no_log": True}, + "state": {"type": "str", "choices": ["on", "off"]}, + "conn_tx_power": {"type": "int"}, + "pin": {"type": "str", "no_log": True}, + "pin_force": {"type": "bool", "default": False}, + }, + supports_check_mode=True, + ) + if not HAS_MESHCORE: + module.fail_json(msg=missing_required_lib("meshcore")) + pin = module.params["pin"] + if pin is not None and not ble_pin_valid(pin): + module.fail_json(msg="pin must be exactly six digits") + if module.params["pin_force"] and pin is None: + module.fail_json(msg="pin_force needs pin") + p = module.params["conn_tx_power"] + if p is not None and p not in BLE_CONN_TX_VALID: + module.fail_json(msg=f"conn_tx_power {p}: the nRF52840 takes {sorted(BLE_CONN_TX_VALID)}") + link = Link(module.params["transport"], module.params["target"], module.params["password"]) + try: + result = run(work(module, link)) + except (LinkError, ValueError) as e: + module.fail_json(msg=str(e), log=link.log) + module.exit_json(log=link.log, **result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/meshcore_companion_acl.py b/plugins/modules/meshcore_companion_acl.py new file mode 100644 index 0000000..1fd1ffc --- /dev/null +++ b/plugins/modules/meshcore_companion_acl.py @@ -0,0 +1,217 @@ +# Copyright: (c) 2026, TeTeHacko +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +DOCUMENTATION = r""" +module: meshcore_companion_acl +short_description: Remote-CLI ACL of a MeshCore companion (contact flag 0x10), over its BLE link +author: TeTeHacko (@TeTeHacko) +description: + - A companion (fw 1.18+, Solo 2.0+) runs a CLI command that arrives as + TXT_TYPE_CLI_COMMAND only from a contact flagged "remote CLI" + (ContactInfo flags bit 0x10). That flag IS its ACL, and the remote CLI can + do everything (radio, name, PIN, reboot), so the set is converged exactly + like a repeater's ACL - the listed keys get it, every other contact loses it. + - Flags live on the companion and can only be changed over its own link, so + this runs on a host with BLE in range (bleak, NUS, one write = one frame) and + needs a bond with the node. A listed key the companion does not know is + added as a chat contact; when its table is full, the contact heard longest + ago that is neither a favourite nor in the list is removed to make room + (what the firmware's own auto-add does) and reported in C(evicted). + - Each contact is read, only its flags byte changed, and written back + (CMD_ADD_UPDATE_CONTACT takes the CONTACT frame layout), so path, name and + the other flag bits (favourite, telemetry, Solo's kept route) are kept. +options: + mac: {description: BLE MAC of the companion., type: str, required: true} + admins: {description: Pubkeys (64 hex) that get remote CLI., type: list, elements: str, required: true} + names: {description: pubkey -> name for contacts that have to be added., type: dict, default: {}} + timeout: {description: Seconds for the whole BLE session., type: int, default: 120} +""" + +EXAMPLES = r""" +- name: Remote CLI only for these keys + tth.meshcore.meshcore_companion_acl: + mac: "AA:BB:CC:DD:EE:FF" + admins: + - "{{ my_phone_pubkey }}" + names: + "{{ my_phone_pubkey }}": my-phone +""" +import asyncio +import re +import struct + +from ansible.module_utils.basic import AnsibleModule + +try: + from bleak import BleakClient + + HAS_BLEAK = True +except ImportError: + HAS_BLEAK = False + +RX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e" +TX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e" +CMD_APP_START = 1 +CMD_GET_CONTACTS = 4 +CMD_ADD_UPDATE_CONTACT = 9 +CMD_REMOVE_CONTACT = 15 +ERR_TABLE_FULL = 3 +FLAG_FAV = 0x01 +RESP_OK = 0 +RESP_ERR = 1 +RESP_CONTACTS_START = 2 +RESP_CONTACT = 3 +RESP_END = 4 +RESP_SELF_INFO = 5 +FLAG_REMOTE_CLI = 0x10 +HEX64 = re.compile(r"^[0-9a-f]{64}$") +# CONTACT frame: code pub[32] type flags out_path_len out_path[64] name[32] +# last_advert[4] lat[4] lon[4] lastmod[4] +OFF_FLAGS = 1 + 32 + 1 +OFF_NAME = 1 + 32 + 3 + 64 +OFF_LAST_ADVERT = OFF_NAME + 32 +CONTACT_LEN = 1 + 32 + 3 + 64 + 32 + 16 + + +class Ble: + def __init__(self, client): + self.c = client + self.q = asyncio.Queue() + + async def start(self): + await self.c.start_notify(TX, lambda _, d: self.q.put_nowait(bytes(d))) + + async def send(self, frame, want, timeout=10): + await self.c.write_gatt_char(RX, frame, response=True) + while True: + f = await asyncio.wait_for(self.q.get(), timeout) + if f and f[0] in want: + return f + + +def new_contact_frame(pubkey, name, flags): + nm = name.encode()[:31].ljust(32, b"\0") + return ( + bytes([CMD_ADD_UPDATE_CONTACT]) + + bytes.fromhex(pubkey) + + bytes([1, flags, 0xFF]) + + bytes(64) + + nm + + struct.pack("= CONTACT_LEN - 4: + contacts[f[1:33].hex()] = f + plan = [] # (pubkey, name, old_flags or None, new_flags) + for pk, f in contacts.items(): + has = bool(f[OFF_FLAGS] & FLAG_REMOTE_CLI) + if has != (pk in want): + plan.append( + ( + pk, + f[OFF_NAME : OFF_NAME + 32].split(b"\0")[0].decode(errors="replace") or pk[:8], + f[OFF_FLAGS], + f[OFF_FLAGS] ^ FLAG_REMOTE_CLI, + ) + ) + for pk, name in want.items(): + if pk not in contacts and pk != self_pub: + plan.append((pk, name, None, FLAG_REMOTE_CLI)) + evicted = [] + + def victim(): + cands = [ + (struct.unpack_from(" +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +DOCUMENTATION = r""" +module: meshcore_fairness +short_description: Per-origin advert window and fairness dry-run of a MeshCore repeater, over RF +author: TeTeHacko (@TeTeHacko) +description: + - Reads `fairness advert` and `fairness dryrun`, sends only what differs and + reads both again to prove it took (meshcore-tth firmware). + - The advert window forwards each origin's flood advert at most once per + C(advert_hours) (0 = off). Dry-run counts every verdict of the window and + of the FairnessLimiter buckets but forwards anyway -- for sizing a setting + on a live mast against CoreScope before it bites. + - The counters (held, airtime, cache use, evictions) are returned as + C(stats); they live in RAM and restart from zero on every reboot. + - A node whose firmware does not know the commands is reported as skipped + (flash it first) instead of failing the run. +options: + transport: {description: Companion to talk through (see meshcore_acl)., type: dict, required: true} + target: {description: Full 64-hex pubkey of the repeater., type: str, required: true} + password: {description: Admin password (empty = blank login)., type: str, default: ""} + advert_hours: + description: Advert window in hours, 0-720; 0 = off. Omit to leave it alone. + type: int + dry_run: + description: Count but do not shed. Omit to leave it alone. + type: bool +""" + +EXAMPLES = r""" +- name: One flood advert per origin and 12 h, counted only + tth.meshcore.meshcore_fairness: + transport: {type: tcp, host: 127.0.0.1, port: 5000} + target: "{{ mc_target }}" + password: "{{ vault_meshcore_admin_password }}" + advert_hours: 12 + dry_run: true +""" + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, Link, LinkError, run +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import ( + parse_fairness_advert, + parse_fairness_dry, +) + +EXPECT = r"^(advert window|OK - fairness dry-run|fairness dry-run|Err|Unknown|\?)" + + +async def read(link): + adv_reply = await link.cli("fairness advert", EXPECT) + adv = parse_fairness_advert(adv_reply) + dry = parse_fairness_dry(await link.cli("fairness dryrun", EXPECT)) if adv is not None else None + return adv, dry, adv_reply + + +async def work(module, link): + want_h, want_dry = module.params["advert_hours"], module.params["dry_run"] + await link.open() + try: + await link.login() + adv, dry, reply = await read(link) + if adv is None or dry is None: + return { + "changed": False, + "skipped": True, + "msg": f"firmware has no advert window ({reply!r}) -- flash it first", + } + cmds = [] + if want_h is not None and adv["hours"] != want_h: + cmds.append(f"fairness advert {want_h}") + if want_dry is not None and dry != want_dry: + cmds.append(f"fairness dryrun {'on' if want_dry else 'off'}") + before = {"advert_hours": adv["hours"], "dry_run": dry} + after = { + "advert_hours": adv["hours"] if want_h is None else want_h, + "dry_run": dry if want_dry is None else want_dry, + } + result = { + "changed": bool(cmds), + "commands": cmds, + "stats": adv, + "diff": {"before": f"{before}\n", "after": f"{after}\n"}, + } + if module.check_mode or not cmds: + return result + for cmd in cmds: + r = await link.cli(cmd, EXPECT) + if r.startswith(("Err", "Unknown", "?")): + raise LinkError(f"`{cmd}`: {r}") + adv, dry, reply = await read(link) + if adv is None or {"advert_hours": adv["hours"], "dry_run": dry} != after: + raise LinkError(f"fairness reads {reply!r} / dry-run {dry}, expected {after}") + result["stats"] = adv + return result + finally: + await link.close() + + +def main(): + module = AnsibleModule( + argument_spec={ + "transport": {"type": "dict", "required": True}, + "target": {"type": "str", "required": True}, + "password": {"type": "str", "default": "", "no_log": True}, + "advert_hours": {"type": "int"}, + "dry_run": {"type": "bool"}, + }, + supports_check_mode=True, + ) + if not HAS_MESHCORE: + module.fail_json(msg=missing_required_lib("meshcore")) + h = module.params["advert_hours"] + if h is not None and not 0 <= h <= 720: + module.fail_json(msg="advert_hours must be 0-720") + link = Link(module.params["transport"], module.params["target"], module.params["password"]) + try: + result = run(work(module, link)) + except LinkError as e: + module.fail_json(msg=str(e), log=link.log) + module.exit_json(log=link.log, **result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/meshcore_filter.py b/plugins/modules/meshcore_filter.py new file mode 100644 index 0000000..ed0f360 --- /dev/null +++ b/plugins/modules/meshcore_filter.py @@ -0,0 +1,124 @@ +# Copyright: (c) 2026, TeTeHacko +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +DOCUMENTATION = r""" +module: meshcore_filter +short_description: Message age limit and filter dry-run of a MeshCore repeater, over RF +author: TeTeHacko (@TeTeHacko) +description: + - Reads `filter age` and `filter dryrun`, sends only what differs and reads + both again to prove it took (meshcore-tth firmware). + - The age limit refuses to forward group texts on the channels the repeater + can decrypt whose sender timestamp is older than C(age_minutes) (0 = off). + It judges the SENDER's clock, so companions without a time sync are + dropped too -- keep it in days. It is inactive while the repeater's own + clock is unset; a clock running ahead is not detected. + - Dry-run counts every verdict of `filter` (channel hash, age, sender names) + but forwards anyway. + - The drop counter is returned as C(stats); it restarts from zero on reboot. + - A node whose firmware does not know the commands is reported as skipped + (flash it first) instead of failing the run. +options: + transport: {description: Companion to talk through (see meshcore_acl)., type: dict, required: true} + target: {description: Full 64-hex pubkey of the repeater., type: str, required: true} + password: {description: Admin password (empty = blank login)., type: str, default: ""} + age_minutes: + description: Age limit in minutes, 0-10080; 0 = off. Omit to leave it alone. + type: int + dry_run: + description: Count but do not drop. Omit to leave it alone. + type: bool +""" + +EXAMPLES = r""" +- name: Drop group texts older than a day + tth.meshcore.meshcore_filter: + transport: {type: tcp, host: 127.0.0.1, port: 5000} + target: "{{ mc_target }}" + password: "{{ vault_meshcore_admin_password }}" + age_minutes: 1440 + dry_run: false +""" + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, Link, LinkError, run +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import parse_filter_age, parse_filter_dry + +EXPECT = r"^(filter age|OK - filter|filter dry-run|Err|Unknown|\?)" + + +async def read(link): + age_reply = await link.cli("filter age", EXPECT) + age = parse_filter_age(age_reply) + dry = parse_filter_dry(await link.cli("filter dryrun", EXPECT)) if age is not None else None + return age, dry, age_reply + + +async def work(module, link): + want_min, want_dry = module.params["age_minutes"], module.params["dry_run"] + await link.open() + try: + await link.login() + age, dry, reply = await read(link) + if age is None or dry is None: + return { + "changed": False, + "skipped": True, + "msg": f"firmware has no message age limit ({reply!r}) -- flash it first", + } + cmds = [] + if want_min is not None and age["minutes"] != want_min: + cmds.append(f"filter age {want_min}" if want_min else "filter age off") + if want_dry is not None and dry != want_dry: + cmds.append(f"filter dryrun {'on' if want_dry else 'off'}") + before = {"age_minutes": age["minutes"], "dry_run": dry} + after = { + "age_minutes": age["minutes"] if want_min is None else want_min, + "dry_run": dry if want_dry is None else want_dry, + } + result = { + "changed": bool(cmds), + "commands": cmds, + "stats": age, + "diff": {"before": f"{before}\n", "after": f"{after}\n"}, + } + if module.check_mode or not cmds: + return result + for cmd in cmds: + r = await link.cli(cmd, EXPECT) + if r.startswith(("Err", "Unknown", "?")): + raise LinkError(f"`{cmd}`: {r}") + age, dry, reply = await read(link) + if age is None or {"age_minutes": age["minutes"], "dry_run": dry} != after: + raise LinkError(f"filter reads {reply!r} / dry-run {dry}, expected {after}") + result["stats"] = age + return result + finally: + await link.close() + + +def main(): + module = AnsibleModule( + argument_spec={ + "transport": {"type": "dict", "required": True}, + "target": {"type": "str", "required": True}, + "password": {"type": "str", "default": "", "no_log": True}, + "age_minutes": {"type": "int"}, + "dry_run": {"type": "bool"}, + }, + supports_check_mode=True, + ) + if not HAS_MESHCORE: + module.fail_json(msg=missing_required_lib("meshcore")) + m = module.params["age_minutes"] + if m is not None and not 0 <= m <= 10080: + module.fail_json(msg="age_minutes must be 0-10080") + link = Link(module.params["transport"], module.params["target"], module.params["password"]) + try: + result = run(work(module, link)) + except LinkError as e: + module.fail_json(msg=str(e), log=link.log) + module.exit_json(log=link.log, **result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/meshcore_filter_hash.py b/plugins/modules/meshcore_filter_hash.py new file mode 100644 index 0000000..7d21159 --- /dev/null +++ b/plugins/modules/meshcore_filter_hash.py @@ -0,0 +1,126 @@ +# Copyright: (c) 2026, TeTeHacko +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +DOCUMENTATION = r""" +module: meshcore_filter_hash +short_description: Channel-hash deny-forward list (`filter hash`) of a MeshCore repeater, over RF +author: TeTeHacko (@TeTeHacko) +description: + - Reads `filter hash`, sends only the difference (`filter hash add|del `) + and reads the list again to prove it took. The repeater then refuses to + FORWARD GRP_TXT/GRP_DATA whose channel byte is listed; reception and + rxlog/pktfeed are untouched (meshcore-tth firmware). + - The hash is one byte, so an entry hits every channel whose key hashes to it. + - A node whose firmware does not know the command is reported as skipped + (flash it first) instead of failing the run. +options: + transport: {description: Companion to talk through (see meshcore_acl)., type: dict, required: true} + target: {description: Full 64-hex pubkey of the repeater., type: str, required: true} + password: {description: Admin password (empty = blank login)., type: str, default: ""} + hashes: + description: + - Channel hash bytes to deny, e.g. C(["43"]). Up to 8 (firmware limit). + - C(43/60) throttles instead of blocking -- one packet of that byte per + 60 s is forwarded (meshcore-tth firmware, `filter hash add 43 60`). + type: list + elements: raw + required: true + exclusive: + description: Remove listed hashes that are not in C(hashes). + type: bool + default: true +""" + +EXAMPLES = r""" +- name: Block channel 0x43, throttle 0x09 to one packet a minute + tth.meshcore.meshcore_filter_hash: + transport: {type: tcp, host: 127.0.0.1, port: 5000} + target: "{{ mc_target }}" + password: "{{ vault_meshcore_admin_password }}" + hashes: ["43", "09/60"] +""" + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, Link, LinkError, run +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import ( + entry_hash, + filter_hash_cmd, + norm_entry, + parse_filter_hash, + plan_filter_hash, +) + +EXPECT = r"^(filter hash:|Err|Unknown|\?)" + + +async def read(link): + reply = await link.cli("filter hash", EXPECT) + return parse_filter_hash(reply), reply + + +async def work(module, link): + await link.open() + try: + await link.login() + parsed, reply = await read(link) + if parsed is None: + return { + "changed": False, + "skipped": True, + "msg": f"firmware does not know `filter hash` ({reply!r}) -- flash it first", + } + current, dropped = parsed + add, remove = plan_filter_hash(current, module.params["hashes"], module.params["exclusive"]) + added = {entry_hash(e) for e in add} + after = [h for h in current if h not in remove and entry_hash(h) not in added] + add + result = { + "changed": bool(add or remove), + "add": add, + "remove": remove, + "dropped": dropped, + "diff": {"before": " ".join(current) + "\n", "after": " ".join(after) + "\n"}, + } + if module.check_mode or not (add or remove): + return result + for cmd in [filter_hash_cmd(h, delete=True) for h in remove] + [filter_hash_cmd(h) for h in add]: + r = await link.cli(cmd, EXPECT) + if not r.startswith("filter hash:"): + raise LinkError(f"`{cmd}`: {r}") + parsed, reply = await read(link) + if parsed is None or sorted(parsed[0]) != sorted(after): + raise LinkError(f"deny list reads {reply!r}, expected {after}") + return result + finally: + await link.close() + + +def main(): + module = AnsibleModule( + argument_spec={ + "transport": {"type": "dict", "required": True}, + "target": {"type": "str", "required": True}, + "password": {"type": "str", "default": "", "no_log": True}, + "hashes": {"type": "list", "elements": "raw", "required": True}, + "exclusive": {"type": "bool", "default": True}, + }, + supports_check_mode=True, + ) + if not HAS_MESHCORE: + module.fail_json(msg=missing_required_lib("meshcore")) + try: + hashes = [norm_entry(h) for h in module.params["hashes"]] + except ValueError as e: + module.fail_json(msg=str(e)) + if len({entry_hash(h) for h in hashes}) != len(set(hashes)): + module.fail_json(msg="one channel hash listed with two different intervals") + if len(set(hashes)) > 8: + module.fail_json(msg="firmware holds at most 8 channel hashes") + link = Link(module.params["transport"], module.params["target"], module.params["password"]) + try: + result = run(work(module, link)) + except LinkError as e: + module.fail_json(msg=str(e), log=link.log) + module.exit_json(log=link.log, **result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/meshcore_fw_facts.py b/plugins/modules/meshcore_fw_facts.py new file mode 100644 index 0000000..ec9bab3 --- /dev/null +++ b/plugins/modules/meshcore_fw_facts.py @@ -0,0 +1,106 @@ +# Copyright: (c) 2026, TeTeHacko +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +DOCUMENTATION = r""" +module: meshcore_fw_facts +short_description: Firmware version of a MeshCore repeater or companion, over RF +author: TeTeHacko (@TeTeHacko) +description: + - Logs in as admin and reads `ver`. A companion (C(companion), fw 1.18+ / + Solo 2.0+) answers `ver` as remote CLI only to a contact in its ACL (the + "remote CLI" flag 0x10, see meshcore_companion_acl); anyone else gets silence. With C(wanted), also says whether the + node is current, outdated, dirty (built from a dirty tree, '+') or unknown. + - Returns C(clock_skew), node clock minus ours in seconds, from the + timestamp on the node's `ver` reply. + - Read-only; runs in check mode too. +options: + transport: {description: Companion to talk through (see meshcore_acl)., type: dict, required: true} + target: {description: Full 64-hex pubkey of the node., type: str, required: true} + name: {description: Name for the contact if the companion has to create it., type: str} + companion: {description: "The target is a companion (remote CLI, ACL = flagged contacts).", type: bool, default: false} + password: {description: Admin password (empty = blank login)., type: str, default: ""} + wanted: {description: The version stamp the node should run (from the built ELF)., type: str} + clock_sync: + description: + - Send `clock sync` first (sets the node clock from our timestamp when it is + behind). A freshly flashed node boots in May 2024, and clients drop + replies stamped that far back. Fire-and-forget, its own reply may be the + one that gets dropped. + type: bool + default: false +""" + +EXAMPLES = r""" +- name: Which firmware runs there + tth.meshcore.meshcore_fw_facts: + transport: {type: tcp, host: 127.0.0.1, port: 5000} + target: "{{ mc_target }}" + password: "{{ vault_meshcore_admin_password }}" + clock_sync: true + register: fw + +- name: Show it + ansible.builtin.debug: + msg: "{{ fw.version }}, clock off by {{ fw.clock_skew | default('?') }} s" +""" +import asyncio + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_fw import fw_state, parse_version +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, Link, LinkError, run + + +async def work(module, link): + await link.open() + try: + if not module.params["companion"]: + await link.login() + if module.params["clock_sync"] and not module.check_mode: + await link.mc.commands.send_cmd(link.contact, "clock sync") + link.log.append("$ clock sync (not waiting for the reply)") + await asyncio.sleep(3) + reply = await link.cli("ver", r"\(Build: ") + finally: + await link.close() + version = parse_version(reply) + out = {"changed": False, "ver": reply, "version": version, "name": link.name()} + # Node clock minus ours, from the timestamp the node put on its `ver` reply: + # costs no extra packet and works for companions too (they have no `clock` + # CLI). Positive = node ahead. Accurate to the reply latency (seconds). + if link.last_reply_ts: + out["clock_skew"] = int(link.last_reply_ts - link.last_reply_at) + if module.params["wanted"]: + out["state"] = fw_state(version, module.params["wanted"]) + return out + + +def main(): + module = AnsibleModule( + argument_spec={ + "transport": {"type": "dict", "required": True}, + "target": {"type": "str", "required": True}, + "password": {"type": "str", "default": "", "no_log": True}, + "wanted": {"type": "str"}, + "clock_sync": {"type": "bool", "default": False}, + "companion": {"type": "bool", "default": False}, + "name": {"type": "str"}, + }, + supports_check_mode=True, + ) + if not HAS_MESHCORE: + module.fail_json(msg=missing_required_lib("meshcore")) + link = Link( + module.params["transport"], + module.params["target"], + module.params["password"], + companion=module.params["companion"], + name=module.params["name"], + ) + try: + result = run(work(module, link)) + except (LinkError, ValueError) as e: + module.fail_json(msg=str(e), log=link.log) + module.exit_json(log=link.log, **result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/meshcore_prefs.py b/plugins/modules/meshcore_prefs.py new file mode 100644 index 0000000..be3fd45 --- /dev/null +++ b/plugins/modules/meshcore_prefs.py @@ -0,0 +1,105 @@ +# Copyright: (c) 2026, TeTeHacko +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +DOCUMENTATION = r""" +module: meshcore_prefs +short_description: CLI prefs (`get`/`set`) of a MeshCore repeater, over RF +author: TeTeHacko (@TeTeHacko) +description: + - For every key, `get `; when it differs from the wanted value, + `set ` and `get` again to prove it took. Numbers compare + numerically, on/off/true/false/1/0 as booleans. + - Refuses keys that can cut the node off or are local-console only + (freq, radio, bw/sf/cr, prv.key, password, guest.password). + - Units are the firmware's, `advert.interval` is MINUTES, `flood.advert.interval` + HOURS (3-168). A value out of range is rejected by the node and the module + fails -- it never leaves a silent `OK` behind. +options: + transport: {description: Companion to talk through (see meshcore_acl)., type: dict, required: true} + target: {description: Full 64-hex pubkey of the repeater., type: str, required: true} + password: {description: Admin password (empty = blank login)., type: str, default: ""} + prefs: + description: "Map of pref key -> wanted value, e.g. C({repeat: on, advert.interval: 120})." + type: dict + required: true +""" + +EXAMPLES = r""" +- name: Two-byte path hash, no zero-hop adverts, flood advert every 47 h + tth.meshcore.meshcore_prefs: + transport: {type: tcp, host: 127.0.0.1, port: 5000} + target: "{{ mc_target }}" + password: "{{ vault_meshcore_admin_password }}" + prefs: + path.hash.mode: 1 + advert.interval: 0 + flood.advert.interval: 47 +""" + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, Link, LinkError, run +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import DANGEROUS_PREFS, same_value + + +def as_cli(value): + if isinstance(value, bool): + return "on" if value else "off" + return str(value) + + +async def work(module, link): + prefs = module.params["prefs"] + await link.open() + try: + await link.login() + before, changes = {}, {} + for key, want in prefs.items(): + before[key] = await link.get(key) + if not same_value(before[key], as_cli(want)): + changes[key] = as_cli(want) + result = { + "changed": bool(changes), + "set": changes, + "diff": { + "before": "".join(f"{k}: {before[k]}\n" for k in sorted(changes)), + "after": "".join(f"{k}: {changes[k]}\n" for k in sorted(changes)), + }, + } + if module.check_mode or not changes: + return result + for key, value in changes.items(): + reply = await link.cli(f"set {key} {value}", r"^(OK|Err|\?)") + if not reply.startswith("OK"): + raise LinkError(f"`set {key} {value}`: {reply}") + now = await link.get(key) + if not same_value(now, value): + raise LinkError(f"`set {key} {value}` answered OK but `get` reads {now!r}") + return result + finally: + await link.close() + + +def main(): + module = AnsibleModule( + argument_spec={ + "transport": {"type": "dict", "required": True}, + "target": {"type": "str", "required": True}, + "password": {"type": "str", "default": "", "no_log": True}, + "prefs": {"type": "dict", "required": True}, + }, + supports_check_mode=True, + ) + if not HAS_MESHCORE: + module.fail_json(msg=missing_required_lib("meshcore")) + bad = sorted(set(module.params["prefs"]) & DANGEROUS_PREFS) + if bad: + module.fail_json(msg=f"refusing prefs that can cut the node off (change them on site): {bad}") + link = Link(module.params["transport"], module.params["target"], module.params["password"]) + try: + result = run(work(module, link)) + except LinkError as e: + module.fail_json(msg=str(e), log=link.log) + module.exit_json(log=link.log, **result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/meshcore_region.py b/plugins/modules/meshcore_region.py new file mode 100644 index 0000000..c60f103 --- /dev/null +++ b/plugins/modules/meshcore_region.py @@ -0,0 +1,139 @@ +# Copyright: (c) 2026, TeTeHacko +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +DOCUMENTATION = r""" +module: meshcore_region +short_description: Region tree, home region and default scope of a MeshCore repeater, over RF +author: TeTeHacko (@TeTeHacko) +description: + - Reads the tree with `region`, puts/removes/re-parents regions and switches + flood allow/deny so the tree matches I(regions) exactly (the wildcard root + `*` always stays), sets the home region and the default scope, then + `region save` -- without it the changes are RAM-only and a reboot drops them. + Reads the tree back and fails on a mismatch. + - The CLI reply is cut at ~160 bytes. A tree whose listing does not fit cannot + be read reliably, so the module refuses to manage it. +options: + transport: {description: Companion to talk through (see meshcore_acl)., type: dict, required: true} + target: {description: Full 64-hex pubkey of the repeater., type: str, required: true} + password: {description: Admin password (empty = blank login)., type: str, default: ""} + regions: + description: Wanted regions, C({name, parent (default "*"), flood (default true)}), names without "#". + type: list + elements: dict + required: true + home: {description: Home region name (omit to leave it)., type: str} + default_scope: {description: "Default flood scope region name, or C(); omit to leave it.", type: str} +""" + +EXAMPLES = r""" +- name: Region tree with a home region + tth.meshcore.meshcore_region: + transport: {type: tcp, host: 127.0.0.1, port: 5000} + target: "{{ mc_target }}" + password: "{{ vault_meshcore_admin_password }}" + regions: + - {name: cz} + - {name: cz-ulk, parent: cz} + home: cz-ulk +""" + +from ansible.module_utils.basic import AnsibleModule, missing_required_lib +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, Link, LinkError, run +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import ( + expected_tree, + parse_regions, + plan_regions, + region_reply_truncated, + render_regions, +) + +EXPECT = { + "put": r"^(OK|Err)", + "remove": r"^(OK|Err)", + "allowf": r"^(OK|Err)", + "denyf": r"^(OK|Err)", + "home": r"(home is now|^Err)", + "default": r"(default scope is now|^Err)", + "save": r"^(OK|Err)", +} + + +async def read_tree(link): + text = await link.cli("region", r"^\*") + if region_reply_truncated(text): + raise LinkError(f"region list is cut at the CLI reply limit ({len(text)} B) -- cannot manage it") + return text, parse_regions(text) + + +def default_wanted(name): + return None if name is None else name.lstrip("#") + + +async def work(module, link): + p = module.params + regions = [ + {**r, "name": r["name"].lstrip("#"), "parent": (r.get("parent") or "*").lstrip("#")} for r in p["regions"] + ] + await link.open() + try: + await link.login() + _text, tree = await read_tree(link) + cmds = plan_regions(tree, regions, p["home"]) + dflt = None + if p["default_scope"] is not None: + reply = await link.cli("region default", r"default scope is") + dflt = reply.split("default scope is", 1)[1].strip().lstrip("#") + if dflt != default_wanted(p["default_scope"]): + cmds.append(f"region default {p['default_scope']}") + want_dflt = default_wanted(p["default_scope"]) + result = { + "changed": bool(cmds), + "commands": cmds, + "diff": { + "before": render_regions(tree) + (f"default scope {dflt}\n" if dflt is not None else ""), + "after": render_regions(expected_tree(tree, regions, p["home"])) + + (f"default scope {want_dflt}\n" if want_dflt is not None else ""), + }, + } + if module.check_mode or not cmds: + return result + for c in cmds: + reply = await link.cli(c, EXPECT[c.split()[1]]) + if reply.startswith("Err"): + raise LinkError(f"`{c}`: {reply}") + reply = await link.cli("region save", EXPECT["save"]) + if not reply.startswith("OK"): + raise LinkError(f"`region save`: {reply}") + _text, after = await read_tree(link) + left = plan_regions(after, regions, p["home"]) + if left: + raise LinkError(f"region tree after apply still differs: {left}") + return result + finally: + await link.close() + + +def main(): + module = AnsibleModule( + argument_spec={ + "transport": {"type": "dict", "required": True}, + "target": {"type": "str", "required": True}, + "password": {"type": "str", "default": "", "no_log": True}, + "regions": {"type": "list", "elements": "dict", "required": True}, + "home": {"type": "str"}, + "default_scope": {"type": "str"}, + }, + supports_check_mode=True, + ) + if not HAS_MESHCORE: + module.fail_json(msg=missing_required_lib("meshcore")) + link = Link(module.params["transport"], module.params["target"], module.params["password"]) + try: + result = run(work(module, link)) + except LinkError as e: + module.fail_json(msg=str(e), log=link.log) + module.exit_json(log=link.log, **result) + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..88a05f2 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +# Python on the host the modules run on (the one with the companion). +meshcore>=2.3 +# meshcore_companion_acl only (BLE link to a companion). +bleak>=0.22 diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..5c87f28 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,6 @@ +line-length = 120 + +[lint.per-file-ignores] +# Ansible requires DOCUMENTATION before the imports (ansible-test validate-modules +# reports an import before it as an error), so the two rules cannot both hold. +"plugins/modules/*.py" = ["E402"] diff --git a/tests/unit/plugins/module_utils/test_meshcore_fw.py b/tests/unit/plugins/module_utils/test_meshcore_fw.py new file mode 100644 index 0000000..a55e69b --- /dev/null +++ b/tests/unit/plugins/module_utils/test_meshcore_fw.py @@ -0,0 +1,88 @@ +"""Unit tests for `ver` and BLE reply parsing. Inputs are real replies.""" + +import pytest +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_fw import ( + ble_pin_valid, + blepwr_set_ok, + fw_state, + parse_ble, + parse_ble_pin, + parse_blepwr, + parse_version, +) + +# a repeater right after a flash +VER = "v1.17.1-tth76685cf (Build: 07 Oct 2026)" + + +# ── versions ──────────────────────────────────────────────────────────────── + + +def test_parse_version_from_ver_reply_and_board_probe(): + assert parse_version(VER) == "v1.17.1-tth76685cf" + assert parse_version("3333333333333333 xiao/text v1.17.1-tthdf35580+") == "v1.17.1-tthdf35580+" + assert parse_version("0123456789ABCDEF xiao/nic -") is None + + +def test_parse_version_solo_companion(): + assert parse_version("v2.0-tthe266e89 (Build: 16 Oct 2026)") == "v2.0-tthe266e89" + assert parse_version("v2.0-rc3-tth8345a5a (Build: x)") == "v2.0-rc3-tth8345a5a" + assert parse_version("v2.0+tth.20261016152233 (Build: x)") == "v2.0+tth.20261016152233" + + +def test_parse_version_old_dashed_stamp(): + assert parse_version("v1.16.0-tth-956238c (Build: x)") == "v1.16.0-tth-956238c" + + +def test_fw_state(): + w = "v1.17.1-tth76685cf" + assert fw_state(w, w) == "current" + assert fw_state("v1.17.1-tthb3b4cd6", w) == "outdated" + assert fw_state(None, w) == "unknown" + + +def test_dirty_node_is_never_current(): + # the same sha with '+' is NOT what we built + assert fw_state("v1.17.1-tth76685cf+", "v1.17.1-tth76685cf") == "dirty" + + +def test_refuses_dirty_wanted(): + with pytest.raises(ValueError): + fw_state("v1.17.1-tth76685cf", "v1.17.1-tth76685cf+") + + +# ── BLE replies ───────────────────────────────────────────────────────────── + + +def test_ble_replies(): + assert parse_ble("BLE: on (advertising)") == "on" + assert parse_ble("BLE: off") == "off" + assert parse_blepwr("BLE conn tx: 0 dBm, adv tx: 8 dBm") == 0 + assert parse_blepwr("BLE conn tx: -4 dBm, adv tx: 8 dBm") == -4 + with pytest.raises(ValueError): + parse_ble("Unknown command") + + +def test_blepwr_must_be_saved(): + assert blepwr_set_ok("OK - BLE conn tx 8 dBm (1/1 conn), saved") + assert not blepwr_set_ok("OK - BLE conn tx 8 dBm (0/0 conn), NOT saved") + assert not blepwr_set_ok("ERR - BLE conn tx 8 dBm (0/1 conn)") + + +def test_stock_meshcore_version(): + assert parse_version("v1.18.0 (Build: 25 Oct 2026)") == "v1.18.0" + assert parse_version("MeshCore v1.18.0 or so") is None # not a `ver` reply + + +def test_ble_pin_status(): + # meshcore-tth c2053768 on a XIAO, 3. 11. 2026 + assert parse_ble("BLE: off, PIN build default") == "off" + assert parse_ble_pin("BLE: off, PIN build default") == "build default" + assert parse_ble_pin("BLE: on (advertising), PIN own") == "own" + assert parse_ble_pin("BLE: on (connected)") is None # firmware without `ble pin` + + +def test_ble_pin_format(): + assert ble_pin_valid("482913") + for bad in ("12345", "1234567", "12a456", "", None, 123456): + assert not ble_pin_valid(bad) diff --git a/tests/unit/plugins/module_utils/test_meshcore_plan.py b/tests/unit/plugins/module_utils/test_meshcore_plan.py new file mode 100644 index 0000000..b73f0ad --- /dev/null +++ b/tests/unit/plugins/module_utils/test_meshcore_plan.py @@ -0,0 +1,248 @@ +"""Unit tests for the radio-free planning logic. Inputs are real replies.""" + +import pytest +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import ( + filter_hash_cmd, + norm_entry, + norm_hash, + parse_fairness_advert, + parse_fairness_dry, + parse_filter_age, + parse_filter_dry, + parse_filter_hash, + parse_regions, + plan_acl, + plan_filter_hash, + plan_regions, + region_reply_truncated, + same_value, +) + +# real `region` reply of a repeater +LTM = "* F\n cz F\n cz-ulk^ F\n cz-sudety F\n cs F\n" +# another repeater (home on the wildcard) +HREB = "*^ F\n cz F\n cz-kvk F\n cs F\n" + +TTH = "a1" * 32 +L1 = "b2" * 32 +SCRAPE2 = "c3" * 32 +TEST2 = "d4" * 32 + + +# ── regions ───────────────────────────────────────────────────────────────── + + +def test_parse_region_tree(): + t = parse_regions(LTM) + assert t["*"] == {"parent": None, "flood": True, "home": False} + assert t["cz-ulk"] == {"parent": "cz", "flood": True, "home": True} + assert t["cs"]["parent"] == "*" + + +def test_parse_home_on_wildcard_and_denied_flood(): + t = parse_regions(HREB + " zz\n") + assert t["*"]["home"] is True + assert t["zz"] == {"parent": "*", "flood": False, "home": False} + + +def test_parse_rejects_garbage(): + with pytest.raises(ValueError): + parse_regions("* F\n a b c d\n") + + +def test_matching_tree_needs_nothing(): + want = [{"name": "cz"}, {"name": "cz-ulk", "parent": "cz"}, {"name": "cz-sudety", "parent": "cz"}, {"name": "cs"}] + assert plan_regions(parse_regions(LTM), want, home="cz-ulk") == [] + + +def test_add_remove_and_order(): + want = [{"name": "cz"}, {"name": "cz-kvk", "parent": "cz"}, {"name": "cs"}, {"name": "eu", "flood": False}] + cmds = plan_regions(parse_regions(LTM), want) + # children removed before parents could be; nothing here removes cz itself + assert "region remove cz-ulk" in cmds and "region remove cz-sudety" in cmds + assert cmds.index("region put cz-kvk cz") > max( + cmds.index("region remove cz-ulk"), cmds.index("region remove cz-sudety") + ) + # put allows flood by default, so a denied region needs denyf after put + assert cmds.index("region denyf eu") == cmds.index("region put eu") + 1 + + +def test_remove_deepest_first(): + cmds = plan_regions(parse_regions(LTM), [{"name": "cs"}]) + assert cmds.index("region remove cz-ulk") < cmds.index("region remove cz") + assert cmds.index("region remove cz-sudety") < cmds.index("region remove cz") + + +def test_put_parent_before_child(): + want = [{"name": "sk-ba", "parent": "sk"}, {"name": "sk"}] + cmds = plan_regions(parse_regions("* F\n"), want) + assert cmds == ["region put sk", "region put sk-ba sk"] + + +def test_flood_flip_and_home(): + want = [{"name": "cz", "flood": False}, {"name": "cz-kvk", "parent": "cz"}, {"name": "cs"}] + assert plan_regions(parse_regions(HREB), want, home="cz-kvk") == ["region denyf cz", "region home cz-kvk"] + + +def test_truncation_detected(): + assert not region_reply_truncated(LTM) + assert region_reply_truncated("x" * 156) + + +# ── ACL ───────────────────────────────────────────────────────────────────── + + +def test_acl_adds_missing_admin(): + current = {L1[:12]: 3, SCRAPE2[:12]: 3} + add, remove = plan_acl(current, [L1, SCRAPE2, TTH]) + assert add == [TTH] and remove == [] + + +def test_acl_removes_unknown_and_wrong_perm(): + current = {L1[:12]: 3, "aaaaaaaaaaaa": 3, TTH[:12]: 1} + add, remove = plan_acl(current, [L1, TTH]) + assert add == [TTH] # present, but not admin + assert remove == ["aaaaaaaaaaaa"] + + +def test_acl_non_exclusive_keeps_extras(): + assert plan_acl({"aaaaaaaaaaaa": 3}, [L1], exclusive=False) == ([L1], []) + + +def test_acl_keeps_the_managing_identity(): + # the companion the module runs through must never lock itself out + _add, remove = plan_acl({TEST2[:12]: 3, L1[:12]: 3}, [L1], keep=[TEST2]) + assert remove == [] + + +# ── prefs ─────────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + "cur,want,same", + [ + ("869.4320068", "869.432", True), + ("120", 120, True), + ("on", "on", True), + ("on", "off", False), + ("1", "on", True), + ("25", "24", False), + ("my-repeater", "my-repeater", True), + ], +) +def test_same_value(cur, want, same): + assert same_value(cur, want) is same + + +def test_render_roundtrip(): + from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import render_regions + + for text in (LTM, HREB): + assert render_regions(parse_regions(text)) == text + + +def test_expected_tree_matches_plan(): + from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import expected_tree, render_regions + + want = [{"name": "cz"}, {"name": "cz-ulk", "parent": "cz"}, {"name": "cz-kvk", "parent": "cz"}, {"name": "cs"}] + out = render_regions(expected_tree(parse_regions(LTM.replace(" cz-sudety F\n", "")), want)) + assert out == "* F\n cz F\n cz-ulk^ F\n cz-kvk F\n cs F\n" + + +# ── filter hash ───────────────────────────────────────────────────────────── + + +def test_parse_filter_hash_real_replies(): + # bench repeater, 14. 10. 2026 + assert parse_filter_hash("filter hash: dropped 0, deny: (nic)") == ([], 0) + assert parse_filter_hash("filter hash: dropped 1, deny: 43 09") == (["43", "09"], 1) + # older firmware: no command / swallowed by the sender-name filter + assert parse_filter_hash("Unknown command") is None + assert parse_filter_hash("Err - filter [add|del |list|clear]") is None + # meshcore-tth throttle: passed counter + `hash/secs` entries + assert parse_filter_hash("filter hash: dropped 7, passed 2, deny: 43/60 09") == (["43/60", "09"], 7) + assert parse_filter_hash("filter hash: dropped 0, passed 0, deny: (nic)") == ([], 0) + assert parse_filter_hash("Err - filter [add|del |list|clear|hash|age|dryrun]") is None + + +def test_parse_filter_age_real_replies(): + # bench boards, 2. 11. 2026 + assert parse_filter_age("filter age off, dropped 0") == { + "minutes": 0, + "dry_run": False, + "clock_unset": False, + "dropped": 0, + } + assert parse_filter_age("OK - filter age 1440m, dropped 0")["minutes"] == 1440 + assert parse_filter_age("filter age 60m DRY-RUN, dropped 6") == { + "minutes": 60, + "dry_run": True, + "clock_unset": False, + "dropped": 6, + } + assert parse_filter_age("filter age 60m (clock not set, inactive), dropped 0")["clock_unset"] + # older firmware: unknown, or taken by the sender-name filter + assert parse_filter_age("Unknown command") is None + assert parse_filter_age("Err - filter [add|del |list|clear]") is None + + +def test_parse_filter_dry_real_replies(): + assert parse_filter_dry("filter dry-run off") is False + assert parse_filter_dry("OK - filter dry-run on") is True + assert parse_filter_dry("Unknown command") is None + + +def test_norm_entry(): + assert norm_entry("43") == norm_entry(0x43) == "43" + assert norm_entry("0x43/60") == norm_entry(" 43/60 ") == "43/60" + assert norm_entry("43/0") == "43" + with pytest.raises(ValueError): + norm_entry("43/70000") + with pytest.raises(ValueError): + norm_entry("43/abc") + + +def test_filter_hash_cmd(): + assert filter_hash_cmd("43") == "filter hash add 43" + assert filter_hash_cmd("43/60") == "filter hash add 43 60" + assert filter_hash_cmd("43/60", delete=True) == "filter hash del 43" + + +def test_norm_hash(): + assert norm_hash("43") == norm_hash("0x43") == norm_hash(0x43) == "43" + assert norm_hash("9") == "09" + with pytest.raises(ValueError): + norm_hash("143") + + +def test_plan_filter_hash(): + assert plan_filter_hash([], ["43"]) == (["43"], []) + assert plan_filter_hash(["43"], ["0x43"]) == ([], []) + assert plan_filter_hash(["43", "09"], ["43"]) == ([], ["09"]) + assert plan_filter_hash(["43", "09"], ["43"], exclusive=False) == ([], []) + # block -> throttle and back: re-add in place, no delete in between + assert plan_filter_hash(["43"], ["43/60"]) == (["43/60"], []) + assert plan_filter_hash(["43/60"], ["43"]) == (["43"], []) + assert plan_filter_hash(["43/60"], ["0x43/60"]) == ([], []) + + +def test_parse_fairness_real_replies(): + # replies of MeshCore 39031b18 on the bench, 1. 11. 2026 + assert parse_fairness_advert("advert window 24h DRY-RUN, held 0 (0s air), cache 0/256, evicted 0") == { + "hours": 24, + "dry_run": True, + "held": 0, + "air_s": 0, + "cache": 0, + "evicted": 0, + } + assert parse_fairness_advert("advert window 1h, held 10 (8s air), cache 1/256, evicted 0")["held"] == 10 + assert parse_fairness_advert("advert window 0h, held 10 (8s air), cache 1/256, evicted 0")["hours"] == 0 + assert parse_fairness_dry("fairness dry-run on") is True + assert parse_fairness_dry("OK - fairness dry-run off") is False + + +def test_parse_fairness_old_firmware(): + old = "Err - fairness [on|off|grid|cap ...|refill ...]" + assert parse_fairness_advert(old) is None + assert parse_fairness_dry(old) is None