aiopapouch 0.1.0__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,218 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Levad
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,17 @@
1
+ Metadata-Version: 2.5
2
+ Name: aiopapouch
3
+ Version: 0.1.0
4
+ Summary: API client and device models for Papouch's devices
5
+ Project-URL: Source, https://github.com/VladislavLevitskii/aiopapouch
6
+ Author-email: VladislavLevitskii <vladlevitskii@gmail.com>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: aiohttp>=3.0.0
11
+ Requires-Dist: defusedxml>=0.7.1
12
+ Description-Content-Type: text/markdown
13
+
14
+ # aiopapouch
15
+ The repository contains I/O Python library for Papouch s.r.o. devices.
16
+
17
+ # TODO structure and big picture
@@ -0,0 +1,4 @@
1
+ # aiopapouch
2
+ The repository contains I/O Python library for Papouch s.r.o. devices.
3
+
4
+ # TODO structure and big picture
@@ -0,0 +1,12 @@
1
+ """This file is used as a hub for imports."""
2
+
3
+ from .client import PapouchHTTPClient, PapouchTransport
4
+ from .devices import PapouchDevice, create_device, is_device_supported
5
+
6
+ __all__ = [
7
+ "PapouchDevice",
8
+ "PapouchHTTPClient",
9
+ "PapouchTransport",
10
+ "create_device",
11
+ "is_device_supported",
12
+ ]
@@ -0,0 +1,240 @@
1
+ """This file is used for communicating with the device."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ import logging
5
+ import re
6
+ from typing import Any, override
7
+
8
+ import aiohttp
9
+ import defusedxml.ElementTree as defused_ET
10
+
11
+ from homeassistant.helpers.device_registry import format_mac
12
+
13
+ from .exceptions import DeviceAuthError, DeviceConnectionError, DeviceLogicError
14
+
15
+ INFO_URL = "is.xml"
16
+ DATA_URL = "fresh.xml"
17
+ SETTINGS_URL = "settings.xml"
18
+ SET_URL = "set.xml"
19
+ SAVE_URL = "save.xml"
20
+
21
+ ENCODING = "iso-8859-2"
22
+ WEB_MODE_INDEX = 3
23
+ TIMEOUT_REQUEST = 10
24
+
25
+ _LOGGER = logging.getLogger(__name__)
26
+
27
+
28
+ class PapouchTransport(ABC):
29
+ """Abstract base class for all Papouch communication methods."""
30
+
31
+ @abstractmethod
32
+ async def fetch_info(self) -> str:
33
+ """Fetch the device identification data."""
34
+
35
+ @abstractmethod
36
+ async def fetch_settings(self) -> str:
37
+ """Fetch the device configuration."""
38
+
39
+ @abstractmethod
40
+ async def fetch_data(self) -> str:
41
+ """Fetch the latest sensor readings."""
42
+
43
+ @abstractmethod
44
+ async def read_command(
45
+ self, params: dict, context: str, endpoint: str = SET_URL
46
+ ) -> str:
47
+ """Command for communicating with any device by using GET request.
48
+
49
+ Parameters are GET queries that will be added to the request.
50
+ Context string is used for error message
51
+ and it will be populated with a device information.
52
+ """
53
+
54
+ @abstractmethod
55
+ async def write_command(
56
+ self, payload: str, context: str, endpoint: str = SAVE_URL
57
+ ) -> str:
58
+ """Send a complex payload (like XML settings).
59
+
60
+ Context string is used for error message
61
+ and it will be populated with a device information.
62
+ """
63
+
64
+ @abstractmethod
65
+ async def get_device_info(self) -> tuple[str | None, str | None]:
66
+ """Return name and location of the device."""
67
+
68
+ @abstractmethod
69
+ async def get_device_mac(self) -> str:
70
+ """Return MAC of the device."""
71
+
72
+ @property
73
+ @abstractmethod
74
+ def protocol(self) -> str:
75
+ """Return type of the protocol to communicate with a device."""
76
+
77
+
78
+ class PapouchHTTPClient(PapouchTransport):
79
+ """API client for communicating with a device."""
80
+
81
+ def __init__(
82
+ self, ip_address: str, session: aiohttp.ClientSession, password: str = ""
83
+ ) -> None:
84
+ """Constructor for API client."""
85
+ self.base_url = f"http://{ip_address}/"
86
+ self.session = session
87
+ self.ip_address = ip_address
88
+
89
+ if password != "":
90
+ self._auth = aiohttp.BasicAuth("admin", password)
91
+ else:
92
+ self._auth = aiohttp.BasicAuth("", "")
93
+
94
+ @property
95
+ @override
96
+ def protocol(self) -> str:
97
+ return "http"
98
+
99
+ async def _fetch(self, endpoint: str) -> str:
100
+ raw_xml = await self._send_request("GET", endpoint, context=endpoint)
101
+ return re.sub(r'\s+xmlns="[^"]+"', "", raw_xml)
102
+
103
+ @override
104
+ async def fetch_info(self) -> str:
105
+ """Fetching information about a device."""
106
+ return await self._fetch(INFO_URL)
107
+
108
+ @override
109
+ async def fetch_data(self) -> str:
110
+ """Fetching data about a device."""
111
+ return await self._fetch(DATA_URL)
112
+
113
+ @override
114
+ async def fetch_settings(self) -> str:
115
+ """Fetching settings about a device."""
116
+ return await self._fetch(SETTINGS_URL)
117
+
118
+ @override
119
+ async def get_device_info(self) -> tuple[str | None, str | None]:
120
+ info = await self.fetch_info()
121
+
122
+ try:
123
+ root = defused_ET.fromstring(info)
124
+ except defused_ET.ParseError:
125
+ return (None, None)
126
+
127
+ heartbeat = None
128
+ for element in root.iter():
129
+ if element.tag.endswith("heartbeat"):
130
+ heartbeat = element
131
+ break
132
+
133
+ if heartbeat is None:
134
+ return (None, None)
135
+
136
+ device_name = heartbeat.attrib.get("device")
137
+ device_location = heartbeat.attrib.get("location")
138
+
139
+ return (device_name, device_location)
140
+
141
+ @override
142
+ async def get_device_mac(self) -> str:
143
+ settings = await self.fetch_settings()
144
+ root = defused_ET.fromstring(settings)
145
+ box = root.find(".//set[@box='12']")
146
+
147
+ if box is not None:
148
+ return format_mac(str(box.attrib.get("mac", "")))
149
+
150
+ raise DeviceLogicError(
151
+ f"Device: {self.ip_address} doesn't have a box 12 with MAC address"
152
+ )
153
+
154
+ async def _send_request(
155
+ self, method: str, endpoint: str, context: str, **kwargs: Any
156
+ ) -> str:
157
+
158
+ timeout = aiohttp.ClientTimeout(total=TIMEOUT_REQUEST)
159
+
160
+ try:
161
+ async with self.session.request(
162
+ method,
163
+ self.base_url + endpoint,
164
+ timeout=timeout,
165
+ auth=self._auth,
166
+ **kwargs,
167
+ ) as response:
168
+ if response.status != 200:
169
+ if response.status == 401:
170
+ raise DeviceAuthError("Invalid password")
171
+
172
+ raise DeviceConnectionError(
173
+ f"Failed to send command: {response.status}"
174
+ )
175
+ return await response.text(encoding=ENCODING)
176
+
177
+ except (aiohttp.ClientError, TimeoutError) as exception:
178
+ raise DeviceConnectionError(
179
+ f"Failed to connect to {context} - {self.ip_address}: {exception}"
180
+ ) from exception
181
+
182
+ @override
183
+ async def read_command(
184
+ self, params: dict, context: str, endpoint: str = SET_URL
185
+ ) -> str:
186
+ """Command for communicating with any device by using GET request.
187
+
188
+ Parameters are GET queries that will be added to the request.
189
+ """
190
+
191
+ return await self._send_request("GET", endpoint, context, params=params)
192
+
193
+ @override
194
+ async def write_command(
195
+ self, payload: str, context: str, endpoint: str = SAVE_URL
196
+ ) -> str:
197
+ """Command for communicating with any device by using POST request.
198
+
199
+ Data contains the POST payload that will be sent in the request body.
200
+ Context is a information about the device:
201
+
202
+ e.g. f"{self.name} ({self.location})"
203
+
204
+ Return response text.
205
+ """
206
+
207
+ return await self._send_request("POST", endpoint, context, data=payload)
208
+
209
+ async def get_device_mode(self) -> int:
210
+ """Function is used for the resolving the mode of the device."""
211
+ info_xml = await self.fetch_info()
212
+ root = defused_ET.fromstring(info_xml)
213
+
214
+ heartbeat_tag = None
215
+ for element in root.iter():
216
+ if element.tag.endswith("heartbeat"):
217
+ heartbeat_tag = element
218
+ break
219
+
220
+ if heartbeat_tag is not None:
221
+ mode = heartbeat_tag.attrib.get("mode")
222
+ if mode is not None:
223
+ return int(mode)
224
+
225
+ device_name = heartbeat_tag.attrib.get("device")
226
+ if self._check_exceptions_device_web_mode(device_name):
227
+ return WEB_MODE_INDEX
228
+
229
+ _LOGGER.error("Heartbeat tag found, but 'mode' attribute is missing!")
230
+ return -1
231
+
232
+ _LOGGER.error("Response doesn't have heartbeat tag!")
233
+ return -1
234
+
235
+ def _check_exceptions_device_web_mode(self, device_name: str) -> bool:
236
+ if device_name == "TME":
237
+ return True
238
+ if "Papago" in device_name and "ETH" in device_name:
239
+ return True
240
+ return False
@@ -0,0 +1,46 @@
1
+ """This file is used as a hub for imports."""
2
+
3
+ from ..client import PapouchTransport
4
+ from .base import PapouchDevice
5
+ from .papago import async_setup_papago
6
+ from .quido import async_setup_quido
7
+ from .th2e import async_setup_th2e
8
+ from .tme import async_setup_tme
9
+
10
+ DEVICE_SETUP_HANDLERS = {
11
+ "Quido": async_setup_quido,
12
+ "TH2E": async_setup_th2e,
13
+ "TME": async_setup_tme,
14
+ "Papago": async_setup_papago,
15
+ }
16
+
17
+
18
+ def is_device_supported(device_name: str | None) -> bool:
19
+ """Check if the extracted device name matches any supported prefix."""
20
+ if not device_name:
21
+ return False
22
+
23
+ return any(prefix in device_name for prefix in DEVICE_SETUP_HANDLERS)
24
+
25
+
26
+ async def create_device(api_client: PapouchTransport) -> PapouchDevice | None:
27
+ """Create a proper device instance dynamically based on the fetched info.
28
+
29
+ Returns None if the device is not supported.
30
+ """
31
+
32
+ device_name, _ = await api_client.get_device_info()
33
+
34
+ if not is_device_supported(device_name):
35
+ return None
36
+
37
+ assert device_name is not None
38
+
39
+ for prefix, setup_func in DEVICE_SETUP_HANDLERS.items():
40
+ if prefix in device_name:
41
+ return await setup_func(api_client)
42
+
43
+ return None
44
+
45
+
46
+ __all__ = ["PapouchDevice", "create_device", "is_device_supported"]