How do I print a single data in paho.mqtt instead of a continuous loop in Python?
I want to transfer mqtt data to telegram and report it to grafana from there. But the code below returns data in a continuous loop. I want only one data to come out, then the script to be finished. I replaced the client.loop_forever() with client.loop_start() but there was no output.
import random
import json
from paho.mqtt import client as mqtt_client
broker = '192.168.62.24'
port = 1883
topic = "tvekrani"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 100)}'
username = 'admin'
password = 'admin'
def connect_mqtt() -> mqtt_client:
def on_connect(client, userdata, flags, rc):
if rc == 0:
a=0
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
# client.username_pw_set(username, password)
client.on_connect = on_connect
client.connect(broker, port)
return client
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
#print(msg.payload.decode())
data=(msg.payload.decode())
veri = json.loads(data)
print(veri["speakers"])
client.subscribe(topic)
client.on_message = on_message
def run():
client = connect_mqtt()
subscribe(client)
client.loop_forever()
if __name__ == '__main__':
run()