Skip to content

Commit 61d9ca8

Browse files
committed
feat: use cache for properties and methods
We are using some calculations in methods and properties. To avoid recalculations cache will be used.
1 parent 49b46ce commit 61d9ca8

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

custom_components/sleep_as_android/__init__.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Sleep As Android integration"""
22

33
import logging
4+
from functools import cached_property, cache
45
from typing import Dict, Callable
56

67
from homeassistant.config_entries import ConfigEntry
@@ -47,7 +48,7 @@ def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, registry: er)
4748
self.hass.loop.create_task(self.hass.config_entries.async_forward_entry_setup(self._config_entry, 'sensor'))
4849
# ToDo prepare topic_template and other variables that should be defined one time.
4950

50-
@property
51+
@cached_property
5152
def device_position_in_topic(self) -> int:
5253
""" Position of DEVICE_MACRO in configured MQTT topic """
5354
result: int = 0
@@ -79,6 +80,7 @@ def device_name_from_topic_and_position(topic: str, position: int) -> str:
7980

8081
return s[position]
8182

83+
@cache
8284
def device_name_from_topic(self, topic: str) -> str:
8385
"""Get device name from topic
8486
@@ -87,7 +89,7 @@ def device_name_from_topic(self, topic: str) -> str:
8789
"""
8890
return self.device_name_from_topic_and_position(topic, self.device_position_in_topic)
8991

90-
@property
92+
@cached_property
9193
def topic_template(self) -> str:
9294
"""
9395
Converts topic with {device} to MQTT topic for subscribing
@@ -101,6 +103,7 @@ def topic_template(self) -> str:
101103
pass
102104
return '/'.join(splitted)
103105

106+
@cache
104107
def get_from_config(self, name: str) -> str:
105108
try:
106109
data = self._config_entry.options[name]
@@ -114,7 +117,7 @@ def name(self) -> str:
114117
"""Name of the integration in Home Assistant."""
115118
return self._name
116119

117-
@property
120+
@cached_property
118121
def configured_topic(self) -> str:
119122
"""MQTT topic from integration configuration."""
120123
_topic = None
@@ -127,6 +130,7 @@ def configured_topic(self) -> str:
127130

128131
return _topic
129132

133+
@cache
130134
def create_entity_id(self, device_name: str) -> str:
131135
"""
132136
Generates entity_id based on instance name and device name.
@@ -138,6 +142,7 @@ def create_entity_id(self, device_name: str) -> str:
138142
_LOGGER.debug(f"create_entity_id: my name is {self.name}, device name is {device_name}")
139143
return self.name + "_" + device_name
140144

145+
@cache
141146
def device_name_from_entity_id(self, entity_id: str) -> str:
142147
"""
143148
Extract device name from entity_id

0 commit comments

Comments
 (0)