Skip to content
This repository has been archived by the owner on Mar 8, 2022. It is now read-only.

Commit

Permalink
use WaterAmount in WaterInfoEventDto (#95)
Browse files Browse the repository at this point in the history
* use WaterAmount in WaterInfoEventDto

* fix equal of DisplayNameIntEnum

* fix pylint
  • Loading branch information
edenhaus authored Oct 26, 2021
1 parent b50b5e5 commit ff9ddfe
Show file tree
Hide file tree
Showing 12 changed files with 68 additions and 50 deletions.
15 changes: 8 additions & 7 deletions deebotozmo/cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
#!/usr/bin/env python3
"""Cli module."""
import sys

try:
import click
except ModuleNotFoundError:
sys.exit('Dependencies missing!! Please run "pip install deebotozmo[cli]"')

import asyncio
import base64
import configparser
Expand All @@ -9,19 +16,13 @@
import mimetypes
import os
import platform
import sys
import time
from dataclasses import asdict
from functools import wraps
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union

import aiohttp

try:
import click
except ModuleNotFoundError:
sys.exit('Dependencies missing!! Please run "pip install deebotozmo[cli]"')

from deebotozmo import create_instances
from deebotozmo.commands import Charge, Clean, PlaySound, SetFanSpeed, SetWaterInfo
from deebotozmo.commands.clean import CleanAction, CleanArea, CleanMode
Expand Down Expand Up @@ -333,7 +334,7 @@ async def on_fan_event(fan_speed_event: FanSpeedEventDto) -> None:
fan_speed_listener.unsubscribe()

async def on_water_level(water_info_event: WaterInfoEventDto) -> None:
print(f"Water Level: {water_info_event.amount}")
print(f"Water Level: {water_info_event.amount.display_name}")
event.set()

event.clear()
Expand Down
2 changes: 1 addition & 1 deletion deebotozmo/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from .play_sound import PlaySound
from .relocation import SetRelocationState
from .stats import GetStats
from .water_info import GetWaterInfo, SetWaterInfo, WaterLevel
from .water_info import GetWaterInfo, SetWaterInfo

# fmt: off
# ordered by file asc
Expand Down
22 changes: 5 additions & 17 deletions deebotozmo/commands/water_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,12 @@
import logging
from typing import Any, Dict, Mapping, Union

from ..events import WaterInfoEventDto
from ..util import DisplayNameIntEnum
from ..events import WaterAmount, WaterInfoEventDto
from .common import EventBus, SetCommand, _NoArgsCommand

_LOGGER = logging.getLogger(__name__)


class WaterLevel(DisplayNameIntEnum):
"""Enum class for all possible water levels."""

LOW = 1
MEDIUM = 2
HIGH = 3
ULTRAHIGH = 4


class GetWaterInfo(_NoArgsCommand):
"""Get water info command."""

Expand All @@ -35,9 +25,7 @@ def _handle_body_data_dict(cls, event_bus: EventBus, data: Dict[str, Any]) -> bo
if amount is not None:
try:
event_bus.notify(
WaterInfoEventDto(
mop_attached, WaterLevel(int(amount)).display_name
)
WaterInfoEventDto(mop_attached, WaterAmount(int(amount)))
)
return True
except ValueError:
Expand All @@ -54,13 +42,13 @@ class SetWaterInfo(SetCommand):
get_command = GetWaterInfo

def __init__(
self, amount: Union[str, int, WaterLevel], **kwargs: Mapping[str, Any]
self, amount: Union[str, int, WaterAmount], **kwargs: Mapping[str, Any]
) -> None:
# removing "enable" as we don't can set it
remove_from_kwargs = ["enable"]
if isinstance(amount, str):
amount = WaterLevel.get(amount)
if isinstance(amount, WaterLevel):
amount = WaterAmount.get(amount)
if isinstance(amount, WaterAmount):
amount = amount.value

super().__init__({"amount": amount, "enable": 0}, remove_from_kwargs, **kwargs)
13 changes: 2 additions & 11 deletions deebotozmo/events/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
from enum import Enum, unique
from typing import Any, Dict, List, Optional

from deebotozmo.events.base import EventDto
from deebotozmo.models import Room, VacuumState
from deebotozmo.util import DisplayNameIntEnum


class EventDto:
"""Event base class."""
from .water_info import WaterAmount, WaterInfoEventDto


@dataclass(frozen=True)
Expand Down Expand Up @@ -136,11 +135,3 @@ class StatusEventDto(EventDto):

available: bool
state: Optional[VacuumState]


@dataclass(frozen=True)
class WaterInfoEventDto(EventDto):
"""Water info event representation."""

mop_attached: bool
amount: str
5 changes: 5 additions & 0 deletions deebotozmo/events/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Base event module."""


class EventDto:
"""Event base class."""
23 changes: 23 additions & 0 deletions deebotozmo/events/water_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""Water info event module."""
from dataclasses import dataclass

from deebotozmo.util import DisplayNameIntEnum

from .base import EventDto


class WaterAmount(DisplayNameIntEnum):
"""Enum class for all possible water amounts."""

LOW = 1
MEDIUM = 2
HIGH = 3
ULTRAHIGH = 4


@dataclass(frozen=True)
class WaterInfoEventDto(EventDto):
"""Water info event representation."""

mop_attached: bool
amount: WaterAmount
16 changes: 14 additions & 2 deletions deebotozmo/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,14 @@ class DisplayNameIntEnum(IntEnum):
"""Int enum with a property "display_name"."""

def __new__(cls, *args: Tuple, **_: Mapping) -> "DisplayNameIntEnum":
"""Create new enum."""
"""Create new DisplayNameIntEnum."""
obj = int.__new__(cls)
obj._value_ = args[0]
return obj

def __init__(self, _: int, display_name: Optional[str] = None):
def __init__(self, value: int, display_name: Optional[str] = None):
super().__init__()
self._value_ = value
self._display_name = display_name

@property
Expand All @@ -66,3 +67,14 @@ def get(cls, value: str) -> "DisplayNameIntEnum":
return member

raise ValueError(f"'{value}' is not a valid {cls.__name__} member")

def __eq__(self, x: object) -> bool:
if not isinstance(x, type(self)):
return False
return bool(self._value_ == x._value_)

def __ne__(self, x: object) -> bool:
return not self.__eq__(x)

def __hash__(self) -> int:
return hash(self._value_)
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ max-line-length = 88
# W503: Line break occurred before a binary operator
# E203: Whitespace before ':'
# D202 No blank lines allowed after function docstring
# D105 Missing docstring in magic method
# D107 Missing docstring in __init__
ignore =
E501,
W503,
E203,
D202,
D105,
D107

# Disable unused imports for __init__.py
Expand Down
3 changes: 1 addition & 2 deletions tests/commands/test_fan_speed.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from deebotozmo.commands import FanSpeedLevel

from .helpers import verify_DisplayNameEnum_unique
from tests.helpers import verify_DisplayNameEnum_unique


def test_FanSpeedLevel_unique():
Expand Down
10 changes: 0 additions & 10 deletions tests/commands/test_water_info.py

This file was deleted.

7 changes: 7 additions & 0 deletions tests/events/test_water_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from deebotozmo.events import WaterAmount
from tests.helpers import verify_DisplayNameEnum_unique


def test_WaterLevel_unique():
verify_DisplayNameEnum_unique(WaterAmount)

File renamed without changes.

0 comments on commit ff9ddfe

Please sign in to comment.