Skip to content

Commit

Permalink
fix: issues with switch and time entities
Browse files Browse the repository at this point in the history
  • Loading branch information
humbertogontijo committed Jun 23, 2023
1 parent 4da168f commit d8fc7ee
Show file tree
Hide file tree
Showing 9 changed files with 177 additions and 172 deletions.
6 changes: 3 additions & 3 deletions custom_components/roborock/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from .config_flow import CAMERA_VALUES
from .const import *
from .coordinator import RoborockDataUpdateCoordinator
from .device import RoborockEntityBase
from .device import RoborockEntity
from .roborock_typing import RoborockHassDeviceInfo
from .utils import set_nested_dict

Expand Down Expand Up @@ -80,7 +80,7 @@ async def async_setup_entry(
async_add_entities(entities, True)


class VacuumCameraMap(RoborockEntityBase, Camera):
class VacuumCameraMap(RoborockEntity, Camera):
"""Representation of a Roborock camera map."""

_is_map_valid_by_device = {}
Expand All @@ -93,7 +93,7 @@ def __init__(
coordinator: RoborockDataUpdateCoordinator,
) -> None:
"""Create Roborock map."""
RoborockEntityBase.__init__(self, device_info, unique_id)
RoborockEntity.__init__(self, device_info, unique_id, coordinator.api)
Camera.__init__(self)
self.coordinator = coordinator
self._store_map_image = False
Expand Down
26 changes: 6 additions & 20 deletions custom_components/roborock/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,31 +90,17 @@ async def fill_device_multi_maps_list(self, device_info: RoborockHassDeviceInfo)
map_info.mapFlag: map_info.name for map_info in multi_maps_list.map_info}
device_info.map_mapping = map_mapping

async def fill_sound_volume(self, device_info: RoborockHassDeviceInfo) -> None:
"""Fetch current sound volume."""
sound_volume = await self.api.get_sound_volume()
device_info.sound_volume = sound_volume

async def fill_flow_led_status(self, device_info: RoborockHassDeviceInfo) -> None:
"""Fetch current sound volume."""
flow_led_status = await self.api.get_flow_led_status()
device_info.flow_led_status = flow_led_status

async def fill_child_lock_status(self, device_info: RoborockHassDeviceInfo) -> None:
"""Fetch current sound volume."""
child_lock_status = await self.api.get_child_lock_status()
device_info.child_lock_status = child_lock_status

async def fill_device_info(self, device_info: RoborockHassDeviceInfo):
"""Merge device information."""
await asyncio.gather(
*([
self.fill_device_prop(device_info),
self.fill_device_multi_maps_list(device_info),
self.fill_room_mapping(device_info),
self.fill_sound_volume(device_info),
self.fill_flow_led_status(device_info),
self.fill_child_lock_status(device_info),
asyncio.gather(
*([
self.fill_device_multi_maps_list(device_info),
self.fill_room_mapping(device_info),
]), return_exceptions=True
)
])
)

Expand Down
34 changes: 23 additions & 11 deletions custom_components/roborock/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity import DeviceInfo, Entity
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from roborock.api import RT
from roborock.api import RT, RoborockClient
from roborock.containers import Status
from roborock.exceptions import RoborockException
from roborock.roborock_typing import RoborockCommand
Expand All @@ -19,15 +19,16 @@
_LOGGER = logging.getLogger(__name__)


class RoborockEntityBase(Entity):
class RoborockEntity(Entity):
"""Representation of a base a coordinated Roborock Entity."""

_attr_has_entity_name = True

