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:
Rohan Kapoor 2018-09-04 01:31:45 -07:00 committed by Paulus Schoutsen
parent 8fa9992589
commit e61ac1a4a1
2 changed files with 17 additions and 18 deletions

View file

@ -13,7 +13,6 @@ import os
import socket
import time
import ssl
import re
import requests.certs
import attr
@ -727,23 +726,14 @@ def _raise_on_error(result_code: int) -> None:
def _match_topic(subscription: str, topic: str) -> bool:
"""Test if topic matches subscription."""
reg_ex_parts = [] # type: List[str]
suffix = ""
if subscription.endswith('#'):
subscription = subscription[:-2]
suffix = "(.*)"
sub_parts = subscription.split('/')
for sub_part in sub_parts:
if sub_part == "+":
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
from paho.mqtt.matcher import MQTTMatcher
matcher = MQTTMatcher()
matcher[subscription] = True
try:
next(matcher.iter_match(topic))
return True
except StopIteration:
return False
class MqttAvailability(Entity):

View file

@ -277,6 +277,15 @@ class TestMQTTCallbacks(unittest.TestCase):
self.hass.block_till_done()
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):
"""Test the subscription of wildcard topics."""
mqtt.subscribe(self.hass, 'test-topic/#', self.record_calls)