Dispatch the same ReceiveMessage object if the subscription topic is the same (#114769)

This commit is contained in:
J. Nick Koston 2024-04-03 09:36:57 -10:00 committed by GitHub
parent 535da483b6
commit 3d8a110908
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 15 additions and 7 deletions

View File

@ -835,6 +835,7 @@ class MQTT:
timestamp = dt_util.utcnow()
subscriptions = self._matching_subscriptions(topic)
msg_cache_by_subscription_topic: dict[str, ReceiveMessage] = {}
for subscription in subscriptions:
if msg.retain:
@ -858,17 +859,24 @@ class MQTT:
subscription.job,
)
continue
self.hass.async_run_hass_job(
subscription.job,
ReceiveMessage(
subscription_topic = subscription.topic
if subscription_topic not in msg_cache_by_subscription_topic:
# Only make one copy of the message
# per topic so we avoid storing a separate
# dataclass in memory for each subscriber
# to the same topic for retained messages
receive_msg = ReceiveMessage(
topic,
payload,
msg.qos,
msg.retain,
subscription.topic,
subscription_topic,
timestamp,
),
)
)
msg_cache_by_subscription_topic[subscription_topic] = receive_msg
else:
receive_msg = msg_cache_by_subscription_topic[subscription_topic]
self.hass.async_run_hass_job(subscription.job, receive_msg)
self._mqtt_data.state_write_requests.process_write_state_requests(msg)
def _mqtt_on_callback(

View File

@ -58,7 +58,7 @@ class PublishMessage:
retain: bool
@dataclass
@dataclass(slots=True, frozen=True)
class ReceiveMessage:
"""MQTT Message received."""