Metadata-Version: 2.5
Name: pyopenhwmon
Version: 0.3.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>=1.25.1
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`.
```

### Probing connectivity

`ping()` returns a simple `bool`. For a richer outcome — for example to
distinguish "host up but the API is disabled" (HTTP 404) from "unreachable" —
use `probe()`:

```python
from pyopenhwmon import OHMClient, ProbeStatus

async with OHMClient("192.168.1.50") as client:
    result = await client.probe()
    if result.status is ProbeStatus.OK:
        data = await client.get_data()
    elif result.status is ProbeStatus.API_DISABLED:
        print("OHM is running but the API is disabled")
    elif result.status is ProbeStatus.UNREACHABLE:
        print("OHM server not reachable")
```

## 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, server errors, and malformed
data) from permanent ones (HTTP 404).

## API

### `OHMClient`

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

| Member | Description |
| --- | --- |
| `await get_data() -> OHMData` | Fetch and parse the full data tree. |
| `await probe() -> ProbeResult` | Rich connectivity probe (see `ProbeStatus`). |
| `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`). The `scheme` must be
`"http"` or `"https"` (case-insensitive); `host` must be non-empty and `port`
must be in `1-65535`; all timeouts must be positive. A `ValueError` is raised
otherwise. `connect_timeout` and `read_timeout` optionally narrow the
connect-phase and socket-read timeouts respectively.

### Data models

- `OHMData` — a full snapshot: `root_name`, `computers`, `sensors`.
- `Computer` — a computer node: `name`, `sensors`.
- `Sensor` — a single reading: `name`, `value`, `min_value`, `max_value`,
  `unit`, `raw_value`, `computer`, `path`, `unique_id`.
- `ProbeResult` — the outcome of `probe()`: `status` (a `ProbeStatus`) and
  `http_status` (the HTTP status when a response was received).
- `ProbeStatus` — enum: `OK`, `API_DISABLED`, `HTTP_ERROR`, `UNREACHABLE`.

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`. Note: two
computers that share the same name produce colliding `unique_id` values (a
rare edge case, matching the legacy integration).

### Exceptions

| Exception | Transient | Meaning |
| --- | --- | --- |
| `OHMError` | — | Base class. |
| `OHMConnectionError` | yes | DNS / refused / reset. |
| `OHMTimeoutError` | yes | Connect or read timeout. |
| `OHMHTTPError` | no | Any other unexpected status (non-200, non-404, non-429, non-5xx). |
| `OHMNotFoundError` | no | HTTP 404 (API disabled / wrong port). |
| `OHMRateLimitError` | yes | HTTP 429; exposes `retry_after`. |
| `OHMServerError` | yes | HTTP 5xx (server-side failure). |
| `OHMDataError` | yes | Malformed payload (retry may succeed). |

## 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>`), or is the literal `"-"` (a sensor
  with no current reading, included with `value=None`).
- 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)
