How do I know if receive topic comes from the same subscribe?
jeffreykira opened this issue · 2 comments
jeffreykira commented
I subscribe a topic with plus symbol (LIGHT/+/TURNON)
So I will receive these topics:
LIGHT/ID_1/TURNON
LIGHT/ID_2/TURNON
I hope to receive these topic can do the same thing.
How do I know that LIGHT/ID_1/TURNON
and LIGHT/ID_2/TURNON
are from the same subscribe?
following is my sample code:
TOPIC_LIST = []
def turn_on_tv(client, topic, message, qos, properties):
# do something
def turn_on_light(client, topic, message, qos, properties):
# do something
def init_subscribe(client):
global TOPIC_LIST
TOPIC_LIST = [
{'topic': 'TV/TURNON'., 'qos': 1, 'method': turn_on_tv},
{'topic': 'LIGHT/+/TURNON', 'qos': 1, 'method': turn_on_light},
]
for t in TOPIC_LIST:
client.subscribe(t['topic'], t['qos'])
def on_message(client, topic, payload, qos, properties):
for t in TOPIC_LIST:
if topic == t['topic']: # How do I know?
t['method'](client, topic, message, qos, properties)
break
Lenka42 commented
@jeffreykira For now there are two possibilities:
- you can match received message topic with regexp, like this:
pattern = r'LIGHT/(?P<device_id>\d+)/TURNON'
match = re.fullmatch(pattern, topic)
if match is not None:
device_id = match.group('device_id')
# do the turn on logic here
- or if you use broker supporting MQTT 5.0 version, you can use subscription identifiers for this.
TOPIC_LIST = [
{'topic': 'TV/TURNON'., 'qos': 1, 'method': turn_on_tv, 'subscription_identifier': 1},
{'topic': 'LIGHT/+/TURNON', 'qos': 1, 'method': turn_on_light, 'subscription_identifier': 2},
]
for t in TOPIC_LIST:
# pass it as kwarg to subscribe method
client.subscribe(t['topic'], t['qos'], subscription_identifier=t['subscription_identifier'])
on_message
handler will receive messgae with property subscription_identifier
, which is list:
def on_message(client, topic, payload, qos, properties):
if 2 in properties['subscription_identifier']:
# do the turnon logic here
jeffreykira commented
@Lenka42 Thank you very much for your reply, I will use the second one.