pydeako-community 0.6.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.
- pydeako_community-0.6.1/LICENSE.txt +18 -0
- pydeako_community-0.6.1/PKG-INFO +112 -0
- pydeako_community-0.6.1/README.md +84 -0
- pydeako_community-0.6.1/pydeako/__init__.py +28 -0
- pydeako_community-0.6.1/pydeako/deako/__init__.py +8 -0
- pydeako_community-0.6.1/pydeako/deako/_deako.py +210 -0
- pydeako_community-0.6.1/pydeako/deako/_manager.py +192 -0
- pydeako_community-0.6.1/pydeako/deako/_request.py +34 -0
- pydeako_community-0.6.1/pydeako/deako/test_deako.py +468 -0
- pydeako_community-0.6.1/pydeako/deako/test_manager.py +327 -0
- pydeako_community-0.6.1/pydeako/deako/utils/__init__.py +3 -0
- pydeako_community-0.6.1/pydeako/deako/utils/_connection.py +176 -0
- pydeako_community-0.6.1/pydeako/deako/utils/_socket.py +56 -0
- pydeako_community-0.6.1/pydeako/deako/utils/test_connection.py +398 -0
- pydeako_community-0.6.1/pydeako/deako/utils/test_socket.py +130 -0
- pydeako_community-0.6.1/pydeako/discover/__init__.py +7 -0
- pydeako_community-0.6.1/pydeako/discover/_address_pool.py +40 -0
- pydeako_community-0.6.1/pydeako/discover/_discover.py +128 -0
- pydeako_community-0.6.1/pydeako/discover/test_address_pool.py +88 -0
- pydeako_community-0.6.1/pydeako/discover/test_discover.py +217 -0
- pydeako_community-0.6.1/pydeako/models/__init__.py +19 -0
- pydeako_community-0.6.1/pydeako/models/_const.py +25 -0
- pydeako_community-0.6.1/pydeako/models/_request.py +55 -0
- pydeako_community-0.6.1/pydeako/models/test_request.py +128 -0
- pydeako_community-0.6.1/pydeako/py.typed +0 -0
- pydeako_community-0.6.1/pydeako_community.egg-info/PKG-INFO +112 -0
- pydeako_community-0.6.1/pydeako_community.egg-info/SOURCES.txt +30 -0
- pydeako_community-0.6.1/pydeako_community.egg-info/dependency_links.txt +1 -0
- pydeako_community-0.6.1/pydeako_community.egg-info/requires.txt +1 -0
- pydeako_community-0.6.1/pydeako_community.egg-info/top_level.txt +1 -0
- pydeako_community-0.6.1/pyproject.toml +46 -0
- pydeako_community-0.6.1/setup.cfg +4 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
Copyright (c) 2023 Deako Lighting
|
|
3
|
+
Copyright (c) 2026 pydeako-community contributors
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
in the Software without restriction, including without limitation the rights
|
|
7
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
furnished to do so, subject to the following conditions:
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
copies or substantial portions of the Software.
|
|
12
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
13
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
14
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
15
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
16
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
17
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
18
|
+
SOFTWARE.
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pydeako-community
|
|
3
|
+
Version: 0.6.1
|
|
4
|
+
Summary: Connect and interact with deako devices over the network locally
|
|
5
|
+
Author: pydeako-community contributors
|
|
6
|
+
Author-email: Deako <software@deako.com>
|
|
7
|
+
Maintainer: iulianmac
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
Project-URL: Homepage, https://github.com/pydeako-community/pydeako
|
|
10
|
+
Project-URL: Source, https://github.com/pydeako-community/pydeako
|
|
11
|
+
Project-URL: Bug Tracker, https://github.com/pydeako-community/pydeako/issues
|
|
12
|
+
Project-URL: Changelog, https://github.com/pydeako-community/pydeako/releases
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Topic :: Home Automation
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE.txt
|
|
26
|
+
Requires-Dist: zeroconf
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# pydeako
|
|
30
|
+
|
|
31
|
+
## Description
|
|
32
|
+
|
|
33
|
+
`pydeako` is a Python library for discovering, connecting to, and interacting with Deako smart devices on the local network.
|
|
34
|
+
|
|
35
|
+
This is the community-maintained continuation of [DeakoLights/pydeako](https://github.com/DeakoLights/pydeako), published on PyPI as `pydeako-community`. The import name is still `pydeako`.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
`pip install pydeako-community`
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
### `pydeako` mdns discovery client
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
import asyncio
|
|
47
|
+
from pydeako import discover
|
|
48
|
+
|
|
49
|
+
async def _discover():
|
|
50
|
+
d = discover.DeakoDiscoverer()
|
|
51
|
+
try:
|
|
52
|
+
address = await d.get_address()
|
|
53
|
+
print(f"Found deako device at {address}!")
|
|
54
|
+
except discover.DevicesNotFoundException:
|
|
55
|
+
print("No devices found!")
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
if __name__ == "__main__":
|
|
59
|
+
asyncio.run(_discover())
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### `pydeako` socket client
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
import asyncio
|
|
66
|
+
from pydeako import deako, discover
|
|
67
|
+
|
|
68
|
+
async def _discover():
|
|
69
|
+
client_name = "MyClient"
|
|
70
|
+
d = discover.DeakoDiscoverer()
|
|
71
|
+
deako_client = deako.Deako(d.get_address, client_name=client_name)
|
|
72
|
+
|
|
73
|
+
await deako_client.connect()
|
|
74
|
+
await deako_client.find_devices()
|
|
75
|
+
|
|
76
|
+
devices = deako_client.get_devices()
|
|
77
|
+
|
|
78
|
+
# turn on all devices
|
|
79
|
+
for uuid in devices:
|
|
80
|
+
await deako_client.control_device(uuid, True)
|
|
81
|
+
|
|
82
|
+
if __name__ == "__main__":
|
|
83
|
+
asyncio.run(_discover())
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Contributing
|
|
87
|
+
|
|
88
|
+
### Dev environment setup
|
|
89
|
+
|
|
90
|
+
1. Use Python 3.11–3.14
|
|
91
|
+
2. `python -m venv venv`
|
|
92
|
+
3. `source venv/bin/activate`
|
|
93
|
+
4. `pip install -r requirements.txt`
|
|
94
|
+
5. `pip install -r requirements_test.txt`
|
|
95
|
+
|
|
96
|
+
### Checks
|
|
97
|
+
|
|
98
|
+
1. `pylint pydeako`
|
|
99
|
+
2. `pycodestyle pydeako`
|
|
100
|
+
3. `pytest pydeako`
|
|
101
|
+
|
|
102
|
+
## License
|
|
103
|
+
|
|
104
|
+
MIT License, see LICENSE.txt
|
|
105
|
+
|
|
106
|
+
## Project status
|
|
107
|
+
|
|
108
|
+
Deako published and maintained `pydeako` until release 0.6.0 (December 2024). The repository has had no activity since then. Its only contributor [no longer maintains anything related to Deako](https://github.com/DeakoLights/pydeako/pull/5#issuecomment-6393009318) and [suggested continuing it as a fork](https://github.com/DeakoLights/pydeako/pull/5#issuecomment-6402937827). Deako didn't answer a request to software@deako.com about maintainership.
|
|
109
|
+
|
|
110
|
+
This fork keeps the full history of the original project. Release 0.6.1 contains the same library code as `pydeako` 0.6.0, repackaged and published from GitHub Actions. Fixes land in later releases.
|
|
111
|
+
|
|
112
|
+
Bugs in the Home Assistant Deako integration go to [Home Assistant Core](https://github.com/home-assistant/core/issues); bugs in this library go [here](https://github.com/pydeako-community/pydeako/issues).
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# pydeako
|
|
2
|
+
|
|
3
|
+
## Description
|
|
4
|
+
|
|
5
|
+
`pydeako` is a Python library for discovering, connecting to, and interacting with Deako smart devices on the local network.
|
|
6
|
+
|
|
7
|
+
This is the community-maintained continuation of [DeakoLights/pydeako](https://github.com/DeakoLights/pydeako), published on PyPI as `pydeako-community`. The import name is still `pydeako`.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
`pip install pydeako-community`
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
### `pydeako` mdns discovery client
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
import asyncio
|
|
19
|
+
from pydeako import discover
|
|
20
|
+
|
|
21
|
+
async def _discover():
|
|
22
|
+
d = discover.DeakoDiscoverer()
|
|
23
|
+
try:
|
|
24
|
+
address = await d.get_address()
|
|
25
|
+
print(f"Found deako device at {address}!")
|
|
26
|
+
except discover.DevicesNotFoundException:
|
|
27
|
+
print("No devices found!")
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
if __name__ == "__main__":
|
|
31
|
+
asyncio.run(_discover())
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### `pydeako` socket client
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
import asyncio
|
|
38
|
+
from pydeako import deako, discover
|
|
39
|
+
|
|
40
|
+
async def _discover():
|
|
41
|
+
client_name = "MyClient"
|
|
42
|
+
d = discover.DeakoDiscoverer()
|
|
43
|
+
deako_client = deako.Deako(d.get_address, client_name=client_name)
|
|
44
|
+
|
|
45
|
+
await deako_client.connect()
|
|
46
|
+
await deako_client.find_devices()
|
|
47
|
+
|
|
48
|
+
devices = deako_client.get_devices()
|
|
49
|
+
|
|
50
|
+
# turn on all devices
|
|
51
|
+
for uuid in devices:
|
|
52
|
+
await deako_client.control_device(uuid, True)
|
|
53
|
+
|
|
54
|
+
if __name__ == "__main__":
|
|
55
|
+
asyncio.run(_discover())
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Contributing
|
|
59
|
+
|
|
60
|
+
### Dev environment setup
|
|
61
|
+
|
|
62
|
+
1. Use Python 3.11–3.14
|
|
63
|
+
2. `python -m venv venv`
|
|
64
|
+
3. `source venv/bin/activate`
|
|
65
|
+
4. `pip install -r requirements.txt`
|
|
66
|
+
5. `pip install -r requirements_test.txt`
|
|
67
|
+
|
|
68
|
+
### Checks
|
|
69
|
+
|
|
70
|
+
1. `pylint pydeako`
|
|
71
|
+
2. `pycodestyle pydeako`
|
|
72
|
+
3. `pytest pydeako`
|
|
73
|
+
|
|
74
|
+
## License
|
|
75
|
+
|
|
76
|
+
MIT License, see LICENSE.txt
|
|
77
|
+
|
|
78
|
+
## Project status
|
|
79
|
+
|
|
80
|
+
Deako published and maintained `pydeako` until release 0.6.0 (December 2024). The repository has had no activity since then. Its only contributor [no longer maintains anything related to Deako](https://github.com/DeakoLights/pydeako/pull/5#issuecomment-6393009318) and [suggested continuing it as a fork](https://github.com/DeakoLights/pydeako/pull/5#issuecomment-6402937827). Deako didn't answer a request to software@deako.com about maintainership.
|
|
81
|
+
|
|
82
|
+
This fork keeps the full history of the original project. Release 0.6.1 contains the same library code as `pydeako` 0.6.0, repackaged and published from GitHub Actions. Fixes land in later releases.
|
|
83
|
+
|
|
84
|
+
Bugs in the Home Assistant Deako integration go to [Home Assistant Core](https://github.com/home-assistant/core/issues); bugs in this library go [here](https://github.com/pydeako-community/pydeako/issues).
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pydeako module provides the following:
|
|
3
|
+
- models to interact with Deako devices locally with a socket connection
|
|
4
|
+
- implementation of a Deako socket client
|
|
5
|
+
- mdns discovery client
|
|
6
|
+
"""
|
|
7
|
+
# pylint: disable=duplicate-code
|
|
8
|
+
from .discover import DeakoDiscoverer, DevicesNotFoundException
|
|
9
|
+
from .deako import Deako, FindDevicesError
|
|
10
|
+
from .models import (
|
|
11
|
+
RequestType,
|
|
12
|
+
ResponseType,
|
|
13
|
+
device_list_request,
|
|
14
|
+
device_ping_request,
|
|
15
|
+
state_change_request,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
'DeakoDiscoverer',
|
|
20
|
+
'DevicesNotFoundException',
|
|
21
|
+
'Deako',
|
|
22
|
+
'FindDevicesError',
|
|
23
|
+
'RequestType',
|
|
24
|
+
'ResponseType',
|
|
25
|
+
'device_list_request',
|
|
26
|
+
'device_ping_request',
|
|
27
|
+
'state_change_request',
|
|
28
|
+
]
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Connection over socket."""
|
|
2
|
+
import asyncio
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from ..models import ResponseType
|
|
8
|
+
from ._manager import _Manager
|
|
9
|
+
|
|
10
|
+
_LOGGER: logging.Logger = logging.getLogger(__package__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FindDevicesError(Exception):
|
|
14
|
+
"""Unable to find devices."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, reason: str = "unknown") -> None:
|
|
17
|
+
"""Initialize with optional reason string."""
|
|
18
|
+
self.reason = reason
|
|
19
|
+
super().__init__()
|
|
20
|
+
|
|
21
|
+
def __str__(self):
|
|
22
|
+
return f"Failed to find devices: {self.reason}"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# 2s per device to be received to be conservative
|
|
26
|
+
DEVICE_FOUND_TIME_FACTOR_S = 2
|
|
27
|
+
DEFAULT_DEVICE_LIST_TIMEOUT_S = 10
|
|
28
|
+
DEVICE_LIST_POLLING_INTERVAL_S = 1
|
|
29
|
+
DEVICE_FOUND_POLLING_INTERVAL_S = 1
|
|
30
|
+
|
|
31
|
+
CAPABILITY_DIMMABLE = "dim"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Deako:
|
|
35
|
+
"""Deako specific socket api."""
|
|
36
|
+
|
|
37
|
+
connection_manager: _Manager
|
|
38
|
+
devices: dict[str, Any]
|
|
39
|
+
expected_devices: int
|
|
40
|
+
|
|
41
|
+
def __init__(self, get_address, client_name: str | None = None) -> None:
|
|
42
|
+
"""Init manager for Deako local integration."""
|
|
43
|
+
self.connection_manager = _Manager(
|
|
44
|
+
get_address,
|
|
45
|
+
self.incoming_json,
|
|
46
|
+
client_name=client_name,
|
|
47
|
+
)
|
|
48
|
+
self.devices: dict[str, Any] = {}
|
|
49
|
+
self.expected_devices = 0
|
|
50
|
+
|
|
51
|
+
def update_state(
|
|
52
|
+
self, uuid: str, power: bool, dim: int | None = None,
|
|
53
|
+
) -> None:
|
|
54
|
+
"""Update an in memory device's state."""
|
|
55
|
+
if uuid not in self.devices:
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
self.devices[uuid]["state"]["power"] = power
|
|
59
|
+
# dimmables don't always send dim
|
|
60
|
+
self.devices[uuid]["state"]["dim"] = (
|
|
61
|
+
dim or self.devices[uuid]["state"]["dim"]
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
if "callback" in self.devices[uuid]:
|
|
65
|
+
self.devices[uuid]["callback"]()
|
|
66
|
+
|
|
67
|
+
def set_state_callback(self, uuid: str, callback) -> None:
|
|
68
|
+
"""Add a state update listener."""
|
|
69
|
+
if uuid in self.devices:
|
|
70
|
+
self.devices[uuid]["callback"] = callback
|
|
71
|
+
|
|
72
|
+
def incoming_json(self, in_data: dict) -> None:
|
|
73
|
+
"""Parse incoming socket data which is json."""
|
|
74
|
+
try:
|
|
75
|
+
if in_data["type"] == ResponseType.DEVICE_LIST:
|
|
76
|
+
subdata = in_data["data"]
|
|
77
|
+
self.expected_devices = subdata["number_of_devices"]
|
|
78
|
+
elif in_data["type"] == ResponseType.DEVICE_FOUND:
|
|
79
|
+
subdata = in_data["data"]
|
|
80
|
+
state = subdata["state"]
|
|
81
|
+
if subdata.get("capabilities") is not None:
|
|
82
|
+
dimmable = CAPABILITY_DIMMABLE in subdata["capabilities"]
|
|
83
|
+
else:
|
|
84
|
+
# support older local api versions
|
|
85
|
+
dimmable = state.get("dim") is not None
|
|
86
|
+
self.record_device(
|
|
87
|
+
subdata["name"],
|
|
88
|
+
subdata["uuid"],
|
|
89
|
+
dimmable,
|
|
90
|
+
state["power"],
|
|
91
|
+
state.get("dim"),
|
|
92
|
+
)
|
|
93
|
+
elif in_data["type"] == ResponseType.EVENT:
|
|
94
|
+
subdata = in_data["data"]
|
|
95
|
+
state = subdata["state"]
|
|
96
|
+
self.update_state(
|
|
97
|
+
subdata["target"], state["power"], state.get("dim"),
|
|
98
|
+
)
|
|
99
|
+
except Exception as exc: # pylint: disable=broad-exception-caught
|
|
100
|
+
_LOGGER.error("Failed to parse %s: %s", in_data, exc)
|
|
101
|
+
|
|
102
|
+
# pylint: disable-next=too-many-arguments
|
|
103
|
+
def record_device(
|
|
104
|
+
self, name: str, uuid: str, dimmable: bool,
|
|
105
|
+
power: bool, dim: int | None = None,
|
|
106
|
+
) -> None:
|
|
107
|
+
"""Store a device in local memory."""
|
|
108
|
+
if uuid not in self.devices:
|
|
109
|
+
self.devices[uuid] = {"state": {}}
|
|
110
|
+
|
|
111
|
+
self.devices[uuid]["name"] = name
|
|
112
|
+
self.devices[uuid]["uuid"] = uuid
|
|
113
|
+
self.devices[uuid]["dimmable"] = dimmable
|
|
114
|
+
self.devices[uuid]["state"]["power"] = power
|
|
115
|
+
self.devices[uuid]["state"]["dim"] = dim
|
|
116
|
+
|
|
117
|
+
async def connect(self) -> None:
|
|
118
|
+
"""Initiate the connection sequence."""
|
|
119
|
+
await self.connection_manager.init_connection()
|
|
120
|
+
|
|
121
|
+
async def disconnect(self) -> None:
|
|
122
|
+
"""Close the connection."""
|
|
123
|
+
self.connection_manager.close()
|
|
124
|
+
|
|
125
|
+
def get_devices(self) -> dict:
|
|
126
|
+
"""Get the devices that have been recorded."""
|
|
127
|
+
return self.devices
|
|
128
|
+
|
|
129
|
+
async def find_devices(
|
|
130
|
+
self,
|
|
131
|
+
timeout=DEFAULT_DEVICE_LIST_TIMEOUT_S,
|
|
132
|
+
) -> None:
|
|
133
|
+
"""Request the device list."""
|
|
134
|
+
_LOGGER.info("Finding devices")
|
|
135
|
+
success = await self.connection_manager.send_get_device_list()
|
|
136
|
+
if not success:
|
|
137
|
+
raise FindDevicesError("Failed to send device list request")
|
|
138
|
+
remaining = timeout
|
|
139
|
+
# wait for device list
|
|
140
|
+
while self.expected_devices == 0 and remaining > 0:
|
|
141
|
+
_LOGGER.debug(
|
|
142
|
+
"waiting for device list... time remaining: %is", remaining,
|
|
143
|
+
)
|
|
144
|
+
await asyncio.sleep(DEVICE_LIST_POLLING_INTERVAL_S)
|
|
145
|
+
remaining -= DEVICE_LIST_POLLING_INTERVAL_S
|
|
146
|
+
|
|
147
|
+
# if we get a response, expected_devices will be at least 1
|
|
148
|
+
if self.expected_devices == 0:
|
|
149
|
+
raise FindDevicesError(
|
|
150
|
+
"Timed out waiting for device list response",
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
remaining = self.expected_devices * DEVICE_FOUND_TIME_FACTOR_S
|
|
154
|
+
while len(self.devices) != self.expected_devices and remaining > 0:
|
|
155
|
+
_LOGGER.debug(
|
|
156
|
+
"waiting for devices... expected: %i, received: "
|
|
157
|
+
+ "%i, time remaining: %is",
|
|
158
|
+
self.expected_devices,
|
|
159
|
+
len(self.devices),
|
|
160
|
+
remaining,
|
|
161
|
+
)
|
|
162
|
+
await asyncio.sleep(DEVICE_FOUND_POLLING_INTERVAL_S)
|
|
163
|
+
remaining -= DEVICE_FOUND_POLLING_INTERVAL_S
|
|
164
|
+
_LOGGER.debug("found %i devices", len(self.devices))
|
|
165
|
+
|
|
166
|
+
if len(self.devices) != self.expected_devices and remaining == 0:
|
|
167
|
+
raise FindDevicesError(
|
|
168
|
+
f"Timed out waiting for devices to be found. Expected "
|
|
169
|
+
f"{self.expected_devices} devices but only found "
|
|
170
|
+
f"{len(self.devices)}",
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
async def control_device(
|
|
174
|
+
self, uuid: str, power: bool, dim: int | None = None
|
|
175
|
+
) -> None:
|
|
176
|
+
"""Add control request to queue."""
|
|
177
|
+
|
|
178
|
+
def completed_callback():
|
|
179
|
+
self.update_state(uuid, power, dim)
|
|
180
|
+
|
|
181
|
+
await self.connection_manager.send_state_change(
|
|
182
|
+
uuid, power, dim, completed_callback=completed_callback
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
def get_name(self, uuid: str) -> str | None:
|
|
186
|
+
"""Get a device's name by uuid."""
|
|
187
|
+
device_data = self.devices.get(uuid)
|
|
188
|
+
if device_data is None:
|
|
189
|
+
return None
|
|
190
|
+
|
|
191
|
+
# name should exist if we have data on this device
|
|
192
|
+
return device_data["name"]
|
|
193
|
+
|
|
194
|
+
def get_state(self, uuid: str) -> dict | None:
|
|
195
|
+
"""Get a device's state by uuid."""
|
|
196
|
+
device_data = self.devices.get(uuid)
|
|
197
|
+
if device_data is None:
|
|
198
|
+
return None
|
|
199
|
+
|
|
200
|
+
# state should exist if we have data on this device
|
|
201
|
+
return device_data["state"]
|
|
202
|
+
|
|
203
|
+
def is_dimmable(self, uuid: str) -> bool | None:
|
|
204
|
+
"""Get whether a device is dimmable by uuid."""
|
|
205
|
+
device_data = self.devices.get(uuid)
|
|
206
|
+
if device_data is None:
|
|
207
|
+
return None
|
|
208
|
+
|
|
209
|
+
# dimmable should exist if we have data on this device
|
|
210
|
+
return device_data["dimmable"]
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Manager to SocketConnection, ensuring that there's always an
|
|
3
|
+
active connection. Uses two workers, one to check connectivity
|
|
4
|
+
through pinging, and one to check for messages to send.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import logging
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Callable
|
|
11
|
+
|
|
12
|
+
from ..discover import DevicesNotFoundException
|
|
13
|
+
from ..models import (
|
|
14
|
+
device_list_request,
|
|
15
|
+
device_ping_request,
|
|
16
|
+
state_change_request,
|
|
17
|
+
ResponseType,
|
|
18
|
+
)
|
|
19
|
+
from .utils import _Connection
|
|
20
|
+
from ._request import _Request
|
|
21
|
+
|
|
22
|
+
_LOGGER: logging.Logger = logging.getLogger(__package__)
|
|
23
|
+
|
|
24
|
+
CONNECTED_POLLING_INTERVAL_S = 1
|
|
25
|
+
CONNECTION_TIMEOUT_S = 10
|
|
26
|
+
WORKER_WAIT_S = 0.5
|
|
27
|
+
PING_WORKER_WAIT_S = 10
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class _ManagerState:
|
|
32
|
+
"""State for _Manager, used by workers."""
|
|
33
|
+
|
|
34
|
+
connecting: bool = False
|
|
35
|
+
canceled: bool = False
|
|
36
|
+
logged_send_error = False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# pylint: disable-next=too-many-instance-attributes
|
|
40
|
+
class _Manager:
|
|
41
|
+
"""Manage the socket connection to Deako local integrations."""
|
|
42
|
+
|
|
43
|
+
maintain_worker: asyncio.Task | None = None
|
|
44
|
+
worker: asyncio.Task | None = None
|
|
45
|
+
connection: _Connection | None = None
|
|
46
|
+
tasks: set[asyncio.Task]
|
|
47
|
+
client_name: str | None
|
|
48
|
+
state: _ManagerState
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
get_address,
|
|
53
|
+
incoming_json_callback,
|
|
54
|
+
client_name: str | None = None,
|
|
55
|
+
) -> None:
|
|
56
|
+
"""Initialize with get address function and incoming json callback."""
|
|
57
|
+
self.get_address = get_address
|
|
58
|
+
self.incoming_json_callback = incoming_json_callback
|
|
59
|
+
self.pong_received = False
|
|
60
|
+
self.tasks = set()
|
|
61
|
+
self.client_name = client_name
|
|
62
|
+
self.state = _ManagerState()
|
|
63
|
+
|
|
64
|
+
async def init_connection(self) -> None:
|
|
65
|
+
"""Initialize the connection process."""
|
|
66
|
+
if self.state.connecting:
|
|
67
|
+
_LOGGER.error("Already attempting to connect")
|
|
68
|
+
return
|
|
69
|
+
self.state.connecting = True
|
|
70
|
+
try:
|
|
71
|
+
address, name = await self.get_address()
|
|
72
|
+
except DevicesNotFoundException:
|
|
73
|
+
_LOGGER.warning("No devices to connect to")
|
|
74
|
+
self.create_connection_task()
|
|
75
|
+
self.state.connecting = False
|
|
76
|
+
return
|
|
77
|
+
connection = _Connection(address, name, self.incoming_json)
|
|
78
|
+
timeout = 0
|
|
79
|
+
while not connection.is_connected() and timeout < CONNECTION_TIMEOUT_S:
|
|
80
|
+
await asyncio.sleep(CONNECTED_POLLING_INTERVAL_S)
|
|
81
|
+
timeout += CONNECTED_POLLING_INTERVAL_S
|
|
82
|
+
if timeout == CONNECTION_TIMEOUT_S:
|
|
83
|
+
_LOGGER.error("Timeout attempting to connect. Trying again")
|
|
84
|
+
self.state.connecting = False
|
|
85
|
+
connection.close()
|
|
86
|
+
self.create_connection_task()
|
|
87
|
+
return
|
|
88
|
+
self.connection = connection
|
|
89
|
+
# init connection watching
|
|
90
|
+
if self.maintain_worker is None:
|
|
91
|
+
self.state.canceled = False
|
|
92
|
+
self.maintain_worker = asyncio.create_task(
|
|
93
|
+
self.maintain_connection_worker()
|
|
94
|
+
)
|
|
95
|
+
self.state.connecting = False
|
|
96
|
+
|
|
97
|
+
def close(self) -> None:
|
|
98
|
+
"""Close connection."""
|
|
99
|
+
_LOGGER.debug("Closing connection and canceling workers")
|
|
100
|
+
self.state.canceled = True
|
|
101
|
+
|
|
102
|
+
# Cancel and clear all pending tasks
|
|
103
|
+
for task in self.tasks:
|
|
104
|
+
task.cancel()
|
|
105
|
+
self.tasks.clear()
|
|
106
|
+
|
|
107
|
+
if self.worker is not None:
|
|
108
|
+
self.worker.cancel()
|
|
109
|
+
self.worker = None
|
|
110
|
+
if self.maintain_worker is not None:
|
|
111
|
+
self.maintain_worker.cancel()
|
|
112
|
+
self.maintain_worker = None
|
|
113
|
+
if self.connection is not None:
|
|
114
|
+
self.connection.close()
|
|
115
|
+
self.connection = None
|
|
116
|
+
|
|
117
|
+
def create_connection_task(self):
|
|
118
|
+
"""Create an async task to initiate connection."""
|
|
119
|
+
# RUF006
|
|
120
|
+
# pylint: disable-next=line-too-long
|
|
121
|
+
# noqa keep reference via: https://stackoverflow.com/questions/71938799/python-asyncio-create-task-really-need-to-keep-a-reference
|
|
122
|
+
# even if we don't care
|
|
123
|
+
task = asyncio.create_task(self.init_connection())
|
|
124
|
+
self.tasks.add(task)
|
|
125
|
+
|
|
126
|
+
def remove_task(_task):
|
|
127
|
+
try:
|
|
128
|
+
self.tasks.remove(_task)
|
|
129
|
+
except KeyError:
|
|
130
|
+
pass # already removed
|
|
131
|
+
|
|
132
|
+
task.add_done_callback(remove_task)
|
|
133
|
+
|
|
134
|
+
async def maintain_connection_worker(self) -> None:
|
|
135
|
+
"""Monitor connection and restart if there's a failure."""
|
|
136
|
+
await asyncio.sleep(PING_WORKER_WAIT_S)
|
|
137
|
+
while True:
|
|
138
|
+
if self.state.canceled:
|
|
139
|
+
break
|
|
140
|
+
self.pong_received = False
|
|
141
|
+
_LOGGER.debug("Pinging for responsiveness")
|
|
142
|
+
await self.send_request(
|
|
143
|
+
_Request(device_ping_request(source=self.client_name)),
|
|
144
|
+
)
|
|
145
|
+
await asyncio.sleep(PING_WORKER_WAIT_S)
|
|
146
|
+
if self.pong_received:
|
|
147
|
+
_LOGGER.debug("Pong received")
|
|
148
|
+
else:
|
|
149
|
+
_LOGGER.warning("Never received pong! Dumping this connection")
|
|
150
|
+
self.close()
|
|
151
|
+
self.create_connection_task()
|
|
152
|
+
break
|
|
153
|
+
|
|
154
|
+
def incoming_json(self, incoming_json: dict) -> None:
|
|
155
|
+
"""Handle incoming json."""
|
|
156
|
+
response_type = incoming_json.get("type")
|
|
157
|
+
if response_type == ResponseType.PONG:
|
|
158
|
+
self.pong_received = True
|
|
159
|
+
else:
|
|
160
|
+
self.incoming_json_callback(incoming_json)
|
|
161
|
+
|
|
162
|
+
async def send_get_device_list(self) -> bool:
|
|
163
|
+
"""Send the device list request."""
|
|
164
|
+
return await self.send_request(
|
|
165
|
+
_Request(device_list_request(source=self.client_name)),
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
async def send_state_change(
|
|
169
|
+
self,
|
|
170
|
+
uuid,
|
|
171
|
+
power,
|
|
172
|
+
dim=None,
|
|
173
|
+
completed_callback: Callable | None = None,
|
|
174
|
+
) -> None:
|
|
175
|
+
"""Send a state change request."""
|
|
176
|
+
await self.send_request(
|
|
177
|
+
_Request(
|
|
178
|
+
state_change_request(
|
|
179
|
+
uuid, power, dim, source=self.client_name,
|
|
180
|
+
),
|
|
181
|
+
completed_callback=completed_callback,
|
|
182
|
+
)
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
async def send_request(self, req: _Request) -> bool:
|
|
186
|
+
"""Send a request."""
|
|
187
|
+
if self.connection is not None:
|
|
188
|
+
await self.connection.send_data(req.get_body_str())
|
|
189
|
+
return True
|
|
190
|
+
|
|
191
|
+
_LOGGER.warning("No connection to send data to")
|
|
192
|
+
return False
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Helper for sending requests to local integrations."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Callable
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class _Request:
|
|
8
|
+
"""
|
|
9
|
+
Request to send to local integrations with
|
|
10
|
+
optional callback after successful send.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
body: dict
|
|
14
|
+
completed_callback: Callable | None = None
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self, body: dict, completed_callback: Callable | None = None
|
|
18
|
+
) -> None:
|
|
19
|
+
"""Initialize request with body and optional completed callback."""
|
|
20
|
+
self.body = body
|
|
21
|
+
self.completed_callback = completed_callback
|
|
22
|
+
|
|
23
|
+
def get_body_str(self) -> str:
|
|
24
|
+
"""Get string representation of request."""
|
|
25
|
+
return json.dumps(self.body)
|
|
26
|
+
|
|
27
|
+
def get_type(self) -> str | None:
|
|
28
|
+
"""Get the type of the request."""
|
|
29
|
+
return self.body.get("type")
|
|
30
|
+
|
|
31
|
+
def complete_callback(self):
|
|
32
|
+
"""Call the completed request callback if applicable."""
|
|
33
|
+
if self.completed_callback is not None:
|
|
34
|
+
self.completed_callback()
|