i found different solution to this in python
client.py
class Messages(threading.Thread):
def __init__(
self,
clientname,
broker="127.0.0.1",
pub_topic="msg",
sub_topic=[("msg", 0)],
):
super().__init__()
self.broker = broker
self.sub_topic = sub_topic
self.pub_topic = pub_topic
self.clientname = clientname
self.client = mqtt.Client(self.clientname)
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.on_subscibe = self.on_subscribe
self.received = {}
self.topicTemp = "" <==== define temporary topic name
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print("Server Connection Established")
else:
print("bad connection Returned code=", rc)
self.client.subscribe(self.sub_topic)
def on_subscribe(self, client, userdata, mid, granted_qos):
print("Subscription complete")
def on_message(self, client, userdata, msg):
if self.topicTemp != msg.topic: <=== compare incoming topic name
self.received[msg.topic] = { <=== create new element of received dict
"topic": msg.topic,
"payload": str(msg.payload.decode()),
}
self.topicTemp = msg.topic <== store handlede topic to compare next one
def begin(self):
print("Setting up connection")
self.client.connect(self.broker)
self.client.loop_start()
# self.client.loop_forever()
def end(self):
time.sleep(1)
print("Ending Connection")
self.client.loop_stop()
self.client.disconnect()
def send(self, msg, topic=None):
if topic is None:
topic = self.pub_topic
self.client.publish(topic, msg)
def get(self, msg, topic=None):
if topic is None:
topic = self.sub_topic[0]
self.client.subscribe(topic, msg)
# self.send(msg, topic)
def main():
remote = Messages(clientname="PC", broker="127.0.0.1")
remote.begin()
if __name__ == "__main__":
main()
function.py
from mqtt_client_test import Messages
import time
remote = Messages(
clientname="Camera",
broker="127.0.0.1",
pub_topic="pc/camera",
sub_topic=[("pc/camera", 0), ("commands/detect", 1)],
)
remote.begin()
while True:
msg = remote.received
# print(msg)
if "commands/detect" in msg:
print("command", msg["commands/detect"]["payload"])
if "pc/camera" in msg:
print("camera", msg["pc/camera"]["payload"])
time.sleep(1)
Now you can get payloads from different topics in one on_message function and can extract how you want to use somewhere else...