nus-logger


Namenus-logger JSON
Version 0.1.0 PyPI version JSON
download
home_pageNone
SummaryAuto-reconnecting Nordic UART Service (NUS) BLE logger.
upload_time2025-09-05 07:27:58
maintainerNone
docs_urlNone
authorSimon M
requires_python>=3.9
licenseMIT License Copyright (c) 2025 Simon M. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords ble nus nordic logging
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <div align="center">

<h1>NUS Logger</h1>

<p><strong>Auto‑reconnecting Nordic UART Service (NUS) BLE log collector for Zephyr / nRF Connect SDK devices.</strong></p>

<!-- Badges -->
<p>
<a href="https://pypi.org/project/nus-logger/"><img alt="PyPI" src="https://img.shields.io/pypi/v/nus-logger.svg?color=1e88e5"></a>
<a href="https://github.com/smnmsr/nus-logger/actions/workflows/publish.yml"><img alt="CI" src="https://github.com/smnmsr/nus-logger/actions/workflows/publish.yml/badge.svg"></a>
<img alt="Python Versions" src="https://img.shields.io/pypi/pyversions/nus-logger.svg">
<a href="https://opensource.org/licenses/MIT"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg"></a>
<img alt="BLE" src="https://img.shields.io/badge/BLE-Nordic%20NUS-1976d2">
<img alt="Status" src="https://img.shields.io/badge/status-beta-blue">
</p>

</div>

---

## ✨ Highlights

- **Zero‑config CLI**: discover, connect, stream logs in one command.
- **Resilient**: automatic reconnect with exponential backoff (capped) & graceful exit.
- **Readable timestamps**: UTC (`--ts`) or local (`--ts-local`).
- **Dual view**: optional raw hex alongside decoded UTF‑8 text (`--raw`).
- **Log persistence**: safe append mode (rotation‑friendly) to any file.
- **Cross‑platform**: Windows / macOS / Linux using native Bluetooth via `bleak`.
- **Library friendly**: small, typed API (`NUSClient`, `NUSLoggerController`).
- **Dependency‑light**: just `bleak` (+ `colorama` on Windows for color support).

## Installation

```bash
pip install nus-logger
```

Requires Python 3.9+.

Upgrade in place:

```bash
pip install -U nus-logger
```

## Quick Start (CLI)

```bash
# 1. Zero-config interactive wizard (scan, pick device, choose options)
nus-logger

# 2. List advertising NUS devices (non-interactive)
nus-logger --list

# 3. Connect by (partial) name, show UTC timestamps, also log to file
nus-logger --name my-device --ts --logfile logs/session.txt

# 4. Show local timestamps and raw hex dump
nus-logger --name my-device --ts-local --raw
```

Module mode (equivalent):

```bash
python -m nus_logger --name my-device --ts
```

Press Ctrl-C to stop; the tool will attempt automatic reconnection until max retries.

## CLI Reference

Environment variables override flags when corresponding flags are omitted.

| Flag                   | Description                         | Env               | Notes                            |
| ---------------------- | ----------------------------------- | ----------------- | -------------------------------- |
| `--wizard`             | Interactive scan & option wizard    | –                 | Default when no args             |
| `--list`               | List visible devices then exit      | –                 | Passive scan only                |
| `--name SUBSTR`        | Match advertising name              | `NUS_NAME`        | Case-insensitive substring       |
| `--filter-addr SUBSTR` | Prefer address containing substring | –                 | Helps disambiguate similar names |
| `--ts` / `--ts-local`  | Add UTC or local timestamps         | –                 | Mutually exclusive               |
| `--raw`                | Show hex bytes before decoded line  | –                 | Two aligned columns              |
| `--logfile PATH`       | Append decoded lines to file        | `NUS_LOGFILE`     | File is created if missing       |
| `--timeout SECS`       | Scan / connect timeout              | `NUS_TIMEOUT`     | Applies to each attempt          |
| `--backoff SECS`       | Initial reconnect backoff           | `NUS_BACKOFF`     | Grows up to 15s cap              |
| `--max-retries N`      | Stop after N failed reconnects      | `NUS_MAX_RETRIES` | Omit to retry indefinitely       |
| `--verbose`            | Dump discovered GATT structure once | –                 | For debugging / inspection       |

<details><summary><strong>Show full help example</strong></summary>

```text
nus-logger --help
```

</details>

## Programmatic Use

