inelnet-api 1.0.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: inelnet-api
3
+ Version: 1.0.0
4
+ Summary: Async client for INELNET blinds controller REST API (one object per channel).
5
+ Author: Hadatko
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Hadatko/inelnet_ha
8
+ Project-URL: Repository, https://github.com/Hadatko/inelnet_ha
9
+ Keywords: inelnet,blinds,roller,rest,async,home-assistant
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Home Automation
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: aiohttp>=3.8.0
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=7.0; extra == "dev"
24
+ Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # inelnet-api
28
+
29
+ Asynchrónny klientsky balík pre REST API ovládača INELNET rolet. Jeden objekt reprezentuje jeden kanál (host + číslo kanála).
30
+
31
+ ## Inštalácia
32
+
33
+ ```bash
34
+ pip install inelnet-api
35
+ ```
36
+
37
+ ## Použitie
38
+
39
+ Pre každý kanál vytvor jednu inštanciu `InelnetChannel` (host + číslo kanála 1–16):
40
+
41
+ ```python
42
+ import asyncio
43
+ from inelnet_api import Action, InelnetChannel
44
+
45
+ async def main():
46
+ channel = InelnetChannel(host="192.168.1.67", channel=1)
47
+
48
+ # Kontrola dostupnosti
49
+ ok = await channel.ping()
50
+ if not ok:
51
+ print("Kontrolér nedostupný")
52
+ return
53
+
54
+ # Pohyb: otvoriť / zatvoriť / stop
55
+ await channel.up()
56
+ await channel.down()
57
+ await channel.stop()
58
+
59
+ # Krátky posun a programovací režim
60
+ await channel.up_short()
61
+ await channel.down_short()
62
+ await channel.program()
63
+
64
+ # Príkaz podľa enumu (Action.UP, Action.DOWN, Action.STOP, …)
65
+ # await channel.send_command(Action.UP_SHORT, session=hass_session)
66
+
67
+ # Voliteľne: vlastná session (napr. z Home Assistant)
68
+ # await channel.up(session=hass_session)
69
+
70
+ asyncio.run(main())
71
+ ```
72
+
73
+ ## API
74
+
75
+ - **`InelnetChannel(host: str, channel: int)`** – kanál musí byť 1–16.
76
+ - **`send_command(act, *, session=None, timeout=...)`** – odoslanie príkazu; `act` je člen enumu **`Action`** (napr. `Action.UP`, `Action.DOWN`, `Action.STOP`) alebo celé číslo.
77
+ - **`ping(*, session=None, timeout=...)`** – GET na kontrolér, vráti `True` ak je dostupný.
78
+ - **`up()`, `down()`, `stop()`, `up_short()`, `down_short()`, `program()`** – pohodlné metódy (voliteľne `session=`).
79
+
80
+ Ak nepredáš `session`, knižnica pre každý volanie dočasne vytvorí vlastnú `aiohttp.ClientSession()`. V prostredí ako Home Assistant môžeš predať `async_get_clientsession(hass)` kvôli zdieľanému HTTP klientskému session.
81
+
82
+ ## Publikovanie na PyPI (pre maintainera)
83
+
84
+ ```bash
85
+ # Jednorazovo
86
+ pip install build twine
87
+
88
+ # Build
89
+ python3 -m build
90
+
91
+ # Nahratie na PyPI (vyžaduje účet a token)
92
+ twine upload dist/*
93
+ # alebo len test PyPI:
94
+ twine upload --repository testpypi dist/*
95
+ ```
96
+
97
+ Po úprave kódu zmeň `version` v `pyproject.toml` a v `inelnet_api/__init__.py`, potom znova `python3 -m build` a `twine upload dist/*`.
@@ -0,0 +1,67 @@
1
+ # inelnet_ha
2
+
3
+ Home Assistant integration for controlling INELNET blinds via REST API. You define all channels in one setup step (IP + comma-separated channel list). Each channel becomes one device with four entities: one cover (open/close/stop) and three buttons (Short move up, Short move down, Programming mode).
4
+
5
+ ## Installation
6
+
7
+ For full setup steps see **[Setup guide →](https://github.com/Hadatko/inelnet_ha#)**.
8
+
9
+ 1. Copy the `custom_components/inelnet` folder into your Home Assistant `<config>/custom_components/inelnet` (or clone the repo and symlink).
10
+ 2. Restart Home Assistant.
11
+ 3. **Settings → Devices & services → Add integration** → search for "INELNET Blinds".
12
+ 4. Enter the controller **IP address** (e.g. `192.168.1.67`) and **all channel numbers** comma-separated (e.g. `1` or `1,2,3`). Channels are 1–16. One device per channel is created.
13
+ **Channel definition** (entered when adding the integration):
14
+
15
+ ![Channel definition when adding integration](img/channelDef.jpg)
16
+
17
+ 5. Optionally assign each channel to a room in Home Assistant (**Channel → Room**):
18
+
19
+ ![Assigning channels to rooms](img/channelRoom.png)
20
+
21
+ 6. Each device has **4 entities**: the cover (open/close/stop) plus three buttons (Short move up, Short move down, Programming mode).
22
+
23
+ ## Usage
24
+
25
+ - **Cover** – open/close/stop via UI or `cover.open_cover`, `cover.close_cover`, `cover.stop_cover`.
26
+ - **Buttons** – one entity per action: Short move up, Short move down, Programming mode (for pairing a remote). Use in dashboards or automations.
27
+ - **Device Actions** – the same actions are also available when building automations/scenes as device actions.
28
+
29
+ ## Technical details
30
+
31
+ The integration uses the [inelnet-api](https://pypi.org/project/inelnet-api/) Python package to talk to the controller. The API sends POST requests to `http://<host>/msg.htm` with body `send_ch=<channel>&send_act=<code>`. Codes: 144 stop, 160 up, 176 up_short, 192 down, 208 down_short, 224 program.
32
+
33
+ ### Knižnica inelnet-api (PyPI)
34
+
35
+ API pre roleta je vydané ako samostatný balík **inelnet-api**. Zdroj je v priečinku `inelnet_api/`. Jeden kanál = jedna inštancia `InelnetChannel(host, channel)`.
36
+
37
+ **Publikovanie na PyPI:**
38
+
39
+ 1. Skopíruj `.env.pypi.example` na `.env.pypi`, doplň doň svoj PyPI token (username nechaj `__token__`). Súbor `.env.pypi` je v `.gitignore`, do gitu sa necommitne.
40
+ 2. Spusti (potrebuješ mať nainštalované `build` a `twine`):
41
+
42
+ ```bash
43
+ ./scripts/upload_pypi.sh
44
+ ```
45
+
46
+ Skript načíta údaje z `.env.pypi` a spustí `python3 -m build` a `twine upload dist/*`. Po zmene kódu uprav `version` v `pyproject.toml` a v `inelnet_api/__init__.py`, potom znova spusti `./scripts/upload_pypi.sh`.
47
+
48
+ ## Testing
49
+
50
+ Tests follow the same style as Home Assistant core integrations (pytest, `pytest-homeassistant-custom-component`).
51
+
52
+ ```bash
53
+ pip install -e . && pip install -r requirements_test.txt
54
+ pytest tests/ tests_inelnet_api/ -v
55
+ ```
56
+
57
+ Requires a compatible Home Assistant core environment (e.g. install `homeassistant` in the same venv or use the same Python as HA). The `pytest-homeassistant-custom-component` package provides the `hass` and `enable_custom_integrations` fixtures.
58
+
59
+ ---
60
+
61
+ If anybody is interested in supporting my "sleepless" nights (working mostly between 23:00-3:00) on different projects press:
62
+
63
+ [![Buy me a coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-%F0%9F%8D%BA-yellow?style=for-the-badge&logo=buy-me-a-coffee)](https://www.buymeacoffee.com/hadatko)
64
+
65
+ Thank you ;)
66
+
67
+ Ideas are welcome. But PRs are welcome more ;)
@@ -0,0 +1,71 @@
1
+ # inelnet-api
2
+
3
+ Asynchrónny klientsky balík pre REST API ovládača INELNET rolet. Jeden objekt reprezentuje jeden kanál (host + číslo kanála).
4
+
5
+ ## Inštalácia
6
+
7
+ ```bash
8
+ pip install inelnet-api
9
+ ```
10
+
11
+ ## Použitie
12
+
13
+ Pre každý kanál vytvor jednu inštanciu `InelnetChannel` (host + číslo kanála 1–16):
14
+
15
+ ```python
16
+ import asyncio
17
+ from inelnet_api import Action, InelnetChannel
18
+
19
+ async def main():
20
+ channel = InelnetChannel(host="192.168.1.67", channel=1)
21
+
22
+ # Kontrola dostupnosti
23
+ ok = await channel.ping()
24
+ if not ok:
25
+ print("Kontrolér nedostupný")
26
+ return
27
+
28
+ # Pohyb: otvoriť / zatvoriť / stop
29
+ await channel.up()
30
+ await channel.down()
31
+ await channel.stop()
32
+
33
+ # Krátky posun a programovací režim
34
+ await channel.up_short()
35
+ await channel.down_short()
36
+ await channel.program()
37
+
38
+ # Príkaz podľa enumu (Action.UP, Action.DOWN, Action.STOP, …)
39
+ # await channel.send_command(Action.UP_SHORT, session=hass_session)
40
+
41
+ # Voliteľne: vlastná session (napr. z Home Assistant)
42
+ # await channel.up(session=hass_session)
43
+
44
+ asyncio.run(main())
45
+ ```
46
+
47
+ ## API
48
+
49
+ - **`InelnetChannel(host: str, channel: int)`** – kanál musí byť 1–16.
50
+ - **`send_command(act, *, session=None, timeout=...)`** – odoslanie príkazu; `act` je člen enumu **`Action`** (napr. `Action.UP`, `Action.DOWN`, `Action.STOP`) alebo celé číslo.
51
+ - **`ping(*, session=None, timeout=...)`** – GET na kontrolér, vráti `True` ak je dostupný.
52
+ - **`up()`, `down()`, `stop()`, `up_short()`, `down_short()`, `program()`** – pohodlné metódy (voliteľne `session=`).
53
+
54
+ Ak nepredáš `session`, knižnica pre každý volanie dočasne vytvorí vlastnú `aiohttp.ClientSession()`. V prostredí ako Home Assistant môžeš predať `async_get_clientsession(hass)` kvôli zdieľanému HTTP klientskému session.
55
+
56
+ ## Publikovanie na PyPI (pre maintainera)
57
+
58
+ ```bash
59
+ # Jednorazovo
60
+ pip install build twine
61
+
62
+ # Build
63
+ python3 -m build
64
+
65
+ # Nahratie na PyPI (vyžaduje účet a token)
66
+ twine upload dist/*
67
+ # alebo len test PyPI:
68
+ twine upload --repository testpypi dist/*
69
+ ```
70
+
71
+ Po úprave kódu zmeň `version` v `pyproject.toml` a v `inelnet_api/__init__.py`, potom znova `python3 -m build` a `twine upload dist/*`.
@@ -0,0 +1,6 @@
1
+ """INELNET Blinds REST API client – one object per channel (host + channel)."""
2
+
3
+ from .client import Action, InelnetChannel
4
+
5
+ __all__ = ["Action", "InelnetChannel"]
6
+ __version__ = "1.0.0"
@@ -0,0 +1,171 @@
1
+ """INELNET channel client: one object per channel (host + channel)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from enum import IntEnum
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ import aiohttp
10
+
11
+ if TYPE_CHECKING:
12
+ from aiohttp import ClientSession
13
+
14
+ _LOGGER = logging.getLogger(__name__)
15
+
16
+
17
+ class Action(IntEnum):
18
+ """REST API action codes (send_act parameter)."""
19
+
20
+ STOP = 144
21
+ UP = 160
22
+ UP_SHORT = 176
23
+ DOWN = 192
24
+ DOWN_SHORT = 208
25
+ PROGRAM = 224
26
+
27
+ DEFAULT_TIMEOUT = aiohttp.ClientTimeout(total=10)
28
+ URL_PATH = "/msg.htm"
29
+
30
+
31
+ class InelnetChannel:
32
+ """
33
+ Client for one INELNET controller channel.
34
+ One instance per (host, channel); all methods target that channel only.
35
+ """
36
+
37
+ __slots__ = ("_host", "_channel", "_base_url")
38
+
39
+ def __init__(self, host: str, channel: int) -> None:
40
+ if not 1 <= channel <= 16:
41
+ raise ValueError("channel must be 1–16")
42
+ self._host = host.strip()
43
+ self._channel = channel
44
+ self._base_url = f"http://{self._host}{URL_PATH}"
45
+
46
+ @property
47
+ def host(self) -> str:
48
+ return self._host
49
+
50
+ @property
51
+ def channel(self) -> int:
52
+ return self._channel
53
+
54
+ def _payload(self, act: Action | int) -> str:
55
+ return f"send_ch={self._channel}&send_act={int(act)}"
56
+
57
+ async def send_command(
58
+ self,
59
+ act: Action | int,
60
+ *,
61
+ session: ClientSession | None = None,
62
+ timeout: aiohttp.ClientTimeout = DEFAULT_TIMEOUT,
63
+ ) -> bool:
64
+ """
65
+ Send one REST command to this channel.
66
+ If session is not provided, a temporary session is used for the request.
67
+ """
68
+ payload = self._payload(act)
69
+ if session is not None:
70
+ return await self._post(session, payload, timeout)
71
+ async with aiohttp.ClientSession() as own_session:
72
+ return await self._post(own_session, payload, timeout)
73
+
74
+ async def _post(
75
+ self,
76
+ session: ClientSession,
77
+ payload: str,
78
+ timeout: aiohttp.ClientTimeout,
79
+ ) -> bool:
80
+ try:
81
+ async with session.post(
82
+ self._base_url,
83
+ data=payload,
84
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
85
+ timeout=timeout,
86
+ ) as resp:
87
+ return resp.status == 200
88
+ except (aiohttp.ClientError, OSError) as e:
89
+ _LOGGER.warning("INELNET command failed %s: %s", self._base_url, e)
90
+ return False
91
+
92
+ async def ping(
93
+ self,
94
+ *,
95
+ session: ClientSession | None = None,
96
+ timeout: aiohttp.ClientTimeout = DEFAULT_TIMEOUT,
97
+ ) -> bool:
98
+ """
99
+ Check connectivity to the controller (GET to msg.htm).
100
+ If session is not provided, a temporary session is used.
101
+ """
102
+ if session is not None:
103
+ return await self._get(session, timeout)
104
+ async with aiohttp.ClientSession() as own_session:
105
+ return await self._get(own_session, timeout)
106
+
107
+ async def _get(
108
+ self,
109
+ session: ClientSession,
110
+ timeout: aiohttp.ClientTimeout,
111
+ ) -> bool:
112
+ try:
113
+ async with session.get(self._base_url, timeout=timeout) as resp:
114
+ return resp.status < 400
115
+ except (aiohttp.ClientError, OSError):
116
+ return False
117
+
118
+ # Convenience methods
119
+ async def up(
120
+ self,
121
+ *,
122
+ session: ClientSession | None = None,
123
+ **kwargs: Any,
124
+ ) -> bool:
125
+ """Roll up (open)."""
126
+ return await self.send_command(Action.UP, session=session, **kwargs)
127
+
128
+ async def down(
129
+ self,
130
+ *,
131
+ session: ClientSession | None = None,
132
+ **kwargs: Any,
133
+ ) -> bool:
134
+ """Roll down (close)."""
135
+ return await self.send_command(Action.DOWN, session=session, **kwargs)
136
+
137
+ async def stop(
138
+ self,
139
+ *,
140
+ session: ClientSession | None = None,
141
+ **kwargs: Any,
142
+ ) -> bool:
143
+ """Stop movement."""
144
+ return await self.send_command(Action.STOP, session=session, **kwargs)
145
+
146
+ async def up_short(
147
+ self,
148
+ *,
149
+ session: ClientSession | None = None,
150
+ **kwargs: Any,
151
+ ) -> bool:
152
+ """Short move up."""
153
+ return await self.send_command(Action.UP_SHORT, session=session, **kwargs)
154
+
155
+ async def down_short(
156
+ self,
157
+ *,
158
+ session: ClientSession | None = None,
159
+ **kwargs: Any,
160
+ ) -> bool:
161
+ """Short move down."""
162
+ return await self.send_command(Action.DOWN_SHORT, session=session, **kwargs)
163
+
164
+ async def program(
165
+ self,
166
+ *,
167
+ session: ClientSession | None = None,
168
+ **kwargs: Any,
169
+ ) -> bool:
170
+ """Programming mode (e.g. for pairing remote)."""
171
+ return await self.send_command(Action.PROGRAM, session=session, **kwargs)
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: inelnet-api
3
+ Version: 1.0.0
4
+ Summary: Async client for INELNET blinds controller REST API (one object per channel).
5
+ Author: Hadatko
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Hadatko/inelnet_ha
8
+ Project-URL: Repository, https://github.com/Hadatko/inelnet_ha
9
+ Keywords: inelnet,blinds,roller,rest,async,home-assistant
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Home Automation
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: aiohttp>=3.8.0
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=7.0; extra == "dev"
24
+ Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # inelnet-api
28
+
29
+ Asynchrónny klientsky balík pre REST API ovládača INELNET rolet. Jeden objekt reprezentuje jeden kanál (host + číslo kanála).
30
+
31
+ ## Inštalácia
32
+
33
+ ```bash
34
+ pip install inelnet-api
35
+ ```
36
+
37
+ ## Použitie
38
+
39
+ Pre každý kanál vytvor jednu inštanciu `InelnetChannel` (host + číslo kanála 1–16):
40
+
41
+ ```python
42
+ import asyncio
43
+ from inelnet_api import Action, InelnetChannel
44
+
45
+ async def main():
46
+ channel = InelnetChannel(host="192.168.1.67", channel=1)
47
+
48
+ # Kontrola dostupnosti
49
+ ok = await channel.ping()
50
+ if not ok:
51
+ print("Kontrolér nedostupný")
52
+ return
53
+
54
+ # Pohyb: otvoriť / zatvoriť / stop
55
+ await channel.up()
56
+ await channel.down()
57
+ await channel.stop()
58
+
59
+ # Krátky posun a programovací režim
60
+ await channel.up_short()
61
+ await channel.down_short()
62
+ await channel.program()
63
+
64
+ # Príkaz podľa enumu (Action.UP, Action.DOWN, Action.STOP, …)
65
+ # await channel.send_command(Action.UP_SHORT, session=hass_session)
66
+
67
+ # Voliteľne: vlastná session (napr. z Home Assistant)
68
+ # await channel.up(session=hass_session)
69
+
70
+ asyncio.run(main())
71
+ ```
72
+
73
+ ## API
74
+
75
+ - **`InelnetChannel(host: str, channel: int)`** – kanál musí byť 1–16.
76
+ - **`send_command(act, *, session=None, timeout=...)`** – odoslanie príkazu; `act` je člen enumu **`Action`** (napr. `Action.UP`, `Action.DOWN`, `Action.STOP`) alebo celé číslo.
77
+ - **`ping(*, session=None, timeout=...)`** – GET na kontrolér, vráti `True` ak je dostupný.
78
+ - **`up()`, `down()`, `stop()`, `up_short()`, `down_short()`, `program()`** – pohodlné metódy (voliteľne `session=`).
79
+
80
+ Ak nepredáš `session`, knižnica pre každý volanie dočasne vytvorí vlastnú `aiohttp.ClientSession()`. V prostredí ako Home Assistant môžeš predať `async_get_clientsession(hass)` kvôli zdieľanému HTTP klientskému session.
81
+
82
+ ## Publikovanie na PyPI (pre maintainera)
83
+
84
+ ```bash
85
+ # Jednorazovo
86
+ pip install build twine
87
+
88
+ # Build
89
+ python3 -m build
90
+
91
+ # Nahratie na PyPI (vyžaduje účet a token)
92
+ twine upload dist/*
93
+ # alebo len test PyPI:
94
+ twine upload --repository testpypi dist/*
95
+ ```
96
+
97
+ Po úprave kódu zmeň `version` v `pyproject.toml` a v `inelnet_api/__init__.py`, potom znova `python3 -m build` a `twine upload dist/*`.
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ ./inelnet_api/__init__.py
5
+ ./inelnet_api/client.py
6
+ inelnet_api/README.md
7
+ inelnet_api/__init__.py
8
+ inelnet_api/client.py
9
+ inelnet_api.egg-info/PKG-INFO
10
+ inelnet_api.egg-info/SOURCES.txt
11
+ inelnet_api.egg-info/dependency_links.txt
12
+ inelnet_api.egg-info/requires.txt
13
+ inelnet_api.egg-info/top_level.txt
14
+ tests/test_button.py
15
+ tests/test_config_flow.py
16
+ tests/test_cover.py
17
+ tests/test_init.py
@@ -0,0 +1,5 @@
1
+ aiohttp>=3.8.0
2
+
3
+ [dev]
4
+ pytest>=7.0
5
+ pytest-asyncio>=0.21
@@ -0,0 +1 @@
1
+ inelnet_api
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "inelnet-api"
7
+ version = "1.0.0"
8
+ description = "Async client for INELNET blinds controller REST API (one object per channel)."
9
+ readme = "inelnet_api/README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ { name = "Hadatko" }
14
+ ]
15
+ keywords = ["inelnet", "blinds", "roller", "rest", "async", "home-assistant"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Topic :: Home Automation",
25
+ ]
26
+ dependencies = [
27
+ "aiohttp>=3.8.0",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ dev = [
32
+ "pytest>=7.0",
33
+ "pytest-asyncio>=0.21",
34
+ ]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/Hadatko/inelnet_ha"
38
+ Repository = "https://github.com/Hadatko/inelnet_ha"
39
+
40
+ [tool.setuptools.packages.find]
41
+ where = ["."]
42
+ include = ["inelnet_api*"]
43
+
44
+ [tool.setuptools.package-dir]
45
+ "" = "."
46
+
47
+ [tool.pytest.ini_options]
48
+ asyncio_mode = "auto"
49
+ testpaths = ["tests_inelnet_api"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,96 @@
1
+ """Tests for INELNET Blinds button platform."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from unittest.mock import AsyncMock, MagicMock, patch
6
+
7
+ import pytest
8
+ from homeassistant.config_entries import ConfigEntry
9
+
10
+ from custom_components.inelnet.button import InelnetButtonEntity
11
+ from custom_components.inelnet.const import (
12
+ Action,
13
+ CONF_CHANNELS,
14
+ CONF_HOST,
15
+ DOMAIN,
16
+ )
17
+ from inelnet_api import InelnetChannel
18
+
19
+
20
+ @pytest.fixture
21
+ def button_config_entry() -> ConfigEntry:
22
+ """Config entry for button tests."""
23
+ return ConfigEntry(
24
+ version=1,
25
+ minor_version=0,
26
+ domain=DOMAIN,
27
+ title="INELNET test",
28
+ data={CONF_HOST: "192.168.1.67", CONF_CHANNELS: [1, 2]},
29
+ source="user",
30
+ options={},
31
+ entry_id="test-button-entry",
32
+ unique_id="192.168.1.67-1,2",
33
+ discovery_keys=set(),
34
+ subentries_data={},
35
+ )
36
+
37
+
38
+ def test_button_entity_attributes(button_config_entry: ConfigEntry) -> None:
39
+ """Test button entity has correct unique_id and device info."""
40
+ client = InelnetChannel("192.168.1.67", 2)
41
+ entity = InelnetButtonEntity(
42
+ entry=button_config_entry,
43
+ client=client,
44
+ unique_id_suffix="short_up",
45
+ action=Action.UP_SHORT,
46
+ translation_key="short_up",
47
+ )
48
+ assert entity.unique_id == "test-button-entry-ch2-short_up"
49
+ assert entity.device_info is not None
50
+ identifiers = getattr(entity.device_info, "identifiers", entity.device_info.get("identifiers"))
51
+ assert identifiers == {(DOMAIN, "test-button-entry-ch2")}
52
+ assert entity.entity_registry_enabled_default is False
53
+
54
+
55
+ async def test_button_press_sends_command(button_config_entry: ConfigEntry) -> None:
56
+ """Test async_press calls client.send_command with correct action code."""
57
+ client = InelnetChannel("192.168.1.67", 1)
58
+ client.send_command = AsyncMock(return_value=True)
59
+ entity = InelnetButtonEntity(
60
+ entry=button_config_entry,
61
+ client=client,
62
+ unique_id_suffix="program",
63
+ action=Action.PROGRAM,
64
+ translation_key="program",
65
+ )
66
+ entity.hass = MagicMock()
67
+ mock_session = MagicMock()
68
+ with patch(
69
+ "custom_components.inelnet.button.async_get_clientsession",
70
+ return_value=mock_session,
71
+ ):
72
+ await entity.async_press()
73
+ client.send_command.assert_called_once_with(Action.PROGRAM, session=mock_session)
74
+
75
+
76
+ async def test_button_short_down_sends_correct_code(
77
+ button_config_entry: ConfigEntry,
78
+ ) -> None:
79
+ """Test Short move down button sends ACT_DOWN_SHORT."""
80
+ client = InelnetChannel("10.0.0.1", 3)
81
+ client.send_command = AsyncMock(return_value=True)
82
+ entity = InelnetButtonEntity(
83
+ entry=button_config_entry,
84
+ client=client,
85
+ unique_id_suffix="short_down",
86
+ action=Action.DOWN_SHORT,
87
+ translation_key="short_down",
88
+ )
89
+ entity.hass = MagicMock()
90
+ mock_session = MagicMock()
91
+ with patch(
92
+ "custom_components.inelnet.button.async_get_clientsession",
93
+ return_value=mock_session,
94
+ ):
95
+ await entity.async_press()
96
+ client.send_command.assert_called_once_with(Action.DOWN_SHORT, session=mock_session)
@@ -0,0 +1,165 @@
1
+ """Tests for INELNET Blinds config flow."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from unittest.mock import patch
6
+
7
+ import pytest
8
+ from homeassistant import config_entries
9
+ from homeassistant.data_entry_flow import FlowResultType
10
+
11
+ from custom_components.inelnet.config_flow import is_valid_host, parse_channels
12
+ from custom_components.inelnet.const import CONF_CHANNELS, CONF_HOST, DOMAIN
13
+
14
+
15
+ class TestParseChannels:
16
+ """Tests for parse_channels helper."""
17
+
18
+ def test_single_channel(self) -> None:
19
+ """Parse a single channel."""
20
+ assert parse_channels("1") == [1]
21
+
22
+ def test_multiple_channels(self) -> None:
23
+ """Parse comma-separated channels."""
24
+ assert parse_channels("1,2,3") == [1, 2, 3]
25
+ assert parse_channels("3, 1, 2") == [1, 2, 3]
26
+
27
+ def test_sorts_channels(self) -> None:
28
+ """Channels are returned sorted."""
29
+ assert parse_channels("4,2,1,3") == [1, 2, 3, 4]
30
+
31
+ def test_empty_raises(self) -> None:
32
+ """Empty or whitespace-only raises ValueError."""
33
+ with pytest.raises(ValueError):
34
+ parse_channels("")
35
+ with pytest.raises(ValueError):
36
+ parse_channels(" ")
37
+
38
+ def test_invalid_number_raises(self) -> None:
39
+ """Non-numeric part raises ValueError."""
40
+ with pytest.raises(ValueError):
41
+ parse_channels("1,a,3")
42
+
43
+ def test_out_of_range_raises(self) -> None:
44
+ """Channel < 1 or > 16 raises ValueError."""
45
+ with pytest.raises(ValueError):
46
+ parse_channels("0")
47
+ with pytest.raises(ValueError):
48
+ parse_channels("17")
49
+
50
+ def test_duplicate_raises(self) -> None:
51
+ """Duplicate channel raises ValueError."""
52
+ with pytest.raises(ValueError):
53
+ parse_channels("1,2,1")
54
+
55
+
56
+ class TestIsValidHost:
57
+ """Tests for is_valid_host helper."""
58
+
59
+ def test_valid_ipv4(self) -> None:
60
+ """Valid IPv4 is accepted."""
61
+ assert is_valid_host("192.168.1.67") is True
62
+ assert is_valid_host("10.0.0.1") is True
63
+
64
+ def test_valid_hostname(self) -> None:
65
+ """Valid hostname is accepted."""
66
+ assert is_valid_host("inelnet.local") is True
67
+ assert is_valid_host("controller") is True
68
+
69
+ def test_empty_invalid(self) -> None:
70
+ """Empty or whitespace is invalid."""
71
+ assert is_valid_host("") is False
72
+ assert is_valid_host(" ") is False
73
+
74
+ def test_invalid_ip_octets(self) -> None:
75
+ """Invalid IPv4-like string can be rejected (implementation may allow)."""
76
+ # Current impl allows any \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}
77
+ assert is_valid_host("256.1.1.1") is True # regex allows it
78
+
79
+
80
+ @pytest.mark.usefixtures("enable_custom_integrations")
81
+ async def test_config_flow_user_step_form(hass) -> None:
82
+ """Test the user step shows the form."""
83
+ result = await hass.config_entries.flow.async_init(
84
+ DOMAIN,
85
+ context={"source": config_entries.SOURCE_USER},
86
+ )
87
+ assert result["type"] is FlowResultType.FORM
88
+ assert result["step_id"] == "user"
89
+ assert CONF_HOST in result["data_schema"].schema
90
+ assert CONF_CHANNELS in result["data_schema"].schema
91
+
92
+
93
+ @pytest.mark.usefixtures("enable_custom_integrations")
94
+ async def test_config_flow_create_entry(hass) -> None:
95
+ """Test successful config flow creates entry."""
96
+ result = await hass.config_entries.flow.async_init(
97
+ DOMAIN,
98
+ context={"source": config_entries.SOURCE_USER},
99
+ )
100
+ assert result["type"] is FlowResultType.FORM
101
+
102
+ result = await hass.config_entries.flow.async_configure(
103
+ result["flow_id"],
104
+ {CONF_HOST: "192.168.1.67", CONF_CHANNELS: "1,2"},
105
+ )
106
+ assert result["type"] is FlowResultType.CREATE_ENTRY
107
+ assert result["title"] == "INELNET 192.168.1.67 (ch 1,2)"
108
+ assert result["data"][CONF_HOST] == "192.168.1.67"
109
+ assert result["data"][CONF_CHANNELS] == [1, 2]
110
+
111
+
112
+ @pytest.mark.usefixtures("enable_custom_integrations")
113
+ async def test_config_flow_invalid_host_shows_error(hass) -> None:
114
+ """Test invalid host shows form with error."""
115
+ result = await hass.config_entries.flow.async_init(
116
+ DOMAIN,
117
+ context={"source": config_entries.SOURCE_USER},
118
+ )
119
+ result = await hass.config_entries.flow.async_configure(
120
+ result["flow_id"],
121
+ {CONF_HOST: "", CONF_CHANNELS: "1"},
122
+ )
123
+ assert result["type"] is FlowResultType.FORM
124
+ assert result["errors"]["base"] == "invalid_host"
125
+
126
+
127
+ @pytest.mark.usefixtures("enable_custom_integrations")
128
+ async def test_config_flow_invalid_channels_shows_error(hass) -> None:
129
+ """Test invalid channels shows form with error."""
130
+ result = await hass.config_entries.flow.async_init(
131
+ DOMAIN,
132
+ context={"source": config_entries.SOURCE_USER},
133
+ )
134
+ result = await hass.config_entries.flow.async_configure(
135
+ result["flow_id"],
136
+ {CONF_HOST: "192.168.1.67", CONF_CHANNELS: "a,b"},
137
+ )
138
+ assert result["type"] is FlowResultType.FORM
139
+ assert result["errors"]["base"] == "invalid_channels"
140
+
141
+
142
+ @pytest.mark.usefixtures("enable_custom_integrations")
143
+ async def test_config_flow_duplicate_aborts(hass) -> None:
144
+ """Test duplicate host+channels aborts."""
145
+ result = await hass.config_entries.flow.async_init(
146
+ DOMAIN,
147
+ context={"source": config_entries.SOURCE_USER},
148
+ )
149
+ result = await hass.config_entries.flow.async_configure(
150
+ result["flow_id"],
151
+ {CONF_HOST: "192.168.1.67", CONF_CHANNELS: "1"},
152
+ )
153
+ assert result["type"] is FlowResultType.CREATE_ENTRY
154
+
155
+ # Same host + channels again should abort
156
+ result2 = await hass.config_entries.flow.async_init(
157
+ DOMAIN,
158
+ context={"source": config_entries.SOURCE_USER},
159
+ )
160
+ result2 = await hass.config_entries.flow.async_configure(
161
+ result2["flow_id"],
162
+ {CONF_HOST: "192.168.1.67", CONF_CHANNELS: "1"},
163
+ )
164
+ assert result2["type"] is FlowResultType.ABORT
165
+ assert result2["reason"] == "already_configured"
@@ -0,0 +1,99 @@
1
+ """Tests for INELNET Blinds cover platform."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from unittest.mock import AsyncMock, MagicMock, patch
6
+
7
+ import pytest
8
+ from homeassistant.config_entries import ConfigEntry
9
+ from homeassistant.core import HomeAssistant
10
+
11
+ from custom_components.inelnet.const import (
12
+ CONF_CHANNELS,
13
+ CONF_HOST,
14
+ DOMAIN,
15
+ )
16
+ from custom_components.inelnet.cover import InelnetCoverEntity
17
+ from inelnet_api import InelnetChannel
18
+
19
+
20
+ @pytest.fixture
21
+ def cover_config_entry() -> ConfigEntry:
22
+ """Config entry for cover tests."""
23
+ return ConfigEntry(
24
+ version=1,
25
+ minor_version=0,
26
+ domain=DOMAIN,
27
+ title="INELNET test",
28
+ data={CONF_HOST: "192.168.1.67", CONF_CHANNELS: [1, 2]},
29
+ source="user",
30
+ options={},
31
+ entry_id="test-cover-entry",
32
+ unique_id="192.168.1.67-1,2",
33
+ discovery_keys=set(),
34
+ subentries_data={},
35
+ )
36
+
37
+
38
+ def test_cover_entity_attributes(cover_config_entry: ConfigEntry) -> None:
39
+ """Test cover entity has correct attributes and device info."""
40
+ client = InelnetChannel("192.168.1.67", 1)
41
+ entity = InelnetCoverEntity(cover_config_entry, client)
42
+ assert entity.unique_id == "test-cover-entry-ch1"
43
+ assert entity.device_info is not None
44
+ identifiers = getattr(entity.device_info, "identifiers", entity.device_info.get("identifiers"))
45
+ assert identifiers == {(DOMAIN, "test-cover-entry-ch1")}
46
+ name = getattr(entity.device_info, "name", entity.device_info.get("name"))
47
+ assert name == "INELNET Blinds channel 1"
48
+ assert entity.is_closed is None
49
+
50
+
51
+ async def test_cover_open_sends_up_command(
52
+ cover_config_entry: ConfigEntry,
53
+ ) -> None:
54
+ """Test async_open_cover calls client.up with session."""
55
+ client = InelnetChannel("192.168.1.67", 1)
56
+ client.up = AsyncMock(return_value=True)
57
+ entity = InelnetCoverEntity(cover_config_entry, client)
58
+ entity.hass = MagicMock()
59
+ mock_session = MagicMock()
60
+ with patch(
61
+ "custom_components.inelnet.cover.async_get_clientsession",
62
+ return_value=mock_session,
63
+ ):
64
+ await entity.async_open_cover()
65
+ client.up.assert_called_once_with(session=mock_session)
66
+
67
+
68
+ async def test_cover_close_sends_down_command(
69
+ cover_config_entry: ConfigEntry,
70
+ ) -> None:
71
+ """Test async_close_cover calls client.down with session."""
72
+ client = InelnetChannel("192.168.1.67", 1)
73
+ client.down = AsyncMock(return_value=True)
74
+ entity = InelnetCoverEntity(cover_config_entry, client)
75
+ entity.hass = MagicMock()
76
+ mock_session = MagicMock()
77
+ with patch(
78
+ "custom_components.inelnet.cover.async_get_clientsession",
79
+ return_value=mock_session,
80
+ ):
81
+ await entity.async_close_cover()
82
+ client.down.assert_called_once_with(session=mock_session)
83
+
84
+
85
+ async def test_cover_stop_sends_stop_command(
86
+ cover_config_entry: ConfigEntry,
87
+ ) -> None:
88
+ """Test async_stop_cover calls client.stop with session."""
89
+ client = InelnetChannel("192.168.1.67", 1)
90
+ client.stop = AsyncMock(return_value=True)
91
+ entity = InelnetCoverEntity(cover_config_entry, client)
92
+ entity.hass = MagicMock()
93
+ mock_session = MagicMock()
94
+ with patch(
95
+ "custom_components.inelnet.cover.async_get_clientsession",
96
+ return_value=mock_session,
97
+ ):
98
+ await entity.async_stop_cover()
99
+ client.stop.assert_called_once_with(session=mock_session)
@@ -0,0 +1,66 @@
1
+ """Tests for INELNET Blinds integration setup and unload."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from unittest.mock import AsyncMock, patch
6
+
7
+ import pytest
8
+ from homeassistant.config_entries import ConfigEntry
9
+ from homeassistant.core import HomeAssistant
10
+
11
+ from custom_components.inelnet import async_setup_entry, async_unload_entry
12
+ from custom_components.inelnet.const import CONF_CHANNELS, CONF_HOST, DOMAIN
13
+
14
+
15
+ @pytest.fixture
16
+ def mock_config_entry() -> ConfigEntry:
17
+ """Create a mock config entry."""
18
+ return ConfigEntry(
19
+ version=1,
20
+ minor_version=0,
21
+ domain=DOMAIN,
22
+ title="INELNET 192.168.1.67 (ch 1,2)",
23
+ data={CONF_HOST: "192.168.1.67", CONF_CHANNELS: [1, 2]},
24
+ source="user",
25
+ options={},
26
+ entry_id="test-entry-id",
27
+ unique_id="192.168.1.67-1,2",
28
+ discovery_keys=set(),
29
+ subentries_data={},
30
+ )
31
+
32
+
33
+ @pytest.mark.usefixtures("enable_custom_integrations")
34
+ async def test_setup_entry_stores_config(
35
+ hass: HomeAssistant, mock_config_entry: ConfigEntry
36
+ ) -> None:
37
+ """Test async_setup_entry stores host and channels in hass.data."""
38
+ with patch(
39
+ "homeassistant.config_entries.ConfigEntries.async_forward_entry_setups",
40
+ new_callable=AsyncMock,
41
+ ):
42
+ result = await async_setup_entry(hass, mock_config_entry)
43
+ assert result is True
44
+ assert DOMAIN in hass.data
45
+ assert mock_config_entry.entry_id in hass.data[DOMAIN]
46
+ assert hass.data[DOMAIN][mock_config_entry.entry_id][CONF_HOST] == "192.168.1.67"
47
+ assert hass.data[DOMAIN][mock_config_entry.entry_id][CONF_CHANNELS] == [1, 2]
48
+
49
+
50
+ @pytest.mark.usefixtures("enable_custom_integrations")
51
+ async def test_unload_entry_removes_config(
52
+ hass: HomeAssistant, mock_config_entry: ConfigEntry
53
+ ) -> None:
54
+ """Test async_unload_entry removes data and returns True."""
55
+ hass.data.setdefault(DOMAIN, {})[mock_config_entry.entry_id] = {
56
+ CONF_HOST: "192.168.1.67",
57
+ CONF_CHANNELS: [1, 2],
58
+ }
59
+ with patch(
60
+ "homeassistant.config_entries.ConfigEntries.async_unload_platforms",
61
+ new_callable=AsyncMock,
62
+ return_value=True,
63
+ ):
64
+ result = await async_unload_entry(hass, mock_config_entry)
65
+ assert result is True
66
+ assert mock_config_entry.entry_id not in hass.data.get(DOMAIN, {})