Delegate mqtt topic match validation to the paho mqtt client (#16403)
* Delegate mqtt match topics to the paho mqtt client * Fixing linting error with importing MQTTMatcher
This commit is contained in:
parent
8fa9992589
commit
e61ac1a4a1
2 changed files with 17 additions and 18 deletions
|
@ -13,7 +13,6 @@ import os
|
||||||
import socket
|
import socket
|
||||||
import time
|
import time
|
||||||
import ssl
|
import ssl
|
||||||
import re
|
|
||||||
import requests.certs
|
import requests.certs
|
||||||
import attr
|
import attr
|
||||||
|
|
||||||
|
@ -727,23 +726,14 @@ def _raise_on_error(result_code: int) -> None:
|
||||||
|
|
||||||
def _match_topic(subscription: str, topic: str) -> bool:
|
def _match_topic(subscription: str, topic: str) -> bool:
|
||||||
"""Test if topic matches subscription."""
|
"""Test if topic matches subscription."""
|
||||||
reg_ex_parts = [] # type: List[str]
|
from paho.mqtt.matcher import MQTTMatcher
|
||||||
suffix = ""
|
matcher = MQTTMatcher()
|
||||||
if subscription.endswith('#'):
|
matcher[subscription] = True
|
||||||
subscription = subscription[:-2]
|
try:
|
||||||
suffix = "(.*)"
|
next(matcher.iter_match(topic))
|
||||||
sub_parts = subscription.split('/')
|
return True
|
||||||
for sub_part in sub_parts:
|
except StopIteration:
|
||||||
if sub_part == "+":
|
return False
|
||||||
reg_ex_parts.append(r"([^\/]+)")
|
|
||||||
else:
|
|
||||||
reg_ex_parts.append(re.escape(sub_part))
|
|
||||||
|
|
||||||
reg_ex = "^" + (r'\/'.join(reg_ex_parts)) + suffix + "$"
|
|
||||||
|
|
||||||
reg = re.compile(reg_ex)
|
|
||||||
|
|
||||||
return reg.match(topic) is not None
|
|
||||||
|
|
||||||
|
|
||||||
class MqttAvailability(Entity):
|
class MqttAvailability(Entity):
|
||||||
|
|
|
@ -277,6 +277,15 @@ class TestMQTTCallbacks(unittest.TestCase):
|
||||||
self.hass.block_till_done()
|
self.hass.block_till_done()
|
||||||
self.assertEqual(0, len(self.calls))
|
self.assertEqual(0, len(self.calls))
|
||||||
|
|
||||||
|
def test_subscribe_topic_level_wildcard_root_topic_no_subtree_match(self):
|
||||||
|
"""Test the subscription of wildcard topics."""
|
||||||
|
mqtt.subscribe(self.hass, 'test-topic/#', self.record_calls)
|
||||||
|
|
||||||
|
fire_mqtt_message(self.hass, 'test-topic-123', 'test-payload')
|
||||||
|
|
||||||
|
self.hass.block_till_done()
|
||||||
|
self.assertEqual(0, len(self.calls))
|
||||||
|
|
||||||
def test_subscribe_topic_subtree_wildcard_subtree_topic(self):
|
def test_subscribe_topic_subtree_wildcard_subtree_topic(self):
|
||||||
"""Test the subscription of wildcard topics."""
|
"""Test the subscription of wildcard topics."""
|
||||||
mqtt.subscribe(self.hass, 'test-topic/#', self.record_calls)
|
mqtt.subscribe(self.hass, 'test-topic/#', self.record_calls)
|
||||||
|
|
Loading…
Add table
Reference in a new issue