Replace state/command methods with topic wrapper at runtime

This commit is contained in:
Edward Brown 2025-11-25 13:12:03 +00:00
parent 879bc347f8
commit 5be372be03
3 changed files with 13 additions and 5 deletions

View file

@ -41,6 +41,14 @@ class Control(Base, Generic[DeviceT]):
self.subscriptions = self.get_subscriptions()
#self.announce = self.get_announce()
for capability in self.capabilities:
for topic in capability.topics:
method_name = topic.callback_name
method = getattr(self, method_name, None)
if not method: continue
setattr(self, f'_{method_name}', method)
setattr(self, f'{method_name}', topic.wrap_back)
@property
def parent(self):
return self.device

View file

@ -76,7 +76,7 @@ class AnnounceTopicState(AnnounceTopic):
return {}
async def wrap_back(self, value):
method = getattr(self.capability.control, self.callback_name, None)
method = getattr(self.capability.control, f'_{self.callback_name}', None)
is_async = aio.is_async(method)
# test
@ -93,7 +93,7 @@ class AnnounceTopicState(AnnounceTopic):
return
value_raw = self.capability.converters.state(value)
await self.capability.control.device.client.publish(self.topic, value_raw)
await self.capability.control.device.client.publish(self.topic, value_raw, retain=True)
return value_raw
@dataclass(kw_only=True)
@ -105,7 +105,7 @@ class AnnounceTopicCommand(AnnounceTopic):
return self.capability.state
async def wrap_back(self, message):
method = getattr(self.capability.control, self.callback_name, None)
method = getattr(self.capability.control, f'_{self.callback_name}', None)
is_async = aio.is_async(method)
value = message.payload.decode('utf-8')

View file

@ -15,7 +15,7 @@ OFF = 'OFF'
BOOL_MAP = {True: ON, False: OFF}
to_bool_ha = BOOL_MAP.get
from_bool = BOOL_MAP.get
def sanitize_name(s, sep='-'):
chars = []
@ -41,7 +41,7 @@ class Converters:
class ConvertersBool(Converters):
command: Callable = to_bool
state: Callable = to_bool_ha
state: Callable = from_bool
class ConvertersString(Converters):