Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove EventListener #276

Merged
merged 3 commits into from
Jul 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 16 additions & 40 deletions deebot_client/events/event_bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,42 +17,18 @@
T = TypeVar("T", bound=Event)


class EventListener(Generic[T]):
"""Object that allows event consumers to easily unsubscribe from event bus."""

def __init__(
self,
event_processing_data: "_EventProcessingData",
callback: Callable[[T], Coroutine[Any, Any, None]],
) -> None:
self._event_processing_data: Final = event_processing_data
self.callback: Final = callback

def unsubscribe(self) -> None:
"""Unsubscribe from event bus."""
self._event_processing_data.subscribers.remove(self)


class _EventProcessingData(Generic[T]):
"""Data class, which holds all needed data per EventDto."""

def __init__(self) -> None:
super().__init__()

self._subscribers: Final[list[EventListener[T]]] = []
self._semaphore: Final = asyncio.Semaphore(1)
self.subscriber_callbacks: Final[
list[Callable[[T], Coroutine[Any, Any, None]]]
] = []
self.semaphore: Final = asyncio.Semaphore(1)
self.last_event: T | None = None

@property
def subscribers(self) -> list[EventListener[T]]:
"""Return subscribers."""
return self._subscribers

@property
def semaphore(self) -> asyncio.Semaphore:
"""Return semaphore."""
return self._semaphore


class EventBus:
"""A very simple event bus system."""
Expand All @@ -70,7 +46,7 @@ def __init__(
def has_subscribers(self, event: type[T]) -> bool:
"""Return True, if emitter has subscribers."""
return (
len(self._event_processing_dict[event].subscribers) > 0
len(self._event_processing_dict[event].subscriber_callbacks) > 0
if event in self._event_processing_dict
else False
)
Expand All @@ -79,23 +55,23 @@ def subscribe(
self,
event_type: type[T],
callback: Callable[[T], Coroutine[Any, Any, None]],
) -> EventListener[T]:
) -> Callable[[], None]:
"""Subscribe to event."""
event_processing_data = self._get_or_create_event_processing_data(event_type)

listener = EventListener(event_processing_data, callback)
event_processing_data.subscribers.append(listener)
def unsubscribe() -> None:
event_processing_data.subscriber_callbacks.remove(callback)

event_processing_data.subscriber_callbacks.append(callback)

if event_processing_data.last_event:
# Notify subscriber directly with the last event
create_task(
self._tasks, listener.callback(event_processing_data.last_event)
)
elif len(event_processing_data.subscribers) == 1:
create_task(self._tasks, callback(event_processing_data.last_event))
elif len(event_processing_data.subscriber_callbacks) == 1:
# first subscriber therefore do refresh
self.request_refresh(event_type)

return listener
return unsubscribe

def notify(self, event: T) -> bool:
"""Notify subscriber with given event representation."""
Expand Down Expand Up @@ -126,10 +102,10 @@ def notify(self, event: T) -> bool:
return False

event_processing_data.last_event = event
if event_processing_data.subscribers:
if event_processing_data.subscriber_callbacks:
_LOGGER.debug("Notify subscribers with %s", event)
for subscriber in event_processing_data.subscribers:
create_task(self._tasks, subscriber.callback(event))
for callback in event_processing_data.subscriber_callbacks:
create_task(self._tasks, callback(event))
return True

_LOGGER.debug("No subscribers... Discharging %s", event)
Expand Down
94 changes: 52 additions & 42 deletions deebot_client/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
PositionType,
RoomsEvent,
)
from .events.event_bus import EventBus, EventListener
from .events.event_bus import EventBus
from .exceptions import MapError
from .logging_filter import get_logger
from .models import Room
Expand Down Expand Up @@ -143,38 +143,9 @@
self._map_data: Final[MapData] = MapData()
self._amount_rooms: int = 0
self._last_image: LastImage | None = None
self._listeners: list[EventListener] = []
self._unsubscribers: list[Callable[[], None]] = []
self._tasks: set[asyncio.Future[Any]] = set()

async def on_map_set(event: MapSetEvent) -> None:
if event.type == MapSetType.ROOMS:
self._amount_rooms = len(event.subsets)
for room_id, _ in self._map_data.rooms.copy().items():
if room_id not in event.subsets:
self._map_data.rooms.pop(room_id, None)
else:
for subset_id, subset in self._map_data.map_subsets.copy().items():
if subset.type == event.type and subset_id not in event.subsets:
self._map_data.map_subsets.pop(subset_id, None)

self._event_bus.subscribe(MapSetEvent, on_map_set)

async def on_map_subset(event: MapSubsetEvent) -> None:
if event.type == MapSetType.ROOMS and event.name:
room = Room(event.name, event.id, event.coordinates)
if self._map_data.rooms.get(event.id, None) != room:
self._map_data.rooms[room.id] = room

if len(self._map_data.rooms) == self._amount_rooms:
self._event_bus.notify(
RoomsEvent(list(self._map_data.rooms.values()))
)

elif self._map_data.map_subsets.get(event.id, None) != event:
self._map_data.map_subsets[event.id] = event

self._event_bus.subscribe(MapSubsetEvent, on_map_subset)

# ---------------------------- METHODS ----------------------------

def _update_trace_points(self, data: str) -> None:
Expand Down Expand Up @@ -227,23 +198,58 @@

def enable(self) -> None:
"""Enable map."""
if self._listeners:
if self._unsubscribers:
return

create_task(self._tasks, self._execute_command(GetCachedMapInfo()))

async def on_map_set(event: MapSetEvent) -> None:

Check warning on line 206 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L206

Added line #L206 was not covered by tests
if event.type == MapSetType.ROOMS:
self._amount_rooms = len(event.subsets)

Check warning on line 208 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L208

Added line #L208 was not covered by tests
for room_id, _ in self._map_data.rooms.copy().items():
if room_id not in event.subsets:
self._map_data.rooms.pop(room_id, None)

Check warning on line 211 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L211

Added line #L211 was not covered by tests
else:
for subset_id, subset in self._map_data.map_subsets.copy().items():
if subset.type == event.type and subset_id not in event.subsets:
self._map_data.map_subsets.pop(subset_id, None)

Check warning on line 215 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L215

Added line #L215 was not covered by tests

self._unsubscribers.append(self._event_bus.subscribe(MapSetEvent, on_map_set))

Check warning on line 217 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L217

Added line #L217 was not covered by tests

async def on_map_subset(event: MapSubsetEvent) -> None:

Check warning on line 219 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L219

Added line #L219 was not covered by tests
if event.type == MapSetType.ROOMS and event.name:
room = Room(event.name, event.id, event.coordinates)

Check warning on line 221 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L221

Added line #L221 was not covered by tests
if self._map_data.rooms.get(event.id, None) != room:
self._map_data.rooms[room.id] = room

Check warning on line 223 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L223

Added line #L223 was not covered by tests

if len(self._map_data.rooms) == self._amount_rooms:
self._event_bus.notify(

Check warning on line 226 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L226

Added line #L226 was not covered by tests
RoomsEvent(list(self._map_data.rooms.values()))
)

elif self._map_data.map_subsets.get(event.id, None) != event:
self._map_data.map_subsets[event.id] = event

Check warning on line 231 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L231

Added line #L231 was not covered by tests

self._unsubscribers.append(

Check warning on line 233 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L233

Added line #L233 was not covered by tests
self._event_bus.subscribe(MapSubsetEvent, on_map_subset)
)

async def on_position(event: PositionsEvent) -> None:
self._map_data.positions = event.positions

self._listeners.append(self._event_bus.subscribe(PositionsEvent, on_position))
self._unsubscribers.append(

Check warning on line 240 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L240

Added line #L240 was not covered by tests
self._event_bus.subscribe(PositionsEvent, on_position)
)

async def on_map_trace(event: MapTraceEvent) -> None:
if event.start == 0:
self._map_data.trace_values.clear()

self._update_trace_points(event.data)

self._listeners.append(self._event_bus.subscribe(MapTraceEvent, on_map_trace))
self._unsubscribers.append(

Check warning on line 250 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L250

Added line #L250 was not covered by tests
self._event_bus.subscribe(MapTraceEvent, on_map_trace)
)

async def on_major_map(event: MajorMapEvent) -> None:
tasks = []
Expand All @@ -263,23 +269,27 @@
if tasks:
await asyncio.gather(*tasks)

self._listeners.append(self._event_bus.subscribe(MajorMapEvent, on_major_map))
self._unsubscribers.append(

Check warning on line 272 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L272

Added line #L272 was not covered by tests
self._event_bus.subscribe(MajorMapEvent, on_major_map)
)

async def on_minor_map(event: MinorMapEvent) -> None:
self._map_data.map_pieces[event.index].update_points(event.value)

self._listeners.append(self._event_bus.subscribe(MinorMapEvent, on_minor_map))
self._unsubscribers.append(

Check warning on line 279 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L279

Added line #L279 was not covered by tests
self._event_bus.subscribe(MinorMapEvent, on_minor_map)
)

def disable(self) -> None:
"""Disable map."""
listeners = self._listeners
self._listeners.clear()
for listener in listeners:
listener.unsubscribe()
unsubscribers = self._unsubscribers
self._unsubscribers.clear()
for unsubscribe in unsubscribers:
unsubscribe()

Check warning on line 288 in deebot_client/map.py

View check run for this annotation

Codecov / codecov/patch

deebot_client/map.py#L288

Added line #L288 was not covered by tests

def refresh(self) -> None:
"""Manually refresh map."""
if not self._listeners:
if not self._unsubscribers:
raise MapError("Please enable the map first")

# todo make it nice pylint: disable=fixme
Expand All @@ -289,7 +299,7 @@

def get_base64_map(self, width: int | None = None) -> bytes:
"""Return map as base64 image string."""
if not self._listeners:
if not self._unsubscribers:
raise MapError("Please enable the map first")

if (
Expand Down
13 changes: 12 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import logging
from collections.abc import AsyncGenerator, Generator
from unittest.mock import Mock
from unittest.mock import AsyncMock, Mock

import aiohttp
import pytest
from asyncio_mqtt import Client

from deebot_client.api_client import ApiClient
from deebot_client.authentication import Authenticator
from deebot_client.events.event_bus import EventBus
from deebot_client.models import Configuration, Credentials, DeviceInfo
from deebot_client.mqtt_client import MqttClient, MqttConfiguration
from deebot_client.vacuum_bot import VacuumBot
Expand Down Expand Up @@ -126,3 +127,13 @@ async def vacuum_bot(
await bot.initialize(mqtt)
yield bot
await bot.teardown()


@pytest.fixture
def execute_mock() -> AsyncMock:
return AsyncMock()


@pytest.fixture
def event_bus(execute_mock: AsyncMock) -> EventBus:
return EventBus(execute_mock)
Loading