Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create MQTTMatcher once per subscription instead of each message #40345

Merged
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions homeassistant/components/mqtt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,7 @@ class Subscription:
"""Class to hold data about an active subscription."""

topic: str = attr.ib()
matcher: Any = attr.ib()
callback: MessageCallbackType = attr.ib()
qos: int = attr.ib(default=0)
encoding: str = attr.ib(default="utf-8")
Expand Down Expand Up @@ -838,7 +839,9 @@ async def async_subscribe(
if not isinstance(topic, str):
raise HomeAssistantError("Topic needs to be a string!")

subscription = Subscription(topic, msg_callback, qos, encoding)
subscription = Subscription(
topic, _matcher_for_topic(topic), msg_callback, qos, encoding
)
self.subscriptions.append(subscription)

# Only subscribe if currently connected.
Expand Down Expand Up @@ -953,7 +956,7 @@ def _mqtt_handle_message(self, msg) -> None:
timestamp = dt_util.utcnow()

for subscription in self.subscriptions:
if not _match_topic(subscription.topic, msg.topic):
if not subscription.matcher(msg.topic):
continue

payload: SubscribePayloadType = msg.payload
Expand Down Expand Up @@ -1050,18 +1053,14 @@ def _raise_on_error(result_code: int) -> None:
)


def _match_topic(subscription: str, topic: str) -> bool:
"""Test if topic matches subscription."""
def _matcher_for_topic(topic: str) -> Any:
balloob marked this conversation as resolved.
Show resolved Hide resolved
# pylint: disable=import-outside-toplevel
from paho.mqtt.matcher import MQTTMatcher

matcher = MQTTMatcher()
matcher[subscription] = True
try:
next(matcher.iter_match(topic))
return True
except StopIteration:
return False
matcher[topic] = True
balloob marked this conversation as resolved.
Show resolved Hide resolved

return lambda topic: next(matcher.iter_match(topic), False)


class MqttAttributes(Entity):
Expand Down