Skip to content

Commit

Permalink
Improve device entry handling.
Browse files Browse the repository at this point in the history
- Add small LRU cache for device handler and name getter, since it's called on every received frame.
- Separate entry creating routine into it's own function.
  • Loading branch information
denpamusic committed Oct 21, 2023
1 parent 0c41842 commit 88d4859
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
4 changes: 3 additions & 1 deletion pyplumio/devices/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

import asyncio
from functools import lru_cache
import logging
from typing import ClassVar

Expand Down Expand Up @@ -43,10 +44,11 @@ def get_device_handler(device_type: int) -> str:
raise UnknownDeviceError(f"Unknown device ({device_type})")


@lru_cache(maxsize=5)
def get_device_handler_and_name(device_type: int) -> tuple[str, str]:
"""Get device handler full path and lowercased class name."""
handler = get_device_handler(device_type)
_, class_name = handler.rsplit(".", 1)
class_name = handler.rsplit(".", 1)[1]
return handler, class_name.lower()


Expand Down
19 changes: 11 additions & 8 deletions pyplumio/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,18 +143,21 @@ async def shutdown(self):
def setup_device_entry(self, device_type: DeviceType) -> Addressable:
"""Setup the device entry."""
handler, name = get_device_handler_and_name(device_type)
write_queue: asyncio.Queue = self.queues[1]

if name not in self.data:
device: Addressable = factory(
handler, queue=write_queue, network=self._network
)
device.dispatch_nowait(ATTR_CONNECTED, True)
self.create_task(device.async_setup())
self.data[name] = device
self.set_event(name)
self._create_device_entry(name, handler)

return self.data[name]

def _create_device_entry(self, name: str, handler: str) -> None:
"""Create the device entry."""
write_queue = self.queues[1]
device: Addressable = factory(handler, queue=write_queue, network=self._network)
device.dispatch_nowait(ATTR_CONNECTED, True)
self.create_task(device.async_setup())
self.data[name] = device
self.set_event(name)

async def _remove_writer(self):
"""Attempt to gracefully remove the frame writer."""
if self.writer:
Expand Down

0 comments on commit 88d4859

Please sign in to comment.