Metadata-Version: 2.5
Name: pyopenhwmon
Version: 0.1.0
Summary: Async Python client for the Open Hardware Monitor (OHM) remote server
Project-URL: Homepage, https://github.com/MichaelMKKelly/pyopenhwmon
Project-URL: Repository, https://github.com/MichaelMKKelly/pyopenhwmon
Project-URL: Issues, https://github.com/MichaelMKKelly/pyopenhwmon/issues
Author: MichaelMKKelly
License: MIT
License-File: LICENSE.md
Keywords: aiohttp,async,monitoring,ohm,open-hardware-monitor,sensors
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Home Automation
Classifier: Typing :: Typed
Requires-Python: >=3.13
Requires-Dist: aiohttp>=3.14
Requires-Dist: yarl
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Provides-Extra: test
Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
Requires-Dist: pytest-cov>=5; extra == 'test'
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# pyopenhwmon

An async, fully-typed Python client for the **Open Hardware Monitor (OHM)**
remote server. It fetches and parses the `/data.json` payload into immutable,
easy-to-work-with data models.

`pyopenhwmon` is purpose-built for the [Home Assistant Open Hardware Monitor
integration](https://www.home-assistant.io/integrations/openhardwaremonitor/)
and is also suitable for standalone use.

> **Scope:** This library targets **Open Hardware Monitor (OHM)** only.
> Libre Hardware Monitor (LHM) is a different application with a different API
> and is covered by a separate integration/library.

## Features

- **Async** end-to-end, built on `aiohttp`.
- **Fully typed** with a `py.typed` marker; passes `mypy --strict`.
- **Immutable data models** (`frozen` dataclasses) that mirror the API without
  over-interpreting it.
- **IPv6-safe** URL construction via `yarl`.
- **Tolerant parsing** — one malformed node never crashes an entire update.
- **Clear exception hierarchy** with a `transient` flag for retry decisions.
- **No hidden retries** — rate-limit `Retry-After` is surfaced to the caller.
- Accepts a **caller-provided `aiohttp.ClientSession`** (never closed by the
  client) or manages its own.

## Installation

```bash
pip install pyopenhwmon
```

Requires Python **3.13** or newer.

## Quick start (standalone)

```python
import asyncio

from pyopenhwmon import OHMClient


async def main() -> None:
    async with OHMClient("192.168.1.50") as client:
        if not await client.ping():
            print("OHM server not reachable")
            return
        data = await client.get_data()
        for sensor in data.sensors:
            print(sensor.unique_id, sensor.value, sensor.unit)


asyncio.run(main())
```

### Using your own session

```python
import aiohttp
from pyopenhwmon import OHMClient

async with aiohttp.ClientSession() as session:
    client = OHMClient("192.168.1.50", session=session)
    data = await client.get_data()
    # `session` is closed by the caller, not by `client`.
```

## Home Assistant

The Home Assistant integration uses this library as its data layer. A typical
`DataUpdateCoordinator` fetch:

```python
from pyopenhwmon import OHMClient, OHMError


async def async_update_data():
    try:
        return await client.get_data()
    except OHMError as err:
        if err.transient:
            raise UpdateFailed(...) from err
        raise ConfigEntryError(...) from err
```

The `transient` flag lets the coordinator distinguish retryable failures
(connection errors, timeouts, rate limits) from permanent ones (HTTP 404,
malformed data).

## API

### `OHMClient`

```python
OHMClient(
    host: str,
    port: int = 8085,
    *,
    session: aiohttp.ClientSession | None = None,
    scheme: str = "http",
    timeout: float = 10.0,
)
```

| Member | Description |
| --- | --- |
| `await get_data() -> OHMData` | Fetch and parse the full data tree. |
| `await ping() -> bool` | Lightweight connectivity check (`True` on HTTP 200). |
| `await close() -> None` | Close the session if the client created it. |
| `url -> yarl.URL` | The absolute `/data.json` URL. |

`OHMClient` is an async context manager (`async with`).

### Data models

- `OHMData` — a full snapshot: `root_name`, `computers`, `sensors`.
- `Computer` — a computer node: `name`, `sensors`.
- `Sensor` — a single reading: `name`, `value`, `min`, `max`, `unit`,
  `raw_value`, `computer`, `path`, `unique_id`.

All models are frozen dataclasses exposing `to_dict()` for diagnostics.

`Sensor.unique_id` is a stable, human-readable identifier built from the name
path, e.g. `TEST-PC/Intel Core i7-7700/Temperatures/CPU Core #1`.

### Exceptions

| Exception | Transient | Meaning |
| --- | --- | --- |
| `OHMError` | — | Base class. |
| `OHMConnectionError` | yes | DNS / refused / reset. |
| `OHMTimeoutError` | yes | Connect or read timeout. |
| `OHMHTTPError` | no | Unexpected 4xx/5xx status. |
| `OHMNotFoundError` | no | HTTP 404 (API disabled / wrong port). |
| `OHMRateLimitError` | yes | HTTP 429; exposes `retry_after`. |
| `OHMDataError` | no | Malformed payload. |

## The OHM `/data.json` payload

OHM serves a JSON tree at `GET /data.json` (no authentication, default port
`8085`). **Every node** carries the keys `id`, `Text`, `Children`, `Min`,
`Value`, `Max`, and `ImageURL`.

- The **root** node is hardcoded with `Text: "Sensor"` and the literal header
  strings `Min: "Min"`, `Value: "Value"`, `Max: "Max"`.
- **Branch** nodes (computer / hardware / category) carry empty strings `""`
  for `Min`/`Value`/`Max`.
- **Sensor leaves** carry real reading strings such as `"31.0 °C"`, or `"-"`
  when there is no reading.
- There is **no `Type` field** in the payload.
- A node is a usable sensor iff it has no children and its `Value` contains a
  space (i.e. looks like `<number> <unit>`).
- Locale decimal commas occur (e.g. `"29,0 °C"`).

Example (trimmed):

```json
{
  "id": 0,
  "Text": "Sensor",
  "Children": [
    {
      "id": 1,
      "Text": "TEST-PC",
      "Children": [
        {
          "id": 2,
          "Text": "Intel Core i7-7700",
          "Children": [
            {
              "id": 3,
              "Text": "Temperatures",
              "Children": [
                {
                  "id": 4,
                  "Text": "CPU Core #1",
                  "Children": [],
                  "Min": "0.0 °C",
                  "Value": "31.0 °C",
                  "Max": "100.0 °C",
                  "ImageURL": "images/transparent.png"
                }
              ],
              "Min": "",
              "Value": "",
              "Max": "",
              "ImageURL": "images_icon/temperature.png"
            }
          ],
          "Min": "",
          "Value": "",
          "Max": "",
          "ImageURL": "images_icon/cpu.png"
        }
      ],
      "Min": "",
      "Value": "",
      "Max": "",
      "ImageURL": "images_icon/computer.png"
    }
  ],
  "Min": "Min",
  "Value": "Value",
  "Max": "Max",
  "ImageURL": ""
}
```

## Development

```bash
python -m venv .venv
.venv/bin/pip install -e ".[dev]"
.venv/bin/pytest            # runs the suite with 100% coverage gate
.venv/bin/ruff check .
.venv/bin/mypy
```

## License

[MIT](LICENSE.md)
