heiman-local-client 0.1.1__tar.gz

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.
@@ -0,0 +1,58 @@
1
+ name: Publish to PyPI
2
+
3
+ "on":
4
+ push:
5
+ branches: [main]
6
+ tags: ["v*"]
7
+
8
+ permissions: {}
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+ permissions:
14
+ contents: read
15
+ steps:
16
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
17
+ with:
18
+ persist-credentials: false
19
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
20
+ with:
21
+ python-version: "3.14"
22
+ - name: Verify the release tag
23
+ if: github.ref_type == 'tag'
24
+ run: |
25
+ python - <<'PY'
26
+ import os
27
+ from pathlib import Path
28
+ import tomllib
29
+
30
+ version = tomllib.loads(Path("pyproject.toml").read_text())["project"]["version"]
31
+ expected = f"v{version}"
32
+ if os.environ["GITHUB_REF_NAME"] != expected:
33
+ raise SystemExit(f"Expected release tag {expected}")
34
+ PY
35
+ - name: Build and check distributions
36
+ run: |
37
+ python -m pip install build twine
38
+ python -m build
39
+ python -m twine check --strict dist/*
40
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
41
+ with:
42
+ name: distributions
43
+ path: dist/
44
+ if-no-files-found: error
45
+
46
+ publish:
47
+ if: github.ref_type == 'tag'
48
+ runs-on: ubuntu-latest
49
+ needs: build
50
+ environment: pypi
51
+ permissions:
52
+ id-token: write
53
+ steps:
54
+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
55
+ with:
56
+ name: distributions
57
+ path: dist/
58
+ - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
@@ -0,0 +1 @@
1
+ /dist/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Heiman Local contributors
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.
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.5
2
+ Name: heiman-local-client
3
+ Version: 0.1.1
4
+ Summary: Asynchronous LAN client for a Heiman Wi-Fi switch
5
+ Project-URL: Source, https://github.com/Leo2442926161/Heiman_local
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: aiohttp>=3.9
10
+ Requires-Dist: yarl>=1.9
11
+ Description-Content-Type: text/markdown
12
+
13
+ # Heiman Local Client
14
+
15
+ An asynchronous Python client for a direct Heiman Wi-Fi switch implementing the `heiman_wifi_v1` LAN HTTP protocol. The caller supplies and closes an `aiohttp.ClientSession`.
16
+
17
+ ```python
18
+ from aiohttp import ClientSession
19
+ from heiman_local_client import HeimanSwitchClient
20
+
21
+
22
+ async def read_switch_power(host: str) -> bool:
23
+ async with ClientSession() as session:
24
+ switch = HeimanSwitchClient(session, host, 80)
25
+ info = await switch.get_info()
26
+ return await switch.get_power(info)
27
+ ```
28
+
29
+ Build a wheel and source distribution with `uv build`. To test the Home Assistant Core integration locally, install the wheel in the Core development environment before running its integration tests.
30
+
31
+ ## Releasing
32
+
33
+ Set the public source repository URL under `[project.urls]` in `pyproject.toml`. In PyPI, configure a Trusted Publisher for this repository with the workflow filename `publish.yml` and the GitHub environment `pypi`.
34
+
35
+ Publish a GitHub release with a tag matching the package version, such as `v0.1.0`. The workflow checks the tag, builds and checks the distributions, and publishes them to PyPI. Include the public workflow and release-tag links in the Home Assistant Core pull request.
@@ -0,0 +1,23 @@
1
+ # Heiman Local Client
2
+
3
+ An asynchronous Python client for a direct Heiman Wi-Fi switch implementing the `heiman_wifi_v1` LAN HTTP protocol. The caller supplies and closes an `aiohttp.ClientSession`.
4
+
5
+ ```python
6
+ from aiohttp import ClientSession
7
+ from heiman_local_client import HeimanSwitchClient
8
+
9
+
10
+ async def read_switch_power(host: str) -> bool:
11
+ async with ClientSession() as session:
12
+ switch = HeimanSwitchClient(session, host, 80)
13
+ info = await switch.get_info()
14
+ return await switch.get_power(info)
15
+ ```
16
+
17
+ Build a wheel and source distribution with `uv build`. To test the Home Assistant Core integration locally, install the wheel in the Core development environment before running its integration tests.
18
+
19
+ ## Releasing
20
+
21
+ Set the public source repository URL under `[project.urls]` in `pyproject.toml`. In PyPI, configure a Trusted Publisher for this repository with the workflow filename `publish.yml` and the GitHub environment `pypi`.
22
+
23
+ Publish a GitHub release with a tag matching the package version, such as `v0.1.0`. The workflow checks the tag, builds and checks the distributions, and publishes them to PyPI. Include the public workflow and release-tag links in the Home Assistant Core pull request.
@@ -0,0 +1,16 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "heiman-local-client"
7
+ version = "0.1.1"
8
+ description = "Asynchronous LAN client for a Heiman Wi-Fi switch"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = ["aiohttp>=3.9", "yarl>=1.9"]
14
+
15
+ [project.urls]
16
+ Source = "https://github.com/Leo2442926161/Heiman_local"
@@ -0,0 +1,142 @@
1
+ """Asynchronous client for a direct Heiman Wi-Fi switch."""
2
+
3
+ from dataclasses import dataclass
4
+ import json
5
+ import re
6
+ from typing import Any
7
+
8
+ from aiohttp import ClientError, ClientSession, ClientTimeout
9
+ from yarl import URL
10
+
11
+ _SCHEMA = "heiman_wifi_v1"
12
+ _SWITCH_TYPES = {"sw", "switch", "smart_switch"}
13
+ _TIMEOUT = ClientTimeout(total=5)
14
+ _MAC_PATTERN = re.compile(r"[0-9a-f]{12}")
15
+
16
+
17
+ class HeimanError(Exception):
18
+ """A request failed or the switch returned an invalid response."""
19
+
20
+
21
+ class UnsupportedDevice(HeimanError):
22
+ """The endpoint does not identify a supported Heiman switch."""
23
+
24
+
25
+ def _mac(value: Any) -> str | None:
26
+ if isinstance(value, str):
27
+ compact = value.strip().lower().replace(":", "").replace("-", "")
28
+ if _MAC_PATTERN.fullmatch(compact) and compact != "000000000000":
29
+ return compact
30
+ return None
31
+
32
+
33
+ def _text(data: dict[str, Any], *keys: str) -> str | None:
34
+ for key in keys:
35
+ if isinstance(value := data.get(key), str) and value.strip():
36
+ return value.strip()
37
+ return None
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class SwitchInfo:
42
+ """Identity and metadata advertised by the switch."""
43
+
44
+ mac: str
45
+ name: str
46
+ model: str | None
47
+ firmware: str | None
48
+ endpoint_id: str | None
49
+
50
+
51
+ class HeimanSwitchClient:
52
+ """Read and control one switch using an injected HTTP session."""
53
+
54
+ def __init__(self, session: ClientSession, host: str, port: int) -> None:
55
+ """Store the local HTTP address and session."""
56
+ self._session = session
57
+ self._url = URL.build(scheme="http", host=host, port=port)
58
+
59
+ async def _request(
60
+ self, method: str, path: str, payload: dict[str, Any] | None = None
61
+ ) -> dict[str, Any]:
62
+ try:
63
+ async with self._session.request(
64
+ method,
65
+ self._url / path,
66
+ json=payload,
67
+ timeout=_TIMEOUT,
68
+ allow_redirects=False,
69
+ ) as response:
70
+ if not 200 <= response.status < 300:
71
+ raise HeimanError(f"/{path} returned HTTP {response.status}")
72
+ body = await response.read()
73
+ except (ClientError, TimeoutError) as err:
74
+ raise HeimanError(f"Request to /{path} failed") from err
75
+
76
+ if method == "POST" and not body.strip():
77
+ return {}
78
+
79
+ try:
80
+ data = json.loads(body)
81
+ except (ValueError, RecursionError) as err:
82
+ raise HeimanError(f"/{path} returned invalid JSON") from err
83
+ if not isinstance(data, dict):
84
+ raise HeimanError(f"/{path} must return a JSON object")
85
+ return data
86
+
87
+ async def get_info(self) -> SwitchInfo:
88
+ """Read the switch identity and check the protocol version."""
89
+ data = await self._request("GET", "info")
90
+ mac = _mac(data.get("mac")) or _mac(data.get("macAddress"))
91
+ device_type = _text(data, "deviceType", "type", "typeCode")
92
+ if (
93
+ data.get("schema") != _SCHEMA
94
+ or mac is None
95
+ or device_type is None
96
+ or device_type.lower() not in _SWITCH_TYPES
97
+ ):
98
+ raise UnsupportedDevice("Expected a heiman_wifi_v1 switch with a MAC")
99
+
100
+ model = _text(data, "model", "productModel")
101
+ return SwitchInfo(
102
+ mac=mac,
103
+ name=_text(data, "name", "deviceName") or model or "Heiman Wi-Fi Switch",
104
+ model=model,
105
+ firmware=_text(data, "firmwareVersion", "version"),
106
+ endpoint_id=_text(data, "id", "device_id"),
107
+ )
108
+
109
+ async def get_power(self, info: SwitchInfo) -> bool:
110
+ """Read the root switch's Boolean power state."""
111
+ data = await self._request("GET", "state")
112
+ properties = data.get("properties", data)
113
+ if isinstance(properties, dict) and isinstance(
114
+ power := properties.get("power"), bool
115
+ ):
116
+ return power
117
+
118
+ devices = data.get("devices")
119
+ if isinstance(devices, list):
120
+ for device in devices:
121
+ if not isinstance(device, dict):
122
+ continue
123
+ endpoint = _text(device, "id", "device_id", "mac")
124
+ if endpoint is None or (
125
+ endpoint != info.endpoint_id and _mac(endpoint) != info.mac
126
+ ):
127
+ continue
128
+ properties = device.get("properties")
129
+ if isinstance(properties, dict) and isinstance(
130
+ power := properties.get("power"), bool
131
+ ):
132
+ return power
133
+
134
+ raise HeimanError("/state has no Boolean power value for the root switch")
135
+
136
+ async def set_power(self, is_on: bool) -> None:
137
+ """Send an explicit Boolean power command to the direct switch."""
138
+ result = await self._request(
139
+ "POST", "control", {"property": "power", "value": is_on}
140
+ )
141
+ if result.get("ok") is False or result.get("success") is False:
142
+ raise HeimanError("The switch rejected the power command")