pyhearth 1.0.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.
pyhearth/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ __copyright__ = "Copyright (c) 2026 Alex Laird"
2
+ __license__ = "MIT"
3
+ __version__ = "1.0.0"
pyhearth/client.py ADDED
@@ -0,0 +1,148 @@
1
+ __copyright__ = "Copyright (c) 2026 Alex Laird"
2
+ __license__ = "MIT"
3
+
4
+ import json
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Final
7
+
8
+ import aiohttp
9
+
10
+ from pyhearth.exception import (
11
+ HearthAuthError,
12
+ HearthConnectionError,
13
+ HearthDemoHomeError,
14
+ HearthRateLimitedError,
15
+ HearthRejectedError,
16
+ )
17
+
18
+ #: Where Hearth's API is.
19
+ DEFAULT_API_URL: Final = "https://api.meethearth.app"
20
+ #: The version of the bridge protocol Hearth's ``/v1/bridge`` endpoint speaks.
21
+ PROTOCOL: Final = 1
22
+ #: How long one request to Hearth may take, in seconds.
23
+ REQUEST_TIMEOUT: Final = 15
24
+ #: How many seconds to wait when Hearth asks to slow down without saying for how long.
25
+ DEFAULT_RETRY_AFTER: Final = 60
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class ReadingsResult:
30
+ """
31
+ What Hearth said about a readings post.
32
+ """
33
+
34
+ #: The posted sensors that aren't added to a room in the Hearth app yet (Hearth drops their readings).
35
+ not_added: list[str] = field(default_factory=list)
36
+
37
+
38
+ class HearthClient:
39
+ """
40
+ A connection to one Hearth home through its API key: ``/v1/bridge`` for the thermostat and ``/v1/readings`` for
41
+ room sensors.
42
+ """
43
+
44
+ def __init__(self,
45
+ session: aiohttp.ClientSession,
46
+ api_key: str,
47
+ base_url: str = DEFAULT_API_URL,
48
+ *,
49
+ source: str | None = None,
50
+ source_name: str | None = None) -> None:
51
+ self._session = session
52
+ self._api_key = api_key
53
+
54
+ #: Where Hearth's API is (Hearth's own unless pointed at another backend).
55
+ self.base_url: str = base_url.rstrip("/")
56
+ #: The readings source this client posts as (Hearth's default, ``api``, if not given): Hearth keeps each
57
+ #: source's sensors and outages apart.
58
+ self.source: str | None = source
59
+ #: How the Hearth app names the source, if given.
60
+ self.source_name: str | None = source_name
61
+
62
+ async def check_key(self) -> None:
63
+ """
64
+ Check that Hearth takes the API key, with an empty readings post (which changes nothing).
65
+
66
+ :raises: :class:`~pyhearth.exception.HearthError`: When Hearth doesn't take the key or can't be reached.
67
+ """
68
+ await self._post("/v1/readings", self._readings_payload([], named=False))
69
+
70
+ async def sync_thermostat(self,
71
+ thermostat: dict[str, Any],
72
+ refused: dict[str, Any] | None = None) -> dict[str, Any] | None:
73
+ """
74
+ Post the thermostat to Hearth.
75
+
76
+ :param thermostat: The thermostat, as ``/v1/bridge`` takes it.
77
+ :param refused: The last setting that couldn't be applied (as Hearth answered it), why, and who refused it.
78
+ :return: The setting Hearth wants applied, if any.
79
+ :raises: :class:`~pyhearth.exception.HearthError`: When Hearth refuses the post or can't be reached.
80
+ """
81
+ payload: dict[str, Any] = {"protocol": PROTOCOL, "thermostat": thermostat}
82
+ if refused is not None:
83
+ payload["refused"] = refused
84
+ status, body = await self._post("/v1/bridge", payload)
85
+ desired = body.get("desired") if status == 200 and isinstance(body, dict) else None
86
+ return desired if isinstance(desired, dict) else None
87
+
88
+ async def post_readings(self, sensors: list[dict[str, Any]]) -> ReadingsResult:
89
+ """
90
+ Post room sensors' readings to Hearth, which keeps only those of sensors added in its app.
91
+
92
+ :param sensors: The readings, as ``/v1/readings`` takes them.
93
+ :return: What Hearth said about them.
94
+ :raises: :class:`~pyhearth.exception.HearthError`: When Hearth refuses the post or can't be reached.
95
+ """
96
+ status, body = await self._post("/v1/readings", self._readings_payload(sensors, named=True))
97
+ if status == 422:
98
+ return ReadingsResult([str(sensor["id"]) for sensor in sensors])
99
+ not_added = body.get("not_added") if isinstance(body, dict) else None
100
+ return ReadingsResult([str(name) for name in not_added] if isinstance(not_added, list) else [])
101
+
102
+ def _readings_payload(self, sensors: list[dict[str, Any]], named: bool) -> dict[str, Any]:
103
+ payload: dict[str, Any] = {}
104
+ if self.source is not None:
105
+ payload["source"] = self.source
106
+ if named and self.source_name is not None:
107
+ payload["name"] = self.source_name
108
+ payload["sensors"] = sensors
109
+ return payload
110
+
111
+ async def _post(self, path: str, payload: dict[str, Any]) -> tuple[int, Any]:
112
+ try:
113
+ async with self._session.post(f"{self.base_url}{path}",
114
+ json=payload,
115
+ headers={"Authorization": f"Bearer {self._api_key}"},
116
+ timeout=aiohttp.ClientTimeout(total=REQUEST_TIMEOUT)) as response:
117
+ text = await response.text()
118
+ status = response.status
119
+ retry_after = response.headers.get("Retry-After")
120
+ except (aiohttp.ClientError, TimeoutError) as e:
121
+ raise HearthConnectionError(f"Couldn't reach Hearth: {e}") from e
122
+
123
+ if status in (200, 204, 422):
124
+ return status, _json(text) if text else None
125
+ elif status == 401:
126
+ raise HearthAuthError("Hearth didn't accept the API key.")
127
+ elif status == 403:
128
+ raise HearthDemoHomeError(text or "The API key belongs to a demo home.")
129
+ elif status == 429:
130
+ raise HearthRateLimitedError("Hearth asked for fewer posts.", {"retry_after": _seconds(retry_after)})
131
+ elif status >= 500:
132
+ raise HearthConnectionError(f"Hearth answered {status}.")
133
+ else:
134
+ raise HearthRejectedError(text[:300] or f"Hearth answered {status}.")
135
+
136
+
137
+ def _json(text: str) -> Any:
138
+ try:
139
+ return json.loads(text)
140
+ except ValueError:
141
+ return None
142
+
143
+
144
+ def _seconds(value: str | None) -> int:
145
+ try:
146
+ return max(1, int(value)) if value is not None else DEFAULT_RETRY_AFTER
147
+ except ValueError:
148
+ return DEFAULT_RETRY_AFTER
pyhearth/exception.py ADDED
@@ -0,0 +1,53 @@
1
+ __copyright__ = "Copyright (c) 2026 Alex Laird"
2
+ __license__ = "MIT"
3
+
4
+ from typing import Any
5
+
6
+
7
+ class HearthError(Exception):
8
+ """
9
+ Raised when a general Hearth API error has occurred.
10
+ """
11
+
12
+ def __init__(self,
13
+ error: str | BaseException,
14
+ meta: dict[str, Any] | None = None) -> None:
15
+ super(HearthError, self).__init__(error)
16
+
17
+ #: Metadata for context around the error that was raised.
18
+ self.meta: dict[str, Any] | None = meta
19
+
20
+
21
+ class HearthAuthError(HearthError):
22
+ """
23
+ Raised when Hearth doesn't accept the API key (it's wrong, it was replaced, or its home is gone).
24
+ """
25
+ pass
26
+
27
+
28
+ class HearthDemoHomeError(HearthError):
29
+ """
30
+ Raised when the API key belongs to a demo home, which runs on a simulated thermostat and takes no posts.
31
+ """
32
+ pass
33
+
34
+
35
+ class HearthRateLimitedError(HearthError):
36
+ """
37
+ Raised when Hearth asks for fewer posts. ``meta["retry_after"]`` is how many seconds to wait.
38
+ """
39
+ pass
40
+
41
+
42
+ class HearthRejectedError(HearthError):
43
+ """
44
+ Raised when Hearth can't read a post. The error's message is Hearth's reason.
45
+ """
46
+ pass
47
+
48
+
49
+ class HearthConnectionError(HearthError):
50
+ """
51
+ Raised when Hearth can't be reached (the network, a timeout, or an error on Hearth's side).
52
+ """
53
+ pass
pyhearth/py.typed ADDED
File without changes
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyhearth
3
+ Version: 1.0.0
4
+ Summary: A Python client for Hearth's home API: post a thermostat and room sensor readings to a Hearth home
5
+ Author-email: Alex Laird <contact@alexlaird.com>
6
+ Maintainer-email: Alex Laird <contact@alexlaird.com>
7
+ License-Expression: MIT
8
+ Project-URL: Changelog, https://github.com/alexdlaird/pyhearth/blob/main/CHANGELOG.md
9
+ Project-URL: Documentation, https://github.com/alexdlaird/pyhearth#readme
10
+ Project-URL: Sponsor, https://github.com/sponsors/alexdlaird
11
+ Project-URL: Source Code, https://github.com/alexdlaird/pyhearth
12
+ Keywords: hearth,thermostat,climate,room-sensors,home-automation,daikin,asyncio
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Home Automation
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: aiohttp>=3.9
29
+ Provides-Extra: dev
30
+ Requires-Dist: coverage[toml]; extra == "dev"
31
+ Requires-Dist: flake8; extra == "dev"
32
+ Requires-Dist: flake8-pyproject; extra == "dev"
33
+ Requires-Dist: pep8-naming; extra == "dev"
34
+ Requires-Dist: mypy; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ [![Version](https://img.shields.io/pypi/v/pyhearth)](https://pypi.org/project/pyhearth)
38
+ [![Python Versions](https://img.shields.io/pypi/pyversions/pyhearth.svg)](https://pypi.org/project/pyhearth)
39
+ [![Coverage](https://img.shields.io/codecov/c/github/alexdlaird/pyhearth)](https://codecov.io/gh/alexdlaird/pyhearth)
40
+ [![Build](https://img.shields.io/github/actions/workflow/status/alexdlaird/pyhearth/build.yml)](https://github.com/alexdlaird/pyhearth/actions/workflows/build.yml)
41
+ [![GitHub License](https://img.shields.io/github/license/alexdlaird/pyhearth)](https://github.com/alexdlaird/pyhearth/blob/main/LICENSE)
42
+
43
+ `pyhearth` is a Python client for [Hearth](https://www.meethearth.app)'s home API. It posts room sensor readings, and
44
+ optionally a thermostat, to a Hearth home with the home's API key, and returns the thermostat setting Hearth answers
45
+ with. It's what [`ha-hearth`](https://github.com/alexdlaird/ha-hearth), Hearth's Home Assistant integration, uses to
46
+ talk to Hearth.
47
+
48
+ ## Installation
49
+
50
+ `pyhearth` is available on [PyPI](https://pypi.org/project/pyhearth/) and can be installed using `pip`:
51
+
52
+ ```sh
53
+ pip install pyhearth
54
+ ```
55
+
56
+ ## Basic Usage
57
+
58
+ In the Hearth app, create the home's API key in Settings, then Manage home, then Sensors, then "Other sensors (Hearth
59
+ API)". Then post readings:
60
+
61
+ ```python
62
+ import asyncio
63
+
64
+ import aiohttp
65
+
66
+ from pyhearth.client import HearthClient
67
+
68
+
69
+ async def main():
70
+ async with aiohttp.ClientSession() as session:
71
+ client = HearthClient(session, "<your API key>", source="my-hub", source_name="My hub")
72
+ result = await client.post_readings([
73
+ {"id": "office", "name": "Office", "temperature": 20.8, "humidity": 41}
74
+ ])
75
+ print(result.not_added)
76
+
77
+
78
+ asyncio.run(main())
79
+ ```
80
+
81
+ A sensor's readings are kept once it's added to a room in the Hearth app; until then, it's listed in `not_added`. The
82
+ fields each endpoint takes are in [Hearth's API docs](https://www.meethearth.app/support.html#hearth-api).
83
+
84
+ Errors are raised as subclasses of `HearthError` (in `pyhearth.exception`): `HearthAuthError` when Hearth doesn't take
85
+ the key, `HearthRateLimitedError` when it asks for fewer posts (`meta["retry_after"]` says how many seconds to wait),
86
+ `HearthRejectedError` when it can't read a post, and `HearthConnectionError` when it can't be reached.
87
+
88
+ ## Contributing
89
+
90
+ If you would like to get involved, be sure to review
91
+ the [Contribution Guide](https://github.com/alexdlaird/pyhearth/blob/main/CONTRIBUTING.rst).
92
+
93
+ Want to contribute financially? If you've found `pyhearth` useful, [sponsorship](https://github.com/sponsors/alexdlaird)
94
+ would also be greatly appreciated!
@@ -0,0 +1,9 @@
1
+ pyhearth/__init__.py,sha256=5rtuFu5MRgQ1gHCXL0bWgH7oYD_eCj5k-Px7srvfAbo,90
2
+ pyhearth/client.py,sha256=k_R_FlE42enlUPiMEZgl7QjvgCTzM0nM3mpY5vAuKqM,6131
3
+ pyhearth/exception.py,sha256=-xMKjXPBq-nds__Kfpd6ucdikl9UlGNo6gdWQSmR95s,1315
4
+ pyhearth/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ pyhearth-1.0.0.dist-info/licenses/LICENSE,sha256=DH_vojkclcvS70LqmgQH3kdwpjEw_0_IAu9KfSniq98,1067
6
+ pyhearth-1.0.0.dist-info/METADATA,sha256=q8w7zlKwmNOlQUrp_PD16woq6ikhLy23GwCNZdxVQSg,4252
7
+ pyhearth-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ pyhearth-1.0.0.dist-info/top_level.txt,sha256=hjXrHO0pUJUxh12yFRjvdHb09XzWAK_jFQHh0W-qxj0,9
9
+ pyhearth-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alex Laird
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 @@
1
+ pyhearth