# 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()