python-pironman 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.
pironman/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ """Asynchronous Python library for the Pironman REST API."""
2
+
3
+ from .client import PironmanClient
4
+ from .device import PironmanDeviceInfo
5
+ from .exceptions import (
6
+ PironmanAPIError,
7
+ PironmanConnectionError,
8
+ PironmanError,
9
+ PironmanResponseError,
10
+ PironmanTimeoutError,
11
+ )
12
+
13
+ __all__ = [
14
+ "PironmanAPIError",
15
+ "PironmanClient",
16
+ "PironmanConnectionError",
17
+ "PironmanDeviceInfo",
18
+ "PironmanError",
19
+ "PironmanResponseError",
20
+ "PironmanTimeoutError",
21
+ ]
pironman/client.py ADDED
@@ -0,0 +1,120 @@
1
+ """Asynchronous client for the local Pironman REST API."""
2
+
3
+ from typing import Any, cast
4
+
5
+ import aiohttp
6
+ from yarl import URL
7
+
8
+ from .const import API_PATH, DEFAULT_PORT, DEFAULT_TIMEOUT
9
+ from .device import PironmanDeviceInfo
10
+ from .exceptions import (
11
+ PironmanAPIError,
12
+ PironmanConnectionError,
13
+ PironmanResponseError,
14
+ PironmanTimeoutError,
15
+ )
16
+
17
+
18
+ class PironmanClient:
19
+ """Communicate with a Pironman device over its local REST API."""
20
+
21
+ def __init__(
22
+ self,
23
+ host: str,
24
+ session: aiohttp.ClientSession,
25
+ *,
26
+ port: int = DEFAULT_PORT,
27
+ timeout: float = DEFAULT_TIMEOUT,
28
+ ) -> None:
29
+ """Initialize with an externally managed HTTP session."""
30
+ host = host.strip()
31
+
32
+ if not host or any(char in host for char in "/?#@"):
33
+ raise ValueError("Invalid Pironman host")
34
+
35
+ if any(char.isspace() for char in host):
36
+ raise ValueError("Invalid Pironman host")
37
+
38
+ if not 1 <= port <= 65535:
39
+ raise ValueError("Invalid Pironman API port")
40
+
41
+ if timeout <= 0:
42
+ raise ValueError("Timeout must be positive")
43
+
44
+ if host.startswith("[") and host.endswith("]"):
45
+ host = host[1:-1]
46
+
47
+ self._session = session
48
+ self._base_url = URL.build(
49
+ scheme="http",
50
+ host=host,
51
+ port=port,
52
+ path=API_PATH,
53
+ )
54
+ self._timeout = aiohttp.ClientTimeout(total=timeout)
55
+
56
+ async def _async_get(self, endpoint: str) -> object:
57
+ """Request and validate an API response."""
58
+ try:
59
+ async with self._session.get(
60
+ self._base_url / endpoint,
61
+ timeout=self._timeout,
62
+ allow_redirects=False,
63
+ ) as response:
64
+ if not 200 <= response.status < 300:
65
+ raise PironmanAPIError(f"{endpoint}: HTTP {response.status}")
66
+
67
+ try:
68
+ result = await response.json()
69
+ except (ValueError, aiohttp.ContentTypeError) as err:
70
+ raise PironmanResponseError(f"{endpoint}: invalid JSON") from err
71
+
72
+ except TimeoutError as err:
73
+ raise PironmanTimeoutError(f"{endpoint}: request timed out") from err
74
+
75
+ except aiohttp.ClientError as err:
76
+ raise PironmanConnectionError(f"{endpoint}: connection failed") from err
77
+
78
+ if not isinstance(result, dict):
79
+ raise PironmanResponseError(f"{endpoint}: expected JSON object")
80
+
81
+ if result.get("status") is not True:
82
+ raise PironmanAPIError(f"{endpoint}: unsuccessful API status")
83
+
84
+ if "data" not in result:
85
+ raise PironmanResponseError(f"{endpoint}: missing data field")
86
+
87
+ return result["data"]
88
+
89
+ async def _async_get_object(
90
+ self,
91
+ endpoint: str,
92
+ ) -> dict[str, Any]:
93
+ """Request an endpoint returning an object."""
94
+ data = await self._async_get(endpoint)
95
+
96
+ if not isinstance(data, dict):
97
+ raise PironmanResponseError(f"{endpoint}: expected object data")
98
+
99
+ return cast(dict[str, Any], data)
100
+
101
+ async def async_get_device_info(self) -> dict[str, Any]:
102
+ """Return device metadata."""
103
+ return await self._async_get_object("get-device-info")
104
+
105
+ async def async_get_data(self) -> dict[str, Any]:
106
+ """Return current hardware measurements."""
107
+ return await self._async_get_object("get-data")
108
+
109
+ async def async_get_config(self) -> dict[str, Any]:
110
+ """Return device configuration."""
111
+ return await self._async_get_object("get-config")
112
+
113
+ async def async_get_ips(self) -> object:
114
+ """Return optional network interface information."""
115
+ return await self._async_get("get-ips")
116
+
117
+ async def async_get_device_metadata(self) -> PironmanDeviceInfo:
118
+ """Return typed device identity and capability metadata."""
119
+ data = await self.async_get_device_info()
120
+ return PironmanDeviceInfo.from_api(data)
pironman/const.py ADDED
@@ -0,0 +1,5 @@
1
+ """Constants for the Pironman REST API."""
2
+
3
+ DEFAULT_PORT = 34001
4
+ DEFAULT_TIMEOUT = 5.0
5
+ API_PATH = "/api/v1.0"
pironman/device.py ADDED
@@ -0,0 +1,65 @@
1
+ """Typed device identity and capability metadata."""
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass
5
+
6
+ from .models import detect_model
7
+
8
+
9
+ def _optional_string(value: object) -> str | None:
10
+ """Return a non-empty string when available."""
11
+ if not isinstance(value, str):
12
+ return None
13
+
14
+ value = value.strip()
15
+ return value or None
16
+
17
+
18
+ def _parse_peripherals(value: object) -> frozenset[str] | None:
19
+ """Parse explicit peripheral metadata without guessing."""
20
+ if not isinstance(value, list):
21
+ return None
22
+
23
+ if not all(isinstance(item, str) and item.strip() for item in value):
24
+ return None
25
+
26
+ return frozenset(item.strip().casefold() for item in value)
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class PironmanDeviceInfo:
31
+ """Identity and capabilities reported by a Pironman device."""
32
+
33
+ name: str | None
34
+ model: str | None
35
+ model_id: str | None
36
+ version: str | None
37
+ device_uid: str | None
38
+ peripherals: frozenset[str] | None
39
+
40
+ @classmethod
41
+ def from_api(
42
+ cls,
43
+ data: Mapping[str, object],
44
+ ) -> "PironmanDeviceInfo":
45
+ """Parse vendor device metadata."""
46
+ return cls(
47
+ name=_optional_string(data.get("name")),
48
+ model=detect_model(data),
49
+ model_id=_optional_string(data.get("id")),
50
+ version=_optional_string(data.get("version")),
51
+ device_uid=_optional_string(data.get("device_uid")),
52
+ peripherals=_parse_peripherals(data.get("peripherals")),
53
+ )
54
+
55
+ @property
56
+ def has_persistent_identity(self) -> bool:
57
+ """Return whether the API supplies a candidate device UID."""
58
+ return self.device_uid is not None
59
+
60
+ def supports(self, peripheral: str) -> bool | None:
61
+ """Return explicit support or None when unknown."""
62
+ if self.peripherals is None:
63
+ return None
64
+
65
+ return peripheral.strip().casefold() in self.peripherals
pironman/exceptions.py ADDED
@@ -0,0 +1,21 @@
1
+ """Exceptions for the Pironman REST API."""
2
+
3
+
4
+ class PironmanError(Exception):
5
+ """Base exception for Pironman errors."""
6
+
7
+
8
+ class PironmanConnectionError(PironmanError):
9
+ """Unable to communicate with the Pironman API."""
10
+
11
+
12
+ class PironmanTimeoutError(PironmanConnectionError):
13
+ """The API request timed out."""
14
+
15
+
16
+ class PironmanAPIError(PironmanError):
17
+ """The API rejected a request."""
18
+
19
+
20
+ class PironmanResponseError(PironmanError):
21
+ """The API returned an invalid response."""
pironman/models.py ADDED
@@ -0,0 +1,64 @@
1
+ """Pironman enclosure model identification (independent of Home Assistant)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+
7
+ MODEL_NAMES = {
8
+ "base": "Pironman 5",
9
+ "mini": "Pironman 5 Mini",
10
+ "max": "Pironman 5 Max",
11
+ "pro_max": "Pironman 5 Pro Max",
12
+ }
13
+
14
+ MODEL_IDS = {
15
+ "pironman5": "base",
16
+ "pironman5-mini": "mini",
17
+ "pironman5-max": "max",
18
+ "pironman5-pro-max": "pro_max",
19
+ }
20
+
21
+ AUTO = "auto"
22
+
23
+
24
+ def normalize_model(value: object) -> str | None:
25
+ """Normalize vendor model variants without guessing from peripherals."""
26
+ if not isinstance(value, str):
27
+ return None
28
+ key = value.strip().casefold().replace("_", "-")
29
+ if key in MODEL_IDS:
30
+ return MODEL_IDS[key]
31
+ if key in ("base", "mini", "max", "pro-max"):
32
+ return "pro_max" if key == "pro-max" else key
33
+ names = {name.casefold(): key for key, name in MODEL_NAMES.items()}
34
+ return names.get(key)
35
+
36
+
37
+ def detect_model(info: Mapping[str, object] | None) -> str | None:
38
+ """Detect from explicit API metadata, returning None when ambiguous.
39
+
40
+ A vendor-supplied generic `name=Pironman 5` is NOT sufficient evidence
41
+ for the base model: older firmware may report that for every variant.
42
+ """
43
+ if not isinstance(info, Mapping):
44
+ return None
45
+ for key in ("id", "variant", "model_id", "product_id", "product", "model"):
46
+ result = normalize_model(info.get(key))
47
+ if result is not None:
48
+ return result
49
+ name = info.get("name")
50
+ result = normalize_model(name)
51
+ return result if result != "base" else None
52
+
53
+
54
+ def resolve_model(
55
+ info: Mapping[str, object] | None, selection: str = AUTO
56
+ ) -> tuple[str | None, str]:
57
+ """Return (model, detection source). A manual selection always wins."""
58
+ if selection != AUTO:
59
+ model = normalize_model(selection)
60
+ if model is None:
61
+ raise ValueError(f"Unsupported model: {selection}")
62
+ return model, "manual"
63
+ detected = detect_model(info)
64
+ return detected, "automatic" if detected else "unknown"
pironman/py.typed ADDED
File without changes
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.5
2
+ Name: python-pironman
3
+ Version: 0.1.0
4
+ Summary: Async Python client for the SunFounder Pironman REST API
5
+ Project-URL: Repository, https://github.com/ChristophKomenda/python-pironman
6
+ Project-URL: Issues, https://github.com/ChristophKomenda/python-pironman/issues
7
+ Author: Christoph Komenda
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.12
14
+ Requires-Dist: aiohttp<4,>=3.10
15
+ Requires-Dist: yarl<2,>=1.12
16
+ Provides-Extra: test
17
+ Requires-Dist: build; extra == 'test'
18
+ Requires-Dist: mypy; extra == 'test'
19
+ Requires-Dist: pytest; extra == 'test'
20
+ Requires-Dist: pytest-asyncio; extra == 'test'
21
+ Requires-Dist: pytest-cov; extra == 'test'
22
+ Requires-Dist: ruff; extra == 'test'
23
+ Requires-Dist: twine; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # Python Pironman
27
+
28
+ An independent asynchronous Python library for the local
29
+ SunFounder Pironman hardware REST API.
30
+
31
+ ## Project goals
32
+
33
+ - Asynchronous HTTP communication using aiohttp.
34
+ - Typed device metadata and hardware capabilities.
35
+ - Read-only monitoring as the initial implementation.
36
+ - Support for externally managed HTTP sessions.
37
+ - Consistent API error handling.
38
+ - Automated tests and hardware validation.
39
+ - Reusable by Home Assistant and other Python applications.
40
+
41
+ ## Status
42
+
43
+ Version 0.1.0 is prepared for initial publication on PyPI.
44
+
45
+ Physical hardware validation has been completed on two Pironman 5 Max devices running API version 1.3.21.
46
+
47
+ Recognition of other Pironman models does not establish verified hardware compatibility.
48
+
49
+ This project is independently maintained and is not an
50
+ official SunFounder or Home Assistant integration.
51
+
52
+ ## Usage
53
+
54
+ Install the development package in a virtual environment:
55
+
56
+ pip install -e .
57
+
58
+ Read basic device information:
59
+
60
+ python examples/read_device.py 192.0.2.10
61
+
62
+ Replace the example address with the actual Pironman host.
63
+
64
+ The caller owns the aiohttp ClientSession.
65
+ The library never closes externally managed sessions.
66
+
67
+ ### Supported endpoints
68
+
69
+ - GET /api/v1.0/get-device-info
70
+ - GET /api/v1.0/get-data
71
+ - GET /api/v1.0/get-config
72
+ - GET /api/v1.0/get-ips
73
+
74
+ The initial implementation is read-only.
75
+ No Home Assistant dependency is required.
76
+
77
+ The network endpoint is optional on older API versions.
78
+ Persistent device identity remains pending upstream review.
79
+
80
+ ## Device identity and capabilities
81
+
82
+ Read typed device metadata using:
83
+
84
+ python examples/read_metadata.py 192.0.2.10
85
+
86
+ Persistent device UID support is optional.
87
+
88
+ Model identifiers are never used as physical device IDs.
89
+ Missing capability information is represented as unknown.
90
+
91
+ See [Device identity](docs/device-identity.md).
92
+
93
+ ## Related projects
94
+
95
+ - [Pironman HACS integration](https://github.com/ChristophKomenda/pironman5-homeassistant-container)
96
+ - [SunFounder Pironman software](https://github.com/sunfounder/pironman5)
97
+ - [Upstream device identity proposal](https://github.com/sunfounder/pironman5/pull/130)
98
+
99
+ ## License
100
+
101
+ MIT
@@ -0,0 +1,11 @@
1
+ pironman/__init__.py,sha256=1hzotHm4HH1WmgwHFugCtmwlP9wXxAcctTLyxySF0Ns,483
2
+ pironman/client.py,sha256=000SNhM9Znx0HFM7MO5MLiGsRedaAaOhV9qkB3DWWj8,4002
3
+ pironman/const.py,sha256=DOSh-q7xjA-0eIuSrM7l-EmVtsvXWV4HUO7kw8f4Q0Y,110
4
+ pironman/device.py,sha256=1lvDbTV1vo2CUbASEv1cbi1vEpWseWP3aGLKMqGrL_w,1953
5
+ pironman/exceptions.py,sha256=fhplb1NznlnUv3JJVrLp-h4-38xetE7hxz2-ks07u_U,492
6
+ pironman/models.py,sha256=NQhquAnMej2oDqwa1aTodgRkPt5R9CEFGYBw_jV6u3U,2064
7
+ pironman/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ python_pironman-0.1.0.dist-info/METADATA,sha256=2r2eUbeIrV34zWPsQwD-ENDMFV24cjTAy9CILfxLknE,3046
9
+ python_pironman-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ python_pironman-0.1.0.dist-info/licenses/LICENSE,sha256=3Cl9k97yBvPE1FEawGirCcRiCMCMp9OoVommYAl77u4,1074
11
+ python_pironman-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Christoph Komenda
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.