```python
import asyncio
from nus_logger.ble_nus import NUSClient

async def main():
	client = NUSClient(name_substring="my-device")
	await client.connect()
	try:
		async for line in client.iter_lines():  # yields decoded UTF-8 log lines
			print(line)
			if "READY" in line:
				await client.write(b"ping\n")  # optional upstream write
	finally:
		await client.disconnect()

asyncio.run(main())
```

See `nus_logger.nus_logger:main` for full CLI orchestration (reconnect logic, backoff, etc.). Higher level automation can use `NUSLoggerController` for managed sessions.

### Minimal Flow (Conceptual)

```text
┌─────────────┐    BLE (NUS)    ┌──────────────┐            ┌─────────────┐
│ Zephyr App  │ ───────────────▶│   Adapter    │────────────▶│  bleak API  │
└─────────────┘                 └──────────────┘            └─────────────┘
	LOG_INF() lines                │                         │
				       ▼                         ▼
			       NUSClient (async)  ──▶  line iterator
				       │
				       ▼
			      NUSLoggerController
				       │
			stdout / hex column / logfile
```

## Typical Workflow (Zephyr / nRF Connect)

To stream the Zephyr logging subsystem over BLE for `nus-logger` to consume you should enable the BLE logging backend with `CONFIG_LOG_BACKEND_BLE=y`. The backend handles formatting, buffering and transport so normal `LOG_INF()/LOG_ERR()` etc. arrive as text lines.

- Additional Kconfig options (buffer sizes, flow control, etc.) may be required for high log volume or long lines; consult the Zephyr sample: https://docs.zephyrproject.org/latest/samples/subsys/logging/ble_backend/README.html

## Troubleshooting

| Situation                        | Hint                                                                        |
| -------------------------------- | --------------------------------------------------------------------------- |
| No devices on Windows            | Toggle Bluetooth off/on or airplane mode, verify advertising.               |
| Linux permission errors          | Ensure user in `bluetooth` group or grant `CAP_NET_RAW` to Python binary.   |
| macOS permission prompt          | Allow Bluetooth access in System Settings > Privacy & Security > Bluetooth. |
| Frequent disconnects             | Reduce distance / interference; backoff resets after ~60s stable link.      |
| Mixed devices with similar names | Use `--filter-addr` to prefer a known address substring.                    |

## Development

```bash
git clone https://github.com/smnmsr/nus-logger.git
cd nus-logger
pip install -e .[dev]
pytest
```

Linting is intentionally minimal; contributions should keep the code small and dependency‑light.

## Versioning & Compatibility

The public surface is the CLI plus the `NUSClient` / `NUSLoggerController` classes. Minor releases may add kwargs/features; removals will occur only in a major bump following semantic versioning principles.

## License

MIT License © 2025 Simon M. See `LICENSE` file for full text.

---

If this saves you time, a ⭐ on GitHub helps others discover it.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "nus-logger",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "BLE, NUS, Nordic, logging",
    "author": "Simon M",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/8c/86/c9a51398bdb332f2563e76d89d310657e016b606e92d9ada4299d47fe1f7/nus_logger-0.1.0.tar.gz",
    "platform": null,
    "description": "<div align=\"center\">\n\n<h1>NUS Logger</h1>\n\n<p><strong>Auto\u2011reconnecting Nordic UART Service (NUS) BLE log collector for Zephyr / nRF Connect SDK devices.</strong></p>\n\n<!-- Badges -->\n<p>\n<a href=\"https://pypi.org/project/nus-logger/\"><img alt=\"PyPI\" src=\"https://img.shields.io/pypi/v/nus-logger.svg?color=1e88e5\"></a>\n<a href=\"https://github.com/smnmsr/nus-logger/actions/workflows/publish.yml\"><img alt=\"CI\" src=\"https://github.com/smnmsr/nus-logger/actions/workflows/publish.yml/badge.svg\"></a>\n<img alt=\"Python Versions\" src=\"https://img.shields.io/pypi/pyversions/nus-logger.svg\">\n<a href=\"https://opensource.org/licenses/MIT\"><img alt=\"License: MIT\" src=\"https://img.shields.io/badge/License-MIT-yellow.svg\"></a>\n<img alt=\"BLE\" src=\"https://img.shields.io/badge/BLE-Nordic%20NUS-1976d2\">\n<img alt=\"Status\" src=\"https://img.shields.io/badge/status-beta-blue\">\n</p>\n\n</div>\n\n---\n\n## \u2728 Highlights\n\n- **Zero\u2011config CLI**: discover, connect, stream logs in one command.\n- **Resilient**: automatic reconnect with exponential backoff (capped) & graceful exit.\n- **Readable timestamps**: UTC (`--ts`) or local (`--ts-local`).\n- **Dual view**: optional raw hex alongside decoded UTF\u20118 text (`--raw`).\n- **Log persistence**: safe append mode (rotation\u2011friendly) to any file.\n- **Cross\u2011platform**: Windows / macOS / Linux using native Bluetooth via `bleak`.\n- **Library friendly**: small, typed API (`NUSClient`, `NUSLoggerController`).\n- **Dependency\u2011light**: just `bleak` (+ `colorama` on Windows for color support).\n\n## Installation\n\n```bash\npip install nus-logger\n```\n\nRequires Python 3.9+.\n\nUpgrade in place:\n\n```bash\npip install -U nus-logger\n```\n\n## Quick Start (CLI)\n\n```bash\n# 1. Zero-config interactive wizard (scan, pick device, choose options)\nnus-logger\n\n# 2. List advertising NUS devices (non-interactive)\nnus-logger --list\n\n# 3. Connect by (partial) name, show UTC timestamps, also log to file\nnus-logger --name my-device --ts --logfile logs/session.txt\n\n# 4. Show local timestamps and raw hex dump\nnus-logger --name my-device --ts-local --raw\n```\n\nModule mode (equivalent):\n\n```bash\npython -m nus_logger --name my-device --ts\n```\n\nPress Ctrl-C to stop; the tool will attempt automatic reconnection until max retries.\n\n## CLI Reference\n\nEnvironment variables override flags when corresponding flags are omitted.\n\n| Flag                   | Description                         | Env               | Notes                            |\n| ---------------------- | ----------------------------------- | ----------------- | -------------------------------- |\n| `--wizard`             | Interactive scan & option wizard    | \u2013                 | Default when no args             |\n| `--list`               | List visible devices then exit      | \u2013                 | Passive scan only                |\n| `--name SUBSTR`        | Match advertising name              | `NUS_NAME`        | Case-insensitive substring       |\n| `--filter-addr SUBSTR` | Prefer address containing substring | \u2013                 | Helps disambiguate similar names |\n| `--ts` / `--ts-local`  | Add UTC or local timestamps         | \u2013                 | Mutually exclusive               |\n| `--raw`                | Show hex bytes before decoded line  | \u2013                 | Two aligned columns              |\n| `--logfile PATH`       | Append decoded lines to file        | `NUS_LOGFILE`     | File is created if missing       |\n| `--timeout SECS`       | Scan / connect timeout              | `NUS_TIMEOUT`     | Applies to each attempt          |\n| `--backoff SECS`       | Initial reconnect backoff           | `NUS_BACKOFF`     | Grows up to 15s cap              |\n| `--max-retries N`      | Stop after N failed reconnects      | `NUS_MAX_RETRIES` | Omit to retry indefinitely       |\n| `--verbose`            | Dump discovered GATT structure once | \u2013                 | For debugging / inspection       |\n\n<details><summary><strong>Show full help example</strong></summary>\n\n```text\nnus-logger --help\n```\n\n</details>\n\n## Programmatic Use\n\n```python\nimport asyncio\nfrom nus_logger.ble_nus import NUSClient\n\nasync def main():\n\tclient = NUSClient(name_substring=\"my-device\")\n\tawait client.connect()\n\ttry:\n\t\tasync for line in client.iter_lines():  # yields decoded UTF-8 log lines\n\t\t\tprint(line)\n\t\t\tif \"READY\" in line:\n\t\t\t\tawait client.write(b\"ping\\n\")  # optional upstream write\n\tfinally:\n\t\tawait client.disconnect()\n\nasyncio.run(main())\n```\n\nSee `nus_logger.nus_logger:main` for full CLI orchestration (reconnect logic, backoff, etc.). Higher level automation can use `NUSLoggerController` for managed sessions.\n\n### Minimal Flow (Conceptual)\n\n```text\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    BLE (NUS)    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510            \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Zephyr App  \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25b6\u2502   Adapter    \u2502\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25b6\u2502  bleak API  \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518                 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518            \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\tLOG_INF() lines                \u2502                         \u2502\n\t\t\t\t       \u25bc                         \u25bc\n\t\t\t       NUSClient (async)  \u2500\u2500\u25b6  line iterator\n\t\t\t\t       \u2502\n\t\t\t\t       \u25bc\n\t\t\t      NUSLoggerController\n\t\t\t\t       \u2502\n\t\t\tstdout / hex column / logfile\n```\n\n## Typical Workflow (Zephyr / nRF Connect)\n\nTo stream the Zephyr logging subsystem over BLE for `nus-logger` to consume you should enable the BLE logging backend with `CONFIG_LOG_BACKEND_BLE=y`. The backend handles formatting, buffering and transport so normal `LOG_INF()/LOG_ERR()` etc. arrive as text lines.\n\n- Additional Kconfig options (buffer sizes, flow control, etc.) may be required for high log volume or long lines; consult the Zephyr sample: https://docs.zephyrproject.org/latest/samples/subsys/logging/ble_backend/README.html\n\n## Troubleshooting\n\n| Situation                        | Hint                                                                        |\n| -------------------------------- | --------------------------------------------------------------------------- |\n| No devices on Windows            | Toggle Bluetooth off/on or airplane mode, verify advertising.               |\n| Linux permission errors          | Ensure user in `bluetooth` group or grant `CAP_NET_RAW` to Python binary.   |\n| macOS permission prompt          | Allow Bluetooth access in System Settings > Privacy & Security > Bluetooth. |\n| Frequent disconnects             | Reduce distance / interference; backoff resets after ~60s stable link.      |\n| Mixed devices with similar names | Use `--filter-addr` to prefer a known address substring.                    |\n\n## Development\n\n```bash\ngit clone https://github.com/smnmsr/nus-logger.git\ncd nus-logger\npip install -e .[dev]\npytest\n```\n\nLinting is intentionally minimal; contributions should keep the code small and dependency\u2011light.\n\n## Versioning & Compatibility\n\nThe public surface is the CLI plus the `NUSClient` / `NUSLoggerController` classes. Minor releases may add kwargs/features; removals will occur only in a major bump following semantic versioning principles.\n\n## License\n\nMIT License \u00a9 2025 Simon M. See `LICENSE` file for full text.\n\n---\n\nIf this saves you time, a \u2b50 on GitHub helps others discover it.\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 Simon M.\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.",
    "summary": "Auto-reconnecting Nordic UART Service (NUS) BLE logger.",
    "version": "0.1.0",
    "project_urls": {
        "Homepage": "https://github.com/smnmsr/nus-logger",
        "Issues": "https://github.com/smnmsr/nus-logger/issues",
        "Source": "https://github.com/smnmsr/nus-logger"
    },
    "split_keywords": [
        "ble",
        " nus",
        " nordic",
        " logging"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "fd536cfbff59d271ff197ceb4f78e2dff050a9274bb19ccb1f5fef30344bec9c",
                "md5": "5865531e4c3c422399a0fb6b629778f7",
                "sha256": "817cf19aa6245633efbcf2c333c3b4e543821940528a508650781a3fe30cfed7"
            },
            "downloads": -1,
            "filename": "nus_logger-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "5865531e4c3c422399a0fb6b629778f7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 19984,
            "upload_time": "2025-09-05T07:27:57",
            "upload_time_iso_8601": "2025-09-05T07:27:57.486588Z",
            "url": "https://files.pythonhosted.org/packages/fd/53/6cfbff59d271ff197ceb4f78e2dff050a9274bb19ccb1f5fef30344bec9c/nus_logger-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "8c86c9a51398bdb332f2563e76d89d310657e016b606e92d9ada4299d47fe1f7",
                "md5": "235b0fd1e9d5cc53651b4f8aaaf050ea",
                "sha256": "2ac02551b7813949de196b9a6b367e015186cd9ea9965f6184c8a234584fe2c0"
            },
            "downloads": -1,
            "filename": "nus_logger-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "235b0fd1e9d5cc53651b4f8aaaf050ea",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 16684,
            "upload_time": "2025-09-05T07:27:58",
            "upload_time_iso_8601": "2025-09-05T07:27:58.840192Z",
            "url": "https://files.pythonhosted.org/packages/8c/86/c9a51398bdb332f2563e76d89d310657e016b606e92d9ada4299d47fe1f7/nus_logger-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-09-05 07:27:58",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "smnmsr",
    "github_project": "nus-logger",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "nus-logger"
}
        
Elapsed time: 0.51578s