Skip to content

Commit

Permalink
Clean up code.
Browse files Browse the repository at this point in the history
- Remove more useless variables.
- Remove LRU cache on split byte function in schedules.
  • Loading branch information
denpamusic committed Oct 14, 2023
1 parent dea162d commit 490e6e4
Show file tree
Hide file tree
Showing 8 changed files with 22 additions and 36 deletions.
3 changes: 1 addition & 2 deletions pyplumio/helpers/data_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ class DataType(ABC):

def __init__(self, data: bytes | None = None, size: int | None = None):
"""Initialize a new data type."""
if size is None:
size = self.size
size = self.size if size is None else size

if data is not None:
self._data = data[0:size] if size > 0 else data
Expand Down
5 changes: 2 additions & 3 deletions pyplumio/helpers/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,9 @@ def factory(class_path: str, **kwargs):
"""Return class instance from the class path."""
try:
module_name, class_name = class_path.rsplit(".", 1)
cls = getattr(
return getattr(
importlib.import_module("." + module_name, "pyplumio"), class_name
)
return cls(**kwargs)
)(**kwargs)
except Exception:
_LOGGER.error("Failed to load module (%s)", class_path)
raise
6 changes: 3 additions & 3 deletions pyplumio/helpers/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,16 @@ def append(self, item) -> None:

def set_state(
self,
state: Literal["off", "on", "day", "night"],
state: Literal["on", "off", "day", "night"],
start: str = START_OF_DAY,
end: str = END_OF_DAY,
) -> None:
"""Set an interval state.
Can be on of the following:
'off', 'on', 'day' or 'night'.
'on', 'off', 'day' or 'night'.
"""
if state not in [*STATES_ON, *STATES_OFF]:
if state not in (STATES_ON + STATES_OFF):
raise ValueError(f'state "{state}" is not allowed')

index, stop_index = _parse_interval(start, end)
Expand Down
5 changes: 2 additions & 3 deletions pyplumio/helpers/uid.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@ def _encode_base5(data: bytes) -> str:
"""Encode bytes to a base5 encoded string."""
key_string = "0123456789ABCDEFGHIJKLMNZPQRSTUV"
number = int.from_bytes(data, "little")
output: str = ""
mask = (1 << 5) - 1
output = ""
while number:
output = key_string[number & mask] + output
output = key_string[number & 0b00011111] + output
number >>= 5

return output
Expand Down
8 changes: 4 additions & 4 deletions pyplumio/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,13 @@ async def frame_producer(
while self.connected.is_set():
try:
if write_queue.qsize() > 0:
request = await write_queue.get()
await self.writer.write(request)
await self.writer.write(await write_queue.get())
write_queue.task_done()

if (response := await self.reader.read()) is not None:
device = self.setup_device_entry(response.sender)
read_queue.put_nowait((device, response))
read_queue.put_nowait(
(self.setup_device_entry(response.sender), response)
)

except FrameDataError as e:
_LOGGER.warning("Incorrect payload: %s", e)
Expand Down
4 changes: 1 addition & 3 deletions pyplumio/structures/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@

def ensure_device_data(data: EventDataType | None, *args) -> EventDataType:
"""Create or merge multiple device datasets."""
if data is None:
data = {}

data = data if data is not None else {}
for new_data in args:
data |= new_data

Expand Down
3 changes: 1 addition & 2 deletions pyplumio/structures/regulator_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ def decode(
)

if schema:
regulator_data = data.setdefault(ATTR_REGDATA, RegulatorData())
regulator_data.load(
data.setdefault(ATTR_REGDATA, RegulatorData()).load(
{
param_id: self._unpack_regulator_data(message, data_type)
for param_id, data_type in schema
Expand Down
24 changes: 8 additions & 16 deletions pyplumio/structures/schedules.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from collections.abc import Sequence
from dataclasses import dataclass
from functools import lru_cache
from itertools import chain
from typing import TYPE_CHECKING, Final

Expand Down Expand Up @@ -125,14 +124,9 @@ def collect_schedule_data(name: str, device: Device) -> EventDataType:
}


@lru_cache(maxsize=16)
def _split_byte(byte: int) -> list[bool]:
"""Split single byte into an eight bits."""
bits = []
for bit in reversed(range(8)):
bits.append(bool(byte & (1 << bit)))

return bits
return [bool(byte & (1 << bit)) for bit in reversed(range(8))]


def _join_byte(bits: Sequence[int | bool]) -> int:
Expand Down Expand Up @@ -168,8 +162,7 @@ class SchedulesStructure(Structure):

def encode(self, data: EventDataType) -> bytearray:
"""Encode data to the bytearray message."""
message = bytearray()
message.append(1)
message = bytearray([1])
try:
message.append(SCHEDULES.index(data[ATTR_TYPE]))
message.append(int(data[ATTR_SWITCH]))
Expand All @@ -178,13 +171,12 @@ def encode(self, data: EventDataType) -> bytearray:
except (KeyError, ValueError) as e:
raise FrameDataError from e

schedule_bytes = []
for day in list(schedule):
schedule_bytes += [
_join_byte(day[i : i + 8]) for i in range(0, len(day), 8)
]

message += bytearray(schedule_bytes)
message += bytearray(
chain.from_iterable(
[_join_byte(day[i : i + 8]) for i in range(0, len(day), 8)]
for day in list(schedule)
)
)

return message

Expand Down

0 comments on commit 490e6e4

Please sign in to comment.