Skip to content

Commit 7ca3829

Browse files
committed
Implement ResetLifeSpan
1 parent cab2f1b commit 7ca3829

7 files changed

Lines changed: 256 additions & 17 deletions

File tree

deebot_client/commands/__init__.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,22 @@
1111
COMMANDS as JSON_COMMANDS,
1212
COMMANDS_WITH_MQTT_P2P_HANDLING as JSON_COMMANDS_WITH_MQTT_P2P_HANDLING,
1313
)
14+
from .xml import (
15+
COMMANDS as XML_COMMANDS,
16+
COMMANDS_WITH_MQTT_P2P_HANDLING as XML_COMMANDS_WITH_MQTT_P2P_HANDLING,
17+
)
1418

1519
if TYPE_CHECKING:
1620
from deebot_client.command import Command, CommandMqttP2P
1721

18-
COMMANDS: dict[DataType, dict[str, type[Command]]] = {DataType.JSON: JSON_COMMANDS}
22+
COMMANDS: dict[DataType, dict[str, type[Command]]] = {
23+
DataType.JSON: JSON_COMMANDS,
24+
DataType.XML: XML_COMMANDS,
25+
}
1926

2027
COMMANDS_WITH_MQTT_P2P_HANDLING: dict[DataType, dict[str, type[CommandMqttP2P]]] = {
21-
DataType.JSON: JSON_COMMANDS_WITH_MQTT_P2P_HANDLING
28+
DataType.JSON: JSON_COMMANDS_WITH_MQTT_P2P_HANDLING,
29+
DataType.XML: XML_COMMANDS_WITH_MQTT_P2P_HANDLING,
2230
}
2331

2432

deebot_client/commands/xml/__init__.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from .charge_state import GetChargeState
1111
from .error import GetError
1212
from .fan_speed import GetFanSpeed
13-
from .life_span import GetLifeSpan
13+
from .life_span import GetLifeSpan, ResetLifeSpan
1414
from .play_sound import PlaySound
1515
from .pos import GetPos
1616
from .stats import GetCleanSum
@@ -27,14 +27,21 @@
2727
"GetLifeSpan",
2828
"GetPos",
2929
"PlaySound",
30+
"ResetLifeSpan",
3031
]
3132

3233
# fmt: off
3334
# ordered by file asc
3435
_COMMANDS: list[type[XmlCommand]] = [
36+
Charge,
37+
GetChargeState,
38+
GetCleanSum,
3539
GetError,
40+
GetFanSpeed,
3641
GetLifeSpan,
42+
GetPos,
3743
PlaySound,
44+
ResetLifeSpan,
3845
]
3946
# fmt: on
4047

deebot_client/commands/xml/common.py

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,24 @@
33
from __future__ import annotations
44

55
from abc import ABC, abstractmethod
6-
from typing import TYPE_CHECKING, cast
6+
from typing import TYPE_CHECKING, cast, override
77
from xml.etree.ElementTree import Element, SubElement
88

99
from defusedxml import ElementTree # type: ignore[import-untyped]
1010

11-
from deebot_client.command import Command, CommandWithMessageHandling, SetCommand
11+
from deebot_client.command import (
12+
Command,
13+
CommandMqttP2P,
14+
CommandWithMessageHandling,
15+
SetCommand,
16+
)
1217
from deebot_client.const import DataType
1318
from deebot_client.logging_filter import get_logger
1419
from deebot_client.message import HandlingResult, HandlingState, MessageStr
1520

1621
if TYPE_CHECKING:
22+
from typing import Any
23+
1724
from deebot_client.event_bus import EventBus
1825

1926
_LOGGER = get_logger(__name__)
@@ -76,11 +83,46 @@ def _handle_xml(cls, _: EventBus, xml: Element) -> HandlingResult:
7683
return HandlingResult.success()
7784

7885
_LOGGER.warning(
79-
'Command "%s" was not successful. XML response: %s', cls.NAME, xml
86+
'Command "%s" was not successful. XML response: %s',
87+
cls.NAME,
88+
ElementTree.tostring(xml, "unicode"),
8089
)
8190
return HandlingResult(HandlingState.FAILED)
8291

8392

93+
class XmlCommandMqttP2P(XmlCommand, CommandMqttP2P, ABC):
94+
"""Json base command for mqtt p2p channel."""
95+
96+
@classmethod
97+
def create_from_mqtt(cls, payload: str | bytes | bytearray) -> CommandMqttP2P:
98+
"""Create a command from the mqtt data."""
99+
xml = ElementTree.fromstring(payload)
100+
return cls._create_from_mqtt(xml.attrib)
101+
102+
@override
103+
def handle_mqtt_p2p(
104+
self, event_bus: EventBus, response_payload: str | bytes | bytearray
105+
) -> None:
106+
"""Handle response received over the mqtt channel "p2p"."""
107+
if isinstance(response_payload, bytearray):
108+
data = bytes(response_payload).decode()
109+
elif isinstance(response_payload, bytes):
110+
data = response_payload.decode()
111+
elif isinstance(response_payload, str):
112+
data = response_payload
113+
else:
114+
msg = "Unsupported message data type {message_type}" # type: ignore[unreachable]
115+
raise TypeError(msg.format(message_type=type(response_payload)))
116+
117+
self._handle_mqtt_p2p(event_bus, data)
118+
119+
@abstractmethod
120+
def _handle_mqtt_p2p(
121+
self, event_bus: EventBus, response: dict[str, Any] | str
122+
) -> None:
123+
"""Handle response received over the mqtt channel "p2p"."""
124+
125+
84126
class XmlSetCommand(ExecuteCommand, SetCommand, ABC):
85127
"""Xml base set command.
86128

deebot_client/commands/xml/life_span.py

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22

33
from __future__ import annotations
44

5-
from typing import TYPE_CHECKING
5+
from types import MappingProxyType
6+
from typing import TYPE_CHECKING, Any
67

8+
from deebot_client.command import InitParam
79
from deebot_client.events import LifeSpan, LifeSpanEvent
8-
from deebot_client.message import HandlingResult
10+
from deebot_client.message import HandlingResult, HandlingState
911

10-
from .common import XmlCommandWithMessageHandling
12+
from .common import ExecuteCommand, XmlCommandMqttP2P, XmlCommandWithMessageHandling
1113

1214
if TYPE_CHECKING:
1315
from xml.etree.ElementTree import Element
@@ -20,8 +22,11 @@ class GetLifeSpan(XmlCommandWithMessageHandling):
2022

2123
NAME = "GetLifeSpan"
2224

23-
def __init__(self, life_span: LifeSpan) -> None:
24-
super().__init__({"type": life_span.xml_value})
25+
def __init__(self, life_span: LifeSpan | str) -> None:
26+
xml_value = (
27+
life_span.xml_value if isinstance(life_span, LifeSpan) else life_span
28+
)
29+
super().__init__({"type": xml_value})
2530

2631
@classmethod
2732
def _handle_xml(cls, event_bus: EventBus, xml: Element) -> HandlingResult:
@@ -47,3 +52,24 @@ def _handle_xml(cls, event_bus: EventBus, xml: Element) -> HandlingResult:
4752
LifeSpanEvent(LifeSpan.from_xml(component_type), percent, left)
4853
)
4954
return HandlingResult.success()
55+
56+
57+
class ResetLifeSpan(ExecuteCommand, XmlCommandMqttP2P):
58+
"""ResetLifeSpan command."""
59+
60+
NAME = "ResetLifeSpan"
61+
_mqtt_params = MappingProxyType({"type": InitParam(str, "life_span")})
62+
63+
def __init__(self, life_span: LifeSpan | str) -> None:
64+
xml_value = (
65+
life_span.xml_value if isinstance(life_span, LifeSpan) else life_span
66+
)
67+
super().__init__({"type": xml_value})
68+
69+
def _handle_mqtt_p2p(
70+
self, event_bus: EventBus, response: dict[str, Any] | str
71+
) -> None:
72+
"""Handle response received over the mqtt channel "p2p"."""
73+
result = self.handle(event_bus, response)
74+
if result.state == HandlingState.SUCCESS:
75+
event_bus.request_refresh(LifeSpanEvent)

tests/commands/xml/__init__.py

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,65 @@
11
from __future__ import annotations
22

3-
from typing import Any
3+
from typing import TYPE_CHECKING, Any, cast
4+
from xml.etree.ElementTree import Element, SubElement
5+
6+
from defusedxml import ElementTree # type: ignore[import-untyped]
7+
from testfixtures import LogCapture
8+
9+
from deebot_client.command import CommandResult
10+
from deebot_client.message import HandlingState
11+
from tests.commands import assert_command
12+
13+
if TYPE_CHECKING:
14+
from deebot_client.commands.xml.common import ExecuteCommand
15+
16+
17+
def get_success_body(
18+
extra_attrs: dict[str, Any] | None = None, sub_element_name: str | None = None
19+
) -> str:
20+
element = ctl_element = Element("ctl")
21+
element.set("ret", "ok")
22+
23+
if extra_attrs is not None and len(extra_attrs) > 0:
24+
if sub_element_name is not None:
25+
element = SubElement(element, sub_element_name.lower())
26+
27+
if isinstance(extra_attrs, dict):
28+
for key, value in extra_attrs.items():
29+
element.set(key, value)
30+
31+
return cast("str", ElementTree.tostring(ctl_element, "unicode"))
32+
33+
34+
def get_failure_body() -> str:
35+
return '<ctl ret="error" />'
36+
37+
38+
async def assert_execute_command(
39+
command: ExecuteCommand, args: dict[str, Any] | list[Any] | None
40+
) -> None:
41+
assert command.NAME != "invalid"
42+
assert command._args == args
43+
44+
# success
45+
xml = get_request_xml(get_success_body())
46+
await assert_command(command, xml, None)
47+
48+
# failed
49+
with LogCapture() as log:
50+
body = get_failure_body()
51+
xml = get_request_xml(body)
52+
await assert_command(
53+
command, xml, None, command_result=CommandResult(HandlingState.FAILED)
54+
)
55+
56+
log.check_present(
57+
(
58+
"deebot_client.commands.xml.common",
59+
"WARNING",
60+
f'Command "{command.NAME}" was not successful. XML response: {body}',
61+
)
62+
)
463

564

665
def get_request_xml(data: str | None) -> dict[str, Any]:

tests/commands/xml/test_common.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from __future__ import annotations
2+
3+
from unittest.mock import Mock, patch
4+
5+
import pytest
6+
7+
from deebot_client.commands.xml.common import XmlCommandMqttP2P
8+
from deebot_client.event_bus import EventBus
9+
10+
11+
@pytest.mark.parametrize(
12+
("payload", "decoded_payload"),
13+
[
14+
(bytearray(bytes("test", "utf-8")), "test"),
15+
(bytes("test", "utf-8"), "test"),
16+
("test", "test"),
17+
],
18+
ids=["bytearray", "bytes", "str"],
19+
)
20+
@patch.multiple(XmlCommandMqttP2P, __abstractmethods__=set())
21+
def test_XmlCommandMqttP2P_decoding(
22+
payload: bytearray | bytes | str, decoded_payload: str
23+
) -> None:
24+
command = XmlCommandMqttP2P() # type: ignore[abstract]
25+
event_bus = Mock(spec_set=EventBus)
26+
with patch.object(command, "_handle_mqtt_p2p", return_value=None) as mqtt_handler:
27+
command.handle_mqtt_p2p(event_bus, payload)
28+
29+
mqtt_handler.assert_called_once_with(event_bus, decoded_payload)
30+
31+
32+
@patch.multiple(XmlCommandMqttP2P, __abstractmethods__=set())
33+
def test_XmlCommandMqttP2P_invalid_decoding() -> None:
34+
command = XmlCommandMqttP2P() # type: ignore[abstract]
35+
event_bus = Mock(spec_set=EventBus)
36+
with (
37+
patch.object(command, "_handle_mqtt_p2p", return_value=None),
38+
pytest.raises(TypeError),
39+
):
40+
command.handle_mqtt_p2p(event_bus, {}) # type: ignore[arg-type]

tests/commands/xml/test_life_span.py

Lines changed: 62 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,38 @@
11
from __future__ import annotations
22

3+
from typing import TYPE_CHECKING
4+
from unittest.mock import patch
5+
36
import pytest
47

58
from deebot_client.command import CommandResult
6-
from deebot_client.commands.xml import GetLifeSpan
9+
from deebot_client.commands.xml import GetLifeSpan, ResetLifeSpan
710
from deebot_client.events import LifeSpan, LifeSpanEvent
811
from deebot_client.message import HandlingState
912
from tests.commands import assert_command
1013

11-
from . import get_request_xml
14+
from . import (
15+
assert_execute_command,
16+
get_failure_body,
17+
get_request_xml,
18+
get_success_body,
19+
)
20+
21+
if TYPE_CHECKING:
22+
from deebot_client.event_bus import EventBus
1223

1324

1425
@pytest.mark.parametrize(
1526
("component_type", "lifespan_type", "left", "total", "expected_event"),
1627
[
1728
("Brush", LifeSpan.BRUSH, 50, 100, LifeSpanEvent(LifeSpan.BRUSH, 50, 50)),
29+
(
30+
"Brush",
31+
LifeSpan.BRUSH.xml_value,
32+
50,
33+
100,
34+
LifeSpanEvent(LifeSpan.BRUSH, 50, 50),
35+
),
1836
(
1937
"DustCaseHeap",
2038
LifeSpan.DUST_CASE_HEAP,
@@ -33,15 +51,15 @@
3351
)
3452
async def test_get_life_span(
3553
component_type: str,
36-
lifespan_type: LifeSpan,
54+
lifespan_type: LifeSpan | str,
3755
left: int,
3856
total: int,
3957
expected_event: LifeSpanEvent,
4058
) -> None:
41-
json = get_request_xml(
59+
xml = get_request_xml(
4260
f"<ctl ret='ok' type='{component_type}' left='{left}' total='{total}'/>"
4361
)
44-
await assert_command(GetLifeSpan(lifespan_type), json, expected_event)
62+
await assert_command(GetLifeSpan(lifespan_type), xml, expected_event)
4563

4664

4765
@pytest.mark.parametrize(
@@ -57,3 +75,42 @@ async def test_get_life_span_error(xml: str) -> None:
5775
None,
5876
command_result=CommandResult(HandlingState.ANALYSE_LOGGED),
5977
)
78+
79+
80+
@pytest.mark.parametrize(
81+
("command", "args"),
82+
[
83+
(ResetLifeSpan(LifeSpan.FILTER), {"type": LifeSpan.FILTER.xml_value}),
84+
(ResetLifeSpan(LifeSpan.FILTER.xml_value), {"type": LifeSpan.FILTER.xml_value}),
85+
(
86+
ResetLifeSpan.create_from_mqtt(b'<ctl type="Brush" />'),
87+
{"type": LifeSpan.BRUSH.xml_value},
88+
),
89+
],
90+
)
91+
async def test_ResetLifeSpan(command: ResetLifeSpan, args: dict[str, str]) -> None:
92+
await assert_execute_command(command, args)
93+
94+
95+
def test_ResetLifeSpan_invokes_refresh(event_bus: EventBus) -> None:
96+
command = ResetLifeSpan(LifeSpan.FILTER)
97+
success_response = get_success_body()
98+
99+
with patch.object(
100+
event_bus, "request_refresh", return_value=None
101+
) as mock_request_refresh:
102+
command.handle_mqtt_p2p(event_bus, success_response)
103+
104+
mock_request_refresh.assert_called_with(LifeSpanEvent)
105+
106+
107+
def test_ResetLifeSpan_not_invokes_refresh(event_bus: EventBus) -> None:
108+
command = ResetLifeSpan(LifeSpan.FILTER)
109+
failure_response = get_failure_body()
110+
111+
with patch.object(
112+
event_bus, "request_refresh", return_value=None
113+
) as mock_request_refresh:
114+
command.handle_mqtt_p2p(event_bus, failure_response)
115+
116+
mock_request_refresh.assert_not_called()

0 commit comments

Comments
 (0)