def __init__(
self,
device_info: RoborockHassDeviceInfo,
unique_id: str | None = None,
unique_id: str,
api: RoborockClient,
) -> None:
"""Initialize the coordinated Roborock Device."""
self._device_name = device_info.device.name
Expand All @@ -36,6 +37,7 @@ def __init__(
self._device_model = device_info.model
self._fw_version = device_info.device.fv
self._device_info = device_info
self.api = api

@property
def device_info(self) -> DeviceInfo:
Expand Down Expand Up @@ -70,8 +72,23 @@ def set_invalid_map(self) -> None:
"""Set map as invalid so it can be updated."""
self._device_info.is_map_valid = False

async def send(
self,
method: RoborockCommand,
params: Optional[list | dict] = None,
return_type: Optional[type[RT]] = None,
) -> RT:
"""Send a command to a vacuum cleaner."""
try:
response = await self.api.send_command(method, params, return_type)
except RoborockException as err:
raise HomeAssistantError(
f"Error while calling {method.name} with {params}"
) from err
return response


class RoborockCoordinatedEntity(RoborockEntityBase, CoordinatorEntity[RoborockDataUpdateCoordinator]):
class RoborockCoordinatedEntity(RoborockEntity, CoordinatorEntity[RoborockDataUpdateCoordinator]):
"""Representation of a base a coordinated Roborock Entity."""

_attr_has_entity_name = True
Expand All @@ -83,7 +100,7 @@ def __init__(
unique_id: str | None = None,
) -> None:
"""Initialize the coordinated Roborock Device."""
RoborockEntityBase.__init__(self, device_info, unique_id)
RoborockEntity.__init__(self, device_info, unique_id, coordinator.api)
CoordinatorEntity.__init__(self, coordinator)
self._device_name = device_info.device.name
self._attr_unique_id = unique_id
Expand All @@ -98,11 +115,6 @@ async def send(
return_type: Optional[type[RT]] = None,
) -> RT:
"""Send a command to a vacuum cleaner."""
try:
response = await self.coordinator.api.send_command(method, params, return_type)
except RoborockException as err:
raise HomeAssistantError(
f"Error while calling {method.name} with {params}"
) from err
response = await super().send(method, params, return_type)
self.coordinator.schedule_refresh()
return response
2 changes: 1 addition & 1 deletion custom_components/roborock/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"roborock"
],
"requirements": [
"python-roborock==0.24.1"
"python-roborock==0.27.2"
],
"version": "1.0.5"
}
19 changes: 12 additions & 7 deletions custom_components/roborock/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@

from dataclasses import dataclass
from collections.abc import Callable
from typing import Any
from collections.abc import Coroutine

from homeassistant.components.number import NumberEntity, NumberEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import slugify
from roborock.roborock_typing import RoborockCommand
from roborock.api import AttributeCache
from roborock.command_cache import CacheableAttribute

from . import DomainData
from .const import DOMAIN
Expand All @@ -22,8 +25,10 @@
class RoborockNumberDescriptionMixin:
"""Define an entity description mixin for button entities."""

value_fn: Callable[[RoborockHassDeviceInfo], float]
api_command: RoborockCommand
# Gets the status of the switch
cache_key: CacheableAttribute
# Sets the status of the switch
update_value: Callable[[AttributeCache, bool], Coroutine[Any, Any, dict]]


@dataclass
Expand All @@ -42,8 +47,8 @@ class RoborockNumberDescription(
native_step=1,
translation_key="sound_volume",
name="Sound Volume",
value_fn=lambda data: data.sound_volume,
api_command=RoborockCommand.CHANGE_SOUND_VOLUME
cache_key=CacheableAttribute.sound_volume,
update_value=lambda cache, value: cache.update_value([value]),
)
]

Expand Down Expand Up @@ -92,9 +97,9 @@ def __init__(
@property
def native_value(self) -> float | None:
"""Get native value."""
return self.entity_description.value_fn(self.coordinator.data)
return self.api.cache.get(self.entity_description.cache_key)

async def async_set_native_value(self, value: float) -> None:
"""Set native value."""
int_value = int(value)
await self.send(self.entity_description.api_command, [int_value])
await self.entity_description.update_value(self.api.cache.get(self.entity_description.cache_key), int_value)
5 changes: 1 addition & 4 deletions custom_components/roborock/roborock_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from dataclasses import dataclass
from typing import Optional, TypedDict

from roborock import ChildLockStatus, DeviceData, DeviceProp, FlowLedStatus
from roborock import DeviceData, DeviceProp


class DeviceNetwork(TypedDict):
Expand Down Expand Up @@ -31,6 +31,3 @@ class RoborockHassDeviceInfo(DeviceData):
map_mapping: Optional[dict[int, str]] = None
room_mapping: Optional[dict[int, str]] = None
current_room: Optional[int] = None
sound_volume: Optional[int] = None
flow_led_status: Optional[FlowLedStatus] = None
child_lock_status: Optional[ChildLockStatus] = None
Loading

0 comments on commit d8fc7ee

Please sign in to comment.