pyopenhwmon 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyopenhwmon/__init__.py +35 -0
- pyopenhwmon/client.py +161 -0
- pyopenhwmon/exceptions.py +68 -0
- pyopenhwmon/models.py +65 -0
- pyopenhwmon/parsing.py +170 -0
- pyopenhwmon/py.typed +0 -0
- pyopenhwmon-0.1.0.dist-info/METADATA +256 -0
- pyopenhwmon-0.1.0.dist-info/RECORD +10 -0
- pyopenhwmon-0.1.0.dist-info/WHEEL +4 -0
- pyopenhwmon-0.1.0.dist-info/licenses/LICENSE.md +21 -0
pyopenhwmon/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""pyopenhwmon — async client for the Open Hardware Monitor remote server.
|
|
2
|
+
|
|
3
|
+
This package provides a modern, fully-typed, async client for the Open
|
|
4
|
+
Hardware Monitor (OHM) ``/data.json`` API. It is intended for use both as a
|
|
5
|
+
standalone library and as the data layer for the Home Assistant Open
|
|
6
|
+
Hardware Monitor integration.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .client import OHMClient
|
|
10
|
+
from .exceptions import (
|
|
11
|
+
OHMConnectionError,
|
|
12
|
+
OHMDataError,
|
|
13
|
+
OHMError,
|
|
14
|
+
OHMHTTPError,
|
|
15
|
+
OHMNotFoundError,
|
|
16
|
+
OHMRateLimitError,
|
|
17
|
+
OHMTimeoutError,
|
|
18
|
+
)
|
|
19
|
+
from .models import Computer, OHMData, Sensor
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"Computer",
|
|
23
|
+
"OHMClient",
|
|
24
|
+
"OHMConnectionError",
|
|
25
|
+
"OHMData",
|
|
26
|
+
"OHMDataError",
|
|
27
|
+
"OHMError",
|
|
28
|
+
"OHMHTTPError",
|
|
29
|
+
"OHMNotFoundError",
|
|
30
|
+
"OHMRateLimitError",
|
|
31
|
+
"OHMTimeoutError",
|
|
32
|
+
"Sensor",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
__version__ = "0.1.0"
|
pyopenhwmon/client.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Async client for the Open Hardware Monitor (OHM) remote server."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from types import TracebackType
|
|
5
|
+
from typing import Final, Self
|
|
6
|
+
|
|
7
|
+
import aiohttp
|
|
8
|
+
import yarl
|
|
9
|
+
|
|
10
|
+
from .exceptions import (
|
|
11
|
+
OHMConnectionError,
|
|
12
|
+
OHMDataError,
|
|
13
|
+
OHMHTTPError,
|
|
14
|
+
OHMNotFoundError,
|
|
15
|
+
OHMRateLimitError,
|
|
16
|
+
OHMTimeoutError,
|
|
17
|
+
)
|
|
18
|
+
from .models import OHMData
|
|
19
|
+
from .parsing import parse_data
|
|
20
|
+
|
|
21
|
+
_LOGGER: Final = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
DEFAULT_PORT: Final = 8085
|
|
24
|
+
DATA_PATH: Final = "/data.json"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class OHMClient:
|
|
28
|
+
"""Async client for the OHM remote server.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
host: The OHM server host (IPv4/IPv6 literal or hostname).
|
|
32
|
+
port: The OHM server port (default ``8085``).
|
|
33
|
+
session: An optional caller-provided ``aiohttp.ClientSession``. If
|
|
34
|
+
given, it is used as-is and never closed by this client.
|
|
35
|
+
scheme: ``"http"`` (default) or ``"https"``.
|
|
36
|
+
timeout: Total request timeout in seconds (default ``10.0``).
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
host: str,
|
|
42
|
+
port: int = DEFAULT_PORT,
|
|
43
|
+
*,
|
|
44
|
+
session: aiohttp.ClientSession | None = None,
|
|
45
|
+
scheme: str = "http",
|
|
46
|
+
timeout: float = 10.0,
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Initialize the client (no I/O happens until a request is made)."""
|
|
49
|
+
self._host = host
|
|
50
|
+
self._port = port
|
|
51
|
+
self._scheme = scheme
|
|
52
|
+
self._timeout = timeout
|
|
53
|
+
self._external_session = session
|
|
54
|
+
self._own_session: aiohttp.ClientSession | None = None
|
|
55
|
+
self._url = self._build_url()
|
|
56
|
+
|
|
57
|
+
def _build_url(self) -> yarl.URL:
|
|
58
|
+
"""Build the ``/data.json`` URL (IPv6-safe via ``yarl``)."""
|
|
59
|
+
return yarl.URL.build(
|
|
60
|
+
scheme=self._scheme,
|
|
61
|
+
host=self._host,
|
|
62
|
+
port=self._port,
|
|
63
|
+
path=DATA_PATH,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def url(self) -> yarl.URL:
|
|
68
|
+
"""The absolute URL of the OHM data endpoint."""
|
|
69
|
+
return self._url
|
|
70
|
+
|
|
71
|
+
def _get_session(self) -> aiohttp.ClientSession:
|
|
72
|
+
"""Return the session to use, creating our own if needed."""
|
|
73
|
+
if self._external_session is not None:
|
|
74
|
+
return self._external_session
|
|
75
|
+
if self._own_session is None or self._own_session.closed:
|
|
76
|
+
self._own_session = aiohttp.ClientSession()
|
|
77
|
+
return self._own_session
|
|
78
|
+
|
|
79
|
+
async def get_data(self) -> OHMData:
|
|
80
|
+
"""Fetch and parse the OHM data tree.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
OHMTimeoutError: On a connect/read timeout.
|
|
84
|
+
OHMConnectionError: On a connection-level failure.
|
|
85
|
+
OHMNotFoundError: On HTTP 404.
|
|
86
|
+
OHMRateLimitError: On HTTP 429.
|
|
87
|
+
OHMHTTPError: On any other 4xx/5xx status.
|
|
88
|
+
OHMDataError: On a malformed payload.
|
|
89
|
+
"""
|
|
90
|
+
_LOGGER.debug("Fetching OHM data from %s", self._url)
|
|
91
|
+
session = self._get_session()
|
|
92
|
+
try:
|
|
93
|
+
async with session.get(
|
|
94
|
+
self._url,
|
|
95
|
+
timeout=aiohttp.ClientTimeout(total=self._timeout),
|
|
96
|
+
) as resp:
|
|
97
|
+
return await self._handle_response(resp)
|
|
98
|
+
except TimeoutError as err:
|
|
99
|
+
raise OHMTimeoutError(f"Timed out connecting to {self._url}") from err
|
|
100
|
+
except aiohttp.ClientError as err:
|
|
101
|
+
raise OHMConnectionError(f"Connection error to {self._url}: {err}") from err
|
|
102
|
+
|
|
103
|
+
async def _handle_response(self, resp: aiohttp.ClientResponse) -> OHMData:
|
|
104
|
+
"""Map an HTTP response to an :class:`OHMData` or a specific error."""
|
|
105
|
+
if resp.status == 404:
|
|
106
|
+
raise OHMNotFoundError(404, str(self._url))
|
|
107
|
+
if resp.status == 429:
|
|
108
|
+
retry_after = _parse_retry_after(resp.headers.get("Retry-After"))
|
|
109
|
+
raise OHMRateLimitError(429, str(self._url), retry_after=retry_after)
|
|
110
|
+
if resp.status >= 400:
|
|
111
|
+
raise OHMHTTPError(resp.status, str(self._url))
|
|
112
|
+
try:
|
|
113
|
+
body = await resp.json(content_type=None)
|
|
114
|
+
except (aiohttp.ClientResponseError, ValueError) as err:
|
|
115
|
+
raise OHMDataError(f"Invalid JSON from {self._url}: {err}") from err
|
|
116
|
+
return parse_data(body)
|
|
117
|
+
|
|
118
|
+
async def ping(self) -> bool:
|
|
119
|
+
"""Lightweight connectivity check.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
``True`` if the server answered with HTTP 200, else ``False``.
|
|
123
|
+
"""
|
|
124
|
+
session = self._get_session()
|
|
125
|
+
try:
|
|
126
|
+
async with session.get(
|
|
127
|
+
self._url,
|
|
128
|
+
timeout=aiohttp.ClientTimeout(total=min(self._timeout, 5.0)),
|
|
129
|
+
) as resp:
|
|
130
|
+
return resp.status == 200
|
|
131
|
+
except (aiohttp.ClientError, TimeoutError):
|
|
132
|
+
return False
|
|
133
|
+
|
|
134
|
+
async def close(self) -> None:
|
|
135
|
+
"""Close the session if this client created it."""
|
|
136
|
+
if self._own_session is not None and not self._own_session.closed:
|
|
137
|
+
await self._own_session.close()
|
|
138
|
+
self._own_session = None
|
|
139
|
+
|
|
140
|
+
async def __aenter__(self) -> Self:
|
|
141
|
+
"""Enter the async context manager."""
|
|
142
|
+
return self
|
|
143
|
+
|
|
144
|
+
async def __aexit__(
|
|
145
|
+
self,
|
|
146
|
+
exc_type: type[BaseException] | None,
|
|
147
|
+
exc: BaseException | None,
|
|
148
|
+
tb: TracebackType | None,
|
|
149
|
+
) -> None:
|
|
150
|
+
"""Exit the async context manager, closing our session if any."""
|
|
151
|
+
await self.close()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _parse_retry_after(value: str | None) -> float | None:
|
|
155
|
+
"""Parse a ``Retry-After`` header value into seconds (or ``None``)."""
|
|
156
|
+
if value is None:
|
|
157
|
+
return None
|
|
158
|
+
try:
|
|
159
|
+
return float(value)
|
|
160
|
+
except ValueError:
|
|
161
|
+
return None
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Exception hierarchy for the pyopenhwmon client.
|
|
2
|
+
|
|
3
|
+
Every exception derives from :class:`OHMError`, which exposes a ``transient``
|
|
4
|
+
flag so callers (for example a Home Assistant ``DataUpdateCoordinator``) can
|
|
5
|
+
decide whether a failure is worth retrying without string-matching messages.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class OHMError(Exception):
|
|
10
|
+
"""Base class for all pyopenhwmon errors.
|
|
11
|
+
|
|
12
|
+
Attributes:
|
|
13
|
+
transient: ``True`` when the failure is likely to clear up if the
|
|
14
|
+
request is retried (network problems, timeouts, rate limiting).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
transient: bool = False
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class OHMConnectionError(OHMError):
|
|
21
|
+
"""A connection-level failure (DNS error, refused, reset)."""
|
|
22
|
+
|
|
23
|
+
transient = True
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class OHMTimeoutError(OHMError):
|
|
27
|
+
"""A connect or read timeout."""
|
|
28
|
+
|
|
29
|
+
transient = True
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class OHMHTTPError(OHMError):
|
|
33
|
+
"""An unexpected HTTP status code (4xx/5xx)."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, status: int, url: str) -> None:
|
|
36
|
+
"""Initialize with the HTTP status and request URL."""
|
|
37
|
+
self.status = status
|
|
38
|
+
self.url = url
|
|
39
|
+
super().__init__(f"HTTP {status} from {url}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class OHMNotFoundError(OHMHTTPError):
|
|
43
|
+
"""HTTP 404 — the OHM API is disabled or the host/port is wrong."""
|
|
44
|
+
|
|
45
|
+
transient = False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class OHMRateLimitError(OHMHTTPError):
|
|
49
|
+
"""HTTP 429 — the server is rate limiting the client."""
|
|
50
|
+
|
|
51
|
+
transient = True
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
status: int,
|
|
56
|
+
url: str,
|
|
57
|
+
*,
|
|
58
|
+
retry_after: float | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
"""Initialize with the status, URL, and optional retry-after seconds."""
|
|
61
|
+
super().__init__(status, url)
|
|
62
|
+
self.retry_after = retry_after
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class OHMDataError(OHMError):
|
|
66
|
+
"""The payload was malformed or had an unexpected shape."""
|
|
67
|
+
|
|
68
|
+
transient = False
|
pyopenhwmon/models.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Immutable data models for OHM data.
|
|
2
|
+
|
|
3
|
+
The models mirror the shape of the OHM ``/data.json`` payload without
|
|
4
|
+
interpreting it: numeric fields are parsed to ``float | None`` while the raw
|
|
5
|
+
strings are preserved for diagnostics.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from dataclasses import asdict, dataclass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Sensor:
|
|
13
|
+
"""A single OHM sensor reading.
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
name: The sensor's display name (the node's ``Text``).
|
|
17
|
+
value: The parsed numeric value, or ``None`` if unavailable.
|
|
18
|
+
min: The parsed minimum, or ``None``.
|
|
19
|
+
max: The parsed maximum, or ``None``.
|
|
20
|
+
unit: The unit string (e.g. ``"°C"``), or ``None``.
|
|
21
|
+
raw_value: The raw ``Value`` string as sent by OHM.
|
|
22
|
+
computer: The name of the computer this sensor belongs to.
|
|
23
|
+
path: The index path from the root node (for diagnostics).
|
|
24
|
+
unique_id: A stable, human-readable identifier built from the name
|
|
25
|
+
path (computer/type/category/sensor).
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
name: str
|
|
29
|
+
value: float | None
|
|
30
|
+
min: float | None
|
|
31
|
+
max: float | None
|
|
32
|
+
unit: str | None
|
|
33
|
+
raw_value: str | None
|
|
34
|
+
computer: str
|
|
35
|
+
path: tuple[int, ...]
|
|
36
|
+
unique_id: str
|
|
37
|
+
|
|
38
|
+
def to_dict(self) -> dict[str, object]:
|
|
39
|
+
"""Return a plain-dict representation (for diagnostics/logging)."""
|
|
40
|
+
return asdict(self)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Computer:
|
|
45
|
+
"""A computer (hardware) node and the sensors beneath it."""
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
sensors: tuple[Sensor, ...]
|
|
49
|
+
|
|
50
|
+
def to_dict(self) -> dict[str, object]:
|
|
51
|
+
"""Return a plain-dict representation (for diagnostics/logging)."""
|
|
52
|
+
return asdict(self)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class OHMData:
|
|
57
|
+
"""A full snapshot of the OHM data tree."""
|
|
58
|
+
|
|
59
|
+
root_name: str
|
|
60
|
+
computers: tuple[Computer, ...]
|
|
61
|
+
sensors: tuple[Sensor, ...]
|
|
62
|
+
|
|
63
|
+
def to_dict(self) -> dict[str, object]:
|
|
64
|
+
"""Return a plain-dict representation (for diagnostics/logging)."""
|
|
65
|
+
return asdict(self)
|
pyopenhwmon/parsing.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Parsing of the raw OHM ``/data.json`` payload into data models.
|
|
2
|
+
|
|
3
|
+
The parser is deliberately tolerant: a malformed or unexpected node is
|
|
4
|
+
skipped rather than allowed to crash an entire update. Only the root node is
|
|
5
|
+
treated as a hard contract — if it is not a well-formed object with a ``Text``
|
|
6
|
+
name and a ``Children`` list, an :class:`~pyopenhwmon.exceptions.OHMDataError`
|
|
7
|
+
is raised.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .exceptions import OHMDataError
|
|
14
|
+
from .models import Computer, OHMData, Sensor
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parse_data(raw: object) -> OHMData:
|
|
18
|
+
"""Parse a raw OHM JSON payload into an :class:`OHMData` snapshot.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
raw: The decoded JSON body (typically a ``dict``).
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
An :class:`OHMData` snapshot of the tree.
|
|
25
|
+
|
|
26
|
+
Raises:
|
|
27
|
+
OHMDataError: If the root node is malformed.
|
|
28
|
+
"""
|
|
29
|
+
if not isinstance(raw, dict):
|
|
30
|
+
raise OHMDataError("Payload root must be a JSON object")
|
|
31
|
+
root_name = _require_str(raw, "Text", "root")
|
|
32
|
+
root_children = _require_list(raw, "Children", "root")
|
|
33
|
+
|
|
34
|
+
computers: list[Computer] = []
|
|
35
|
+
all_sensors: list[Sensor] = []
|
|
36
|
+
for i, comp_node in enumerate(root_children):
|
|
37
|
+
if not isinstance(comp_node, dict):
|
|
38
|
+
continue
|
|
39
|
+
comp_name = comp_node.get("Text")
|
|
40
|
+
if not isinstance(comp_name, str):
|
|
41
|
+
continue
|
|
42
|
+
comp_sensors: list[Sensor] = []
|
|
43
|
+
comp_children = comp_node.get("Children")
|
|
44
|
+
if not isinstance(comp_children, list):
|
|
45
|
+
comp_children = []
|
|
46
|
+
for j, child in enumerate(comp_children):
|
|
47
|
+
_walk(
|
|
48
|
+
child,
|
|
49
|
+
computer=comp_name,
|
|
50
|
+
name_path=[comp_name],
|
|
51
|
+
index_path=(i, j),
|
|
52
|
+
sensors=comp_sensors,
|
|
53
|
+
)
|
|
54
|
+
computers.append(Computer(name=comp_name, sensors=tuple(comp_sensors)))
|
|
55
|
+
all_sensors.extend(comp_sensors)
|
|
56
|
+
return OHMData(
|
|
57
|
+
root_name=root_name,
|
|
58
|
+
computers=tuple(computers),
|
|
59
|
+
sensors=tuple(all_sensors),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _walk(
|
|
64
|
+
node: object,
|
|
65
|
+
*,
|
|
66
|
+
computer: str,
|
|
67
|
+
name_path: list[str],
|
|
68
|
+
index_path: tuple[int, ...],
|
|
69
|
+
sensors: list[Sensor],
|
|
70
|
+
) -> None:
|
|
71
|
+
"""Recursively walk a node, collecting sensor leaves into ``sensors``.
|
|
72
|
+
|
|
73
|
+
``name_path`` is the name path to the node's parent; the node's own
|
|
74
|
+
``Text`` is appended before descending. A node without a ``Text`` name is
|
|
75
|
+
skipped along with its subtree.
|
|
76
|
+
"""
|
|
77
|
+
if not isinstance(node, dict):
|
|
78
|
+
return
|
|
79
|
+
text = node.get("Text")
|
|
80
|
+
if not isinstance(text, str):
|
|
81
|
+
return
|
|
82
|
+
name_path = [*name_path, text]
|
|
83
|
+
children = node.get("Children")
|
|
84
|
+
if not isinstance(children, list) or not children:
|
|
85
|
+
_maybe_add_sensor(node, computer, name_path, index_path, sensors)
|
|
86
|
+
return
|
|
87
|
+
for k, child in enumerate(children):
|
|
88
|
+
_walk(
|
|
89
|
+
child,
|
|
90
|
+
computer=computer,
|
|
91
|
+
name_path=name_path,
|
|
92
|
+
index_path=(*index_path, k),
|
|
93
|
+
sensors=sensors,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _maybe_add_sensor(
|
|
98
|
+
node: Mapping[str, Any],
|
|
99
|
+
computer: str,
|
|
100
|
+
name_path: list[str],
|
|
101
|
+
index_path: tuple[int, ...],
|
|
102
|
+
sensors: list[Sensor],
|
|
103
|
+
) -> None:
|
|
104
|
+
"""Add ``node`` as a sensor if it looks like one (leaf with a reading).
|
|
105
|
+
|
|
106
|
+
A node is a sensor iff it has no children and its ``Value`` contains a
|
|
107
|
+
space (i.e. looks like ``<number> <unit>``).
|
|
108
|
+
"""
|
|
109
|
+
value = node.get("Value")
|
|
110
|
+
if not isinstance(value, str) or " " not in value:
|
|
111
|
+
return
|
|
112
|
+
value_float, unit = _parse_reading(value)
|
|
113
|
+
min_float, _ = _parse_reading(node.get("Min"))
|
|
114
|
+
max_float, _ = _parse_reading(node.get("Max"))
|
|
115
|
+
sensors.append(
|
|
116
|
+
Sensor(
|
|
117
|
+
name=name_path[-1],
|
|
118
|
+
value=value_float,
|
|
119
|
+
min=min_float,
|
|
120
|
+
max=max_float,
|
|
121
|
+
unit=unit,
|
|
122
|
+
raw_value=value,
|
|
123
|
+
computer=computer,
|
|
124
|
+
path=index_path,
|
|
125
|
+
unique_id="/".join(name_path),
|
|
126
|
+
)
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _parse_reading(value: object) -> tuple[float | None, str | None]:
|
|
131
|
+
"""Parse a ``<number> <unit>`` reading into ``(float | None, unit | None)``."""
|
|
132
|
+
if not isinstance(value, str):
|
|
133
|
+
return None, None
|
|
134
|
+
parts = value.split(None, 1)
|
|
135
|
+
if len(parts) == 2:
|
|
136
|
+
num_str, unit = parts[0], parts[1].strip()
|
|
137
|
+
else:
|
|
138
|
+
num_str, unit = value, None
|
|
139
|
+
return _to_float(num_str), unit
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _to_float(number: str) -> float | None:
|
|
143
|
+
"""Convert a locale-formatted number string to ``float`` (or ``None``).
|
|
144
|
+
|
|
145
|
+
A locale decimal comma is normalised to a dot before conversion. ``"-"``
|
|
146
|
+
and empty strings yield ``None``.
|
|
147
|
+
"""
|
|
148
|
+
s = number.strip()
|
|
149
|
+
if not s or s == "-":
|
|
150
|
+
return None
|
|
151
|
+
try:
|
|
152
|
+
return float(s.replace(",", "."))
|
|
153
|
+
except ValueError:
|
|
154
|
+
return None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _require_str(node: Mapping[str, Any], key: str, where: str) -> str:
|
|
158
|
+
"""Return ``node[key]`` if it is a ``str``, else raise :class:`OHMDataError`."""
|
|
159
|
+
val = node.get(key)
|
|
160
|
+
if not isinstance(val, str):
|
|
161
|
+
raise OHMDataError(f"Missing or invalid '{key}' at {where}")
|
|
162
|
+
return val
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _require_list(node: Mapping[str, Any], key: str, where: str) -> list[Any]:
|
|
166
|
+
"""Return ``node[key]`` if it is a ``list``, else raise :class:`OHMDataError`."""
|
|
167
|
+
val = node.get(key)
|
|
168
|
+
if not isinstance(val, list):
|
|
169
|
+
raise OHMDataError(f"Missing or invalid '{key}' at {where}")
|
|
170
|
+
return val
|
pyopenhwmon/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pyopenhwmon
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async Python client for the Open Hardware Monitor (OHM) remote server
|
|
5
|
+
Project-URL: Homepage, https://github.com/MichaelMKKelly/pyopenhwmon
|
|
6
|
+
Project-URL: Repository, https://github.com/MichaelMKKelly/pyopenhwmon
|
|
7
|
+
Project-URL: Issues, https://github.com/MichaelMKKelly/pyopenhwmon/issues
|
|
8
|
+
Author: MichaelMKKelly
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE.md
|
|
11
|
+
Keywords: aiohttp,async,monitoring,ohm,open-hardware-monitor,sensors
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Topic :: Home Automation
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.13
|
|
21
|
+
Requires-Dist: aiohttp>=3.14
|
|
22
|
+
Requires-Dist: yarl
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest-cov>=5; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
28
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
29
|
+
Provides-Extra: test
|
|
30
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
|
|
31
|
+
Requires-Dist: pytest-cov>=5; extra == 'test'
|
|
32
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# pyopenhwmon
|
|
36
|
+
|
|
37
|
+
An async, fully-typed Python client for the **Open Hardware Monitor (OHM)**
|
|
38
|
+
remote server. It fetches and parses the `/data.json` payload into immutable,
|
|
39
|
+
easy-to-work-with data models.
|
|
40
|
+
|
|
41
|
+
`pyopenhwmon` is purpose-built for the [Home Assistant Open Hardware Monitor
|
|
42
|
+
integration](https://www.home-assistant.io/integrations/openhardwaremonitor/)
|
|
43
|
+
and is also suitable for standalone use.
|
|
44
|
+
|
|
45
|
+
> **Scope:** This library targets **Open Hardware Monitor (OHM)** only.
|
|
46
|
+
> Libre Hardware Monitor (LHM) is a different application with a different API
|
|
47
|
+
> and is covered by a separate integration/library.
|
|
48
|
+
|
|
49
|
+
## Features
|
|
50
|
+
|
|
51
|
+
- **Async** end-to-end, built on `aiohttp`.
|
|
52
|
+
- **Fully typed** with a `py.typed` marker; passes `mypy --strict`.
|
|
53
|
+
- **Immutable data models** (`frozen` dataclasses) that mirror the API without
|
|
54
|
+
over-interpreting it.
|
|
55
|
+
- **IPv6-safe** URL construction via `yarl`.
|
|
56
|
+
- **Tolerant parsing** — one malformed node never crashes an entire update.
|
|
57
|
+
- **Clear exception hierarchy** with a `transient` flag for retry decisions.
|
|
58
|
+
- **No hidden retries** — rate-limit `Retry-After` is surfaced to the caller.
|
|
59
|
+
- Accepts a **caller-provided `aiohttp.ClientSession`** (never closed by the
|
|
60
|
+
client) or manages its own.
|
|
61
|
+
|
|
62
|
+
## Installation
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
pip install pyopenhwmon
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Requires Python **3.13** or newer.
|
|
69
|
+
|
|
70
|
+
## Quick start (standalone)
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import asyncio
|
|
74
|
+
|
|
75
|
+
from pyopenhwmon import OHMClient
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
async def main() -> None:
|
|
79
|
+
async with OHMClient("192.168.1.50") as client:
|
|
80
|
+
if not await client.ping():
|
|
81
|
+
print("OHM server not reachable")
|
|
82
|
+
return
|
|
83
|
+
data = await client.get_data()
|
|
84
|
+
for sensor in data.sensors:
|
|
85
|
+
print(sensor.unique_id, sensor.value, sensor.unit)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
asyncio.run(main())
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Using your own session
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
import aiohttp
|
|
95
|
+
from pyopenhwmon import OHMClient
|
|
96
|
+
|
|
97
|
+
async with aiohttp.ClientSession() as session:
|
|
98
|
+
client = OHMClient("192.168.1.50", session=session)
|
|
99
|
+
data = await client.get_data()
|
|
100
|
+
# `session` is closed by the caller, not by `client`.
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Home Assistant
|
|
104
|
+
|
|
105
|
+
The Home Assistant integration uses this library as its data layer. A typical
|
|
106
|
+
`DataUpdateCoordinator` fetch:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from pyopenhwmon import OHMClient, OHMError
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
async def async_update_data():
|
|
113
|
+
try:
|
|
114
|
+
return await client.get_data()
|
|
115
|
+
except OHMError as err:
|
|
116
|
+
if err.transient:
|
|
117
|
+
raise UpdateFailed(...) from err
|
|
118
|
+
raise ConfigEntryError(...) from err
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The `transient` flag lets the coordinator distinguish retryable failures
|
|
122
|
+
(connection errors, timeouts, rate limits) from permanent ones (HTTP 404,
|
|
123
|
+
malformed data).
|
|
124
|
+
|
|
125
|
+
## API
|
|
126
|
+
|
|
127
|
+
### `OHMClient`
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
OHMClient(
|
|
131
|
+
host: str,
|
|
132
|
+
port: int = 8085,
|
|
133
|
+
*,
|
|
134
|
+
session: aiohttp.ClientSession | None = None,
|
|
135
|
+
scheme: str = "http",
|
|
136
|
+
timeout: float = 10.0,
|
|
137
|
+
)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
| Member | Description |
|
|
141
|
+
| --- | --- |
|
|
142
|
+
| `await get_data() -> OHMData` | Fetch and parse the full data tree. |
|
|
143
|
+
| `await ping() -> bool` | Lightweight connectivity check (`True` on HTTP 200). |
|
|
144
|
+
| `await close() -> None` | Close the session if the client created it. |
|
|
145
|
+
| `url -> yarl.URL` | The absolute `/data.json` URL. |
|
|
146
|
+
|
|
147
|
+
`OHMClient` is an async context manager (`async with`).
|
|
148
|
+
|
|
149
|
+
### Data models
|
|
150
|
+
|
|
151
|
+
- `OHMData` — a full snapshot: `root_name`, `computers`, `sensors`.
|
|
152
|
+
- `Computer` — a computer node: `name`, `sensors`.
|
|
153
|
+
- `Sensor` — a single reading: `name`, `value`, `min`, `max`, `unit`,
|
|
154
|
+
`raw_value`, `computer`, `path`, `unique_id`.
|
|
155
|
+
|
|
156
|
+
All models are frozen dataclasses exposing `to_dict()` for diagnostics.
|
|
157
|
+
|
|
158
|
+
`Sensor.unique_id` is a stable, human-readable identifier built from the name
|
|
159
|
+
path, e.g. `TEST-PC/Intel Core i7-7700/Temperatures/CPU Core #1`.
|
|
160
|
+
|
|
161
|
+
### Exceptions
|
|
162
|
+
|
|
163
|
+
| Exception | Transient | Meaning |
|
|
164
|
+
| --- | --- | --- |
|
|
165
|
+
| `OHMError` | — | Base class. |
|
|
166
|
+
| `OHMConnectionError` | yes | DNS / refused / reset. |
|
|
167
|
+
| `OHMTimeoutError` | yes | Connect or read timeout. |
|
|
168
|
+
| `OHMHTTPError` | no | Unexpected 4xx/5xx status. |
|
|
169
|
+
| `OHMNotFoundError` | no | HTTP 404 (API disabled / wrong port). |
|
|
170
|
+
| `OHMRateLimitError` | yes | HTTP 429; exposes `retry_after`. |
|
|
171
|
+
| `OHMDataError` | no | Malformed payload. |
|
|
172
|
+
|
|
173
|
+
## The OHM `/data.json` payload
|
|
174
|
+
|
|
175
|
+
OHM serves a JSON tree at `GET /data.json` (no authentication, default port
|
|
176
|
+
`8085`). **Every node** carries the keys `id`, `Text`, `Children`, `Min`,
|
|
177
|
+
`Value`, `Max`, and `ImageURL`.
|
|
178
|
+
|
|
179
|
+
- The **root** node is hardcoded with `Text: "Sensor"` and the literal header
|
|
180
|
+
strings `Min: "Min"`, `Value: "Value"`, `Max: "Max"`.
|
|
181
|
+
- **Branch** nodes (computer / hardware / category) carry empty strings `""`
|
|
182
|
+
for `Min`/`Value`/`Max`.
|
|
183
|
+
- **Sensor leaves** carry real reading strings such as `"31.0 °C"`, or `"-"`
|
|
184
|
+
when there is no reading.
|
|
185
|
+
- There is **no `Type` field** in the payload.
|
|
186
|
+
- A node is a usable sensor iff it has no children and its `Value` contains a
|
|
187
|
+
space (i.e. looks like `<number> <unit>`).
|
|
188
|
+
- Locale decimal commas occur (e.g. `"29,0 °C"`).
|
|
189
|
+
|
|
190
|
+
Example (trimmed):
|
|
191
|
+
|
|
192
|
+
```json
|
|
193
|
+
{
|
|
194
|
+
"id": 0,
|
|
195
|
+
"Text": "Sensor",
|
|
196
|
+
"Children": [
|
|
197
|
+
{
|
|
198
|
+
"id": 1,
|
|
199
|
+
"Text": "TEST-PC",
|
|
200
|
+
"Children": [
|
|
201
|
+
{
|
|
202
|
+
"id": 2,
|
|
203
|
+
"Text": "Intel Core i7-7700",
|
|
204
|
+
"Children": [
|
|
205
|
+
{
|
|
206
|
+
"id": 3,
|
|
207
|
+
"Text": "Temperatures",
|
|
208
|
+
"Children": [
|
|
209
|
+
{
|
|
210
|
+
"id": 4,
|
|
211
|
+
"Text": "CPU Core #1",
|
|
212
|
+
"Children": [],
|
|
213
|
+
"Min": "0.0 °C",
|
|
214
|
+
"Value": "31.0 °C",
|
|
215
|
+
"Max": "100.0 °C",
|
|
216
|
+
"ImageURL": "images/transparent.png"
|
|
217
|
+
}
|
|
218
|
+
],
|
|
219
|
+
"Min": "",
|
|
220
|
+
"Value": "",
|
|
221
|
+
"Max": "",
|
|
222
|
+
"ImageURL": "images_icon/temperature.png"
|
|
223
|
+
}
|
|
224
|
+
],
|
|
225
|
+
"Min": "",
|
|
226
|
+
"Value": "",
|
|
227
|
+
"Max": "",
|
|
228
|
+
"ImageURL": "images_icon/cpu.png"
|
|
229
|
+
}
|
|
230
|
+
],
|
|
231
|
+
"Min": "",
|
|
232
|
+
"Value": "",
|
|
233
|
+
"Max": "",
|
|
234
|
+
"ImageURL": "images_icon/computer.png"
|
|
235
|
+
}
|
|
236
|
+
],
|
|
237
|
+
"Min": "Min",
|
|
238
|
+
"Value": "Value",
|
|
239
|
+
"Max": "Max",
|
|
240
|
+
"ImageURL": ""
|
|
241
|
+
}
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
## Development
|
|
245
|
+
|
|
246
|
+
```bash
|
|
247
|
+
python -m venv .venv
|
|
248
|
+
.venv/bin/pip install -e ".[dev]"
|
|
249
|
+
.venv/bin/pytest # runs the suite with 100% coverage gate
|
|
250
|
+
.venv/bin/ruff check .
|
|
251
|
+
.venv/bin/mypy
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
## License
|
|
255
|
+
|
|
256
|
+
[MIT](LICENSE.md)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
pyopenhwmon/__init__.py,sha256=mkc2pwVT3OUOzrerh2M55fsLOkqNLucbG_YR6AIFRhg,827
|
|
2
|
+
pyopenhwmon/client.py,sha256=AXBiF0RpO07iMAXwzRae0klcjmdln6xCHWMFU_6rkoU,5476
|
|
3
|
+
pyopenhwmon/exceptions.py,sha256=GyO6dmMAlvdu4YFBRo_4nqEv9YedUpl_JF2wnwUsM68,1776
|
|
4
|
+
pyopenhwmon/models.py,sha256=rdMLidIoznH5CEIbZPwKn4Yb3boI_UTMwQ5PMDGUx9k,1949
|
|
5
|
+
pyopenhwmon/parsing.py,sha256=-MOncu3jP1XqZYquWf_s79cYah5O7iCCt6-wlsBFiZc,5388
|
|
6
|
+
pyopenhwmon/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
pyopenhwmon-0.1.0.dist-info/METADATA,sha256=9syPHwlaqJT7x5NMonuZjYCmzQWQLrawcuH0n_PL6WQ,7605
|
|
8
|
+
pyopenhwmon-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
pyopenhwmon-0.1.0.dist-info/licenses/LICENSE.md,sha256=C_VRk4MKtek6x27OMOsNp795ooP8gkuYhAbsLWRlQqs,1071
|
|
10
|
+
pyopenhwmon-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MichaelMKKelly
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|