forked from DeebotUniverse/client.py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.py
More file actions
366 lines (299 loc) · 11.6 KB
/
command.py
File metadata and controls
366 lines (299 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
"""Base command."""
from __future__ import annotations
from abc import ABC, abstractmethod
import asyncio
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, final
from deebot_client.events import AvailabilityEvent
from deebot_client.exceptions import (
ApiTimeoutError,
DeebotError,
)
from deebot_client.util import verify_required_class_variables_exists
from .const import PATH_API_IOT_DEVMANAGER, REQUEST_HEADERS, DataType
from .logging_filter import get_logger
from .message import HandlingResult, HandlingState, Message
if TYPE_CHECKING:
from types import MappingProxyType
from .authentication import Authenticator
from .event_bus import EventBus
from .models import ApiDeviceInfo
_LOGGER = get_logger(__name__)
@dataclass(frozen=True)
class CommandResult(HandlingResult):
"""Command result object."""
requested_commands: list[Command] = field(default_factory=list)
@classmethod
def success(cls) -> CommandResult:
"""Create result with handling success."""
return CommandResult(HandlingState.SUCCESS)
@classmethod
def analyse(cls) -> CommandResult:
"""Create result with handling analyse."""
return CommandResult(HandlingState.ANALYSE)
@dataclass(frozen=True)
class DeviceCommandResult:
"""Device command result object.
Returns
-------
device_reached (bool): True if the command was targeting the bot, and it responded in time. False otherwise.
This value is not indicating if the command was executed successfully.
raw_response (dict[str, Any]): The command response data.
"""
device_reached: bool
raw_response: dict[str, Any] = field(default_factory=dict)
class Command(ABC):
"""Abstract command object."""
_targets_bot: bool = True
NAME: str
DATA_TYPE: DataType
def __init_subclass__(cls) -> None:
verify_required_class_variables_exists(cls, ("NAME", "DATA_TYPE"))
return super().__init_subclass__()
def __init__(self, args: dict[str, Any] | list[Any] | None = None) -> None:
if args is None:
args = {}
self._args = args
@abstractmethod
def _get_payload(self) -> dict[str, Any] | list[Any] | str:
"""Get the payload for the rest call."""
@final
async def execute(
self,
authenticator: Authenticator,
device_info: ApiDeviceInfo,
event_bus: EventBus,
) -> DeviceCommandResult:
"""Execute command."""
try:
result, response = await self._execute(
authenticator, device_info, event_bus
)
if result.state == HandlingState.SUCCESS:
# Execute command which are requested by the handler
async with asyncio.TaskGroup() as tg:
for requested_command in result.requested_commands:
tg.create_task(
requested_command.execute(
authenticator, device_info, event_bus
)
)
return DeviceCommandResult(
device_reached=self._targets_bot, raw_response=response
)
except Exception: # pylint: disable=broad-except
_LOGGER.warning(
"Could not execute command %s",
self.NAME,
exc_info=True,
)
return DeviceCommandResult(device_reached=False)
async def _execute(
self,
authenticator: Authenticator,
device_info: ApiDeviceInfo,
event_bus: EventBus,
) -> tuple[CommandResult, dict[str, Any]]:
"""Execute command."""
try:
response = await self._execute_api_request(authenticator, device_info)
except ApiTimeoutError:
_LOGGER.warning(
"Could not execute command %s: Timeout reached",
self.NAME,
)
return CommandResult(HandlingState.ERROR), {}
result = self.__handle_response(event_bus, response)
if result.state == HandlingState.ANALYSE:
_LOGGER.debug(
"ANALYSE: Could not handle command: %s with %s", self.NAME, response
)
return (
CommandResult(
HandlingState.ANALYSE_LOGGED,
result.args,
result.requested_commands,
),
response,
)
if result.state == HandlingState.ERROR:
_LOGGER.warning("Could not parse %s: %s", self.NAME, response)
return result, response
async def _execute_api_request(
self, authenticator: Authenticator, device_info: ApiDeviceInfo
) -> dict[str, Any]:
payload = {
"cmdName": self.NAME,
"payload": self._get_payload(),
"payloadType": self.DATA_TYPE.value,
"td": "q",
"toId": device_info["did"],
"toRes": device_info["resource"],
"toType": device_info["class"],
}
credentials = await authenticator.authenticate()
query_params = {
"mid": payload["toType"],
"did": payload["toId"],
"td": payload["td"],
"u": credentials.user_id,
"cv": "1.67.3",
"t": "a",
"av": "1.3.1",
}
return await authenticator.post_authenticated(
PATH_API_IOT_DEVMANAGER,
payload,
query_params=query_params,
headers=REQUEST_HEADERS,
)
def __handle_response(
self, event_bus: EventBus, response: dict[str, Any]
) -> CommandResult:
"""Handle response from a command.
:return: A message response
"""
try:
result = self._handle_response(event_bus, response)
if result.state == HandlingState.ANALYSE:
_LOGGER.debug(
"ANALYSE: Could not handle command: %s with %s", self.NAME, response
)
return CommandResult(
HandlingState.ANALYSE_LOGGED,
result.args,
result.requested_commands,
)
return result
except Exception: # pylint: disable=broad-except
_LOGGER.warning(
"Could not parse response for %s: %s",
self.NAME,
response,
exc_info=True,
)
return CommandResult(HandlingState.ERROR)
@abstractmethod
def _handle_response(
self, event_bus: EventBus, response: dict[str, Any]
) -> CommandResult:
"""Handle response from a command.
:return: A message response
"""
def __eq__(self, obj: object) -> bool:
if isinstance(obj, Command):
return self.NAME == obj.NAME and self._args == obj._args
return False
def __hash__(self) -> int:
return hash(self.NAME) + hash(self._args)
class CommandWithMessageHandling(Command, Message, ABC):
"""Command, which handle response by itself."""
_is_available_check: bool = False
def _handle_response(
self, event_bus: EventBus, response: dict[str, Any]
) -> CommandResult:
"""Handle response from a command.
:return: A message response
"""
if response.get("ret") == "ok":
data = response.get("resp", response)
result = self.handle(event_bus, data)
return CommandResult(result.state, result.args)
if errno := response.get("errno"):
match errno:
case 4200:
# bot offline
_LOGGER.info(
'Device is offline. Could not execute command "%s"', self.NAME
)
event_bus.notify(AvailabilityEvent(available=False))
return CommandResult(HandlingState.FAILED)
case 500:
if self._is_available_check:
_LOGGER.info(
'No response received for command "%s" during availability-check.',
self.NAME,
)
else:
_LOGGER.warning(
'No response received for command "%s". This can happen if the device has network issues or does not support the command',
self.NAME,
)
return CommandResult(HandlingState.FAILED)
_LOGGER.warning('Command "%s" was not successfully.', self.NAME)
return CommandResult(HandlingState.ANALYSE)
@dataclass
class InitParam:
"""Init param."""
type_: type
name: str | None = None
optional: bool = field(default=False, kw_only=True)
class CommandMqttP2P(Command, ABC):
"""Command which can handle mqtt p2p messages."""
_mqtt_params: MappingProxyType[str, InitParam | None]
@abstractmethod
def handle_mqtt_p2p(
self, event_bus: EventBus, response_payload: str | bytes | bytearray
) -> None:
"""Handle response received over the mqtt channel "p2p"."""
@classmethod
@abstractmethod
def create_from_mqtt(cls, payload: str | bytes | bytearray) -> CommandMqttP2P:
"""Create a command from the mqtt data."""
@classmethod
def _create_from_mqtt(cls, data: dict[str, Any]) -> CommandMqttP2P:
"""Create a command from the mqtt data."""
values: dict[str, Any] = {}
if not hasattr(cls, "_mqtt_params"):
raise DeebotError("_mqtt_params not set")
for name, param in cls._mqtt_params.items():
if param is None:
# Remove field
data.pop(name, None)
else:
try:
values[param.name or name] = cls._pop_or_raise(
name, param.type_, data
)
except KeyError as err:
if not param.optional:
msg = f'"{name}" is missing in {data}'
raise DeebotError(msg) from err
if data:
_LOGGER.debug("Following data will be ignored: %s", data)
return cls(**values)
@classmethod
def _pop_or_raise(cls, name: str, type_: type, data: dict[str, Any]) -> Any:
value = data.pop(name)
try:
return cls._decode(type_, value)
except ValueError as err:
msg = f'Could not convert "{value}" of {name} into {type_}'
raise DeebotError(msg) from err
@classmethod
def _decode(cls, type_: type, value: Any) -> Any:
return type_(value)
class GetCommand(CommandWithMessageHandling, ABC):
"""Base get command."""
@classmethod
@abstractmethod
def handle_set_args(
cls, event_bus: EventBus, args: dict[str, Any]
) -> HandlingResult:
"""Handle arguments of set command."""
class SetCommand(CommandWithMessageHandling, CommandMqttP2P, ABC):
"""Base set command.
Command needs to be linked to the "get" command, for handling (updating) the sensors.
"""
@property
@abstractmethod
def get_command(self) -> type[GetCommand]:
"""Return the corresponding "get" command."""
raise NotImplementedError # pragma: no cover
def _handle_mqtt_p2p(
self, event_bus: EventBus, response: dict[str, Any] | str
) -> None:
"""Handle response received over the mqtt channel "p2p"."""
result = self.handle(event_bus, response)
if result.state == HandlingState.SUCCESS and isinstance(self._args, dict):
self.get_command.handle_set_args(event_bus, self._args)