pydeako-community 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pydeako/__init__.py ADDED
@@ -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,8 @@
1
+ """Module for controlling deako devices locally."""
2
+
3
+ from ._deako import Deako, FindDevicesError
4
+
5
+ __all__ = [
6
+ 'Deako',
7
+ 'FindDevicesError',
8
+ ]
@@ -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()