Skip to content

Commit

Permalink
Refactor message (#368)
Browse files Browse the repository at this point in the history
  • Loading branch information
edenhaus authored Dec 12, 2023
1 parent 6afeb4e commit 422b51a
Show file tree
Hide file tree
Showing 11 changed files with 62 additions and 33 deletions.
21 changes: 16 additions & 5 deletions deebot_client/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .const import PATH_API_IOT_DEVMANAGER, REQUEST_HEADERS, DataType
from .event_bus import EventBus
from .logging_filter import get_logger
from .message import HandlingResult, HandlingState, MessageBody
from .message import HandlingResult, HandlingState, Message
from .models import DeviceInfo

_LOGGER = get_logger(__name__)
Expand Down Expand Up @@ -69,7 +69,7 @@ async def execute(
Returns
-------
bot_reached (bool): True if the command was targeting the bot and it responded in time. False otherwise.
bot_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.
"""
try:
Expand Down Expand Up @@ -191,7 +191,7 @@ def __hash__(self) -> int:
return hash(self.name) + hash(self._args)


class CommandWithMessageHandling(Command, MessageBody, ABC):
class CommandWithMessageHandling(Command, Message, ABC):
"""Command, which handle response by itself."""

_is_available_check: bool = False
Expand Down Expand Up @@ -284,6 +284,17 @@ def _pop_or_raise(name: str, type_: type, data: dict[str, Any]) -> Any:
raise DeebotError(msg) from err


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.
Expand All @@ -292,12 +303,12 @@ class SetCommand(CommandWithMessageHandling, CommandMqttP2P, ABC):

@property
@abstractmethod
def get_command(self) -> type[CommandWithMessageHandling]:
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]) -> 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(event_bus, self._args)
self.get_command.handle_set_args(event_bus, self._args)
6 changes: 3 additions & 3 deletions deebot_client/commands/json/clean_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
from deebot_client.command import InitParam
from deebot_client.event_bus import EventBus
from deebot_client.events import CleanCountEvent
from deebot_client.message import HandlingResult, MessageBodyDataDict
from deebot_client.message import HandlingResult

from .common import JsonCommandWithMessageHandling, JsonSetCommand
from .common import JsonGetCommand, JsonSetCommand


class GetCleanCount(JsonCommandWithMessageHandling, MessageBodyDataDict):
class GetCleanCount(JsonGetCommand):
"""Get clean count command."""

name = "getCleanCount"
Expand Down
21 changes: 19 additions & 2 deletions deebot_client/commands/json/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from deebot_client.command import (
Command,
CommandWithMessageHandling,
GetCommand,
InitParam,
SetCommand,
)
Expand All @@ -17,6 +18,7 @@
from deebot_client.message import (
HandlingResult,
HandlingState,
MessageBody,
MessageBodyDataDict,
)

Expand Down Expand Up @@ -46,7 +48,9 @@ def _get_payload(self) -> dict[str, Any] | list[Any]:
return payload


class JsonCommandWithMessageHandling(JsonCommand, CommandWithMessageHandling, ABC):
class JsonCommandWithMessageHandling(
JsonCommand, CommandWithMessageHandling, MessageBody, ABC
):
"""Command, which handle response by itself."""


Expand Down Expand Up @@ -74,7 +78,20 @@ class JsonSetCommand(ExecuteCommand, SetCommand, ABC):
"""


class GetEnableCommand(JsonCommandWithMessageHandling, MessageBodyDataDict, ABC):
class JsonGetCommand(
JsonCommandWithMessageHandling, MessageBodyDataDict, GetCommand, ABC
):
"""Json get command."""

@classmethod
def handle_set_args(
cls, event_bus: EventBus, args: dict[str, Any]
) -> HandlingResult:
"""Handle arguments of set command."""
return cls._handle_body_data_dict(event_bus, args)


class GetEnableCommand(JsonGetCommand, ABC):
"""Abstract get enable command."""

@property # type: ignore[misc]
Expand Down
6 changes: 3 additions & 3 deletions deebot_client/commands/json/efficiency.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
from deebot_client.command import InitParam
from deebot_client.event_bus import EventBus
from deebot_client.events import EfficiencyMode, EfficiencyModeEvent
from deebot_client.message import HandlingResult, MessageBodyDataDict
from deebot_client.message import HandlingResult

from .common import JsonCommandWithMessageHandling, JsonSetCommand
from .common import JsonGetCommand, JsonSetCommand


class GetEfficiencyMode(JsonCommandWithMessageHandling, MessageBodyDataDict):
class GetEfficiencyMode(JsonGetCommand):
"""Get efficiency mode command."""

name = "getEfficiency"
Expand Down
2 changes: 1 addition & 1 deletion deebot_client/commands/json/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def _handle_body_data_dict(
return HandlingResult.analyse()


# from https://github.com/mrbungle64/ecovacs-deebot.js/blob/master/library/errorCodes.js
# from https://github.com/mrbungle64/ecovacs-deebot.js/blob/master/library/errorCodes.json
_ERROR_CODES = {
-3: "Error parsing response data",
-2: "Internal error",
Expand Down
6 changes: 3 additions & 3 deletions deebot_client/commands/json/fan_speed.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
from deebot_client.command import InitParam
from deebot_client.event_bus import EventBus
from deebot_client.events import FanSpeedEvent, FanSpeedLevel
from deebot_client.message import HandlingResult, MessageBodyDataDict
from deebot_client.message import HandlingResult

from .common import JsonCommandWithMessageHandling, JsonSetCommand
from .common import JsonGetCommand, JsonSetCommand


class GetFanSpeed(JsonCommandWithMessageHandling, MessageBodyDataDict):
class GetFanSpeed(JsonGetCommand):
"""Get fan speed command."""

name = "getSpeed"
Expand Down
6 changes: 3 additions & 3 deletions deebot_client/commands/json/volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
from deebot_client.command import InitParam
from deebot_client.event_bus import EventBus
from deebot_client.events import VolumeEvent
from deebot_client.message import HandlingResult, MessageBodyDataDict
from deebot_client.message import HandlingResult

from .common import JsonCommandWithMessageHandling, JsonSetCommand
from .common import JsonGetCommand, JsonSetCommand


class GetVolume(JsonCommandWithMessageHandling, MessageBodyDataDict):
class GetVolume(JsonGetCommand):
"""Get volume command."""

name = "getVolume"
Expand Down
6 changes: 3 additions & 3 deletions deebot_client/commands/json/water_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
from deebot_client.command import InitParam
from deebot_client.event_bus import EventBus
from deebot_client.events import WaterAmount, WaterInfoEvent
from deebot_client.message import HandlingResult, MessageBodyDataDict
from deebot_client.message import HandlingResult

from .common import JsonCommandWithMessageHandling, JsonSetCommand
from .common import JsonGetCommand, JsonSetCommand


class GetWaterInfo(JsonCommandWithMessageHandling, MessageBodyDataDict):
class GetWaterInfo(JsonGetCommand):
"""Get water info command."""

name = "getWaterInfo"
Expand Down
6 changes: 3 additions & 3 deletions deebot_client/commands/json/work_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
from deebot_client.command import InitParam
from deebot_client.event_bus import EventBus
from deebot_client.events import WorkMode, WorkModeEvent
from deebot_client.message import HandlingResult, MessageBodyDataDict
from deebot_client.message import HandlingResult

from .common import JsonCommandWithMessageHandling, JsonSetCommand
from .common import JsonGetCommand, JsonSetCommand


class GetWorkMode(JsonCommandWithMessageHandling, MessageBodyDataDict):
class GetWorkMode(JsonGetCommand):
"""Get work mode command."""

name = "getWorkMode"
Expand Down
9 changes: 5 additions & 4 deletions deebot_client/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,7 @@ def _handle(
:return: A message response
"""
if isinstance(message, dict):
data_body = message.get("body", message)
return cls.__handle_body(event_bus, data_body)
return cls.__handle_body(event_bus, message["body"])

return super()._handle(event_bus, message)

Expand Down Expand Up @@ -165,8 +164,10 @@ def _handle_body(cls, event_bus: EventBus, body: dict[str, Any]) -> HandlingResu
:return: A message response
"""
data = body.get("data", body)
return cls.__handle_body_data(event_bus, data)
if "data" in body:
return cls.__handle_body_data(event_bus, body["data"])

return super()._handle_body(event_bus, body)


class MessageBodyDataDict(MessageBodyData):
Expand Down
6 changes: 3 additions & 3 deletions tests/commands/json/test_work_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,18 @@ def test_WorkMode_unique() -> None:
({"mode": 3}, WorkModeEvent(WorkMode.MOP_AFTER_VACUUM)),
],
)
async def test_GetWaterInfo(json: dict[str, Any], expected: WorkModeEvent) -> None:
async def test_GetWorkMode(json: dict[str, Any], expected: WorkModeEvent) -> None:
json = get_request_json(get_success_body(json))
await assert_command(GetWorkMode(), json, expected)


@pytest.mark.parametrize(("value"), [WorkMode.MOP_AFTER_VACUUM, "mop_after_vacuum"])
async def test_SetWaterInfo(value: WorkMode | str) -> None:
async def test_SetWorkMode(value: WorkMode | str) -> None:
command = SetWorkMode(value)
args = {"mode": 3}
await assert_set_command(command, args, WorkModeEvent(WorkMode.MOP_AFTER_VACUUM))


def test_SetWaterInfo_inexisting_value() -> None:
def test_SetWorkMode_inexisting_value() -> None:
with pytest.raises(ValueError, match="'INEXSTING' is not a valid WorkMode member"):
SetWorkMode("inexsting")

0 comments on commit 422b51a

Please sign in to comment.