Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1584

Python • MQTT JSON use data outside function

$
0
0
How do I use the time and distance data outside this function?
The print stats line never shows, guess because the loop_forever comes before?


Output
[Received] Time: 16:58:08, Distance: 0mm
16:58:08 0


Code:

import paho.mqtt.client as mqttimport jsonimport threadingimport timefrom time import sleep, strftime, time# Initialise global variables:    time = '23:59:59?'distance = 'mm?'def on_message(client, userdata, msg):    def handle_message():        global time        global distance                data = json.loads(msg.payload.decode())        print(f"[Received] Time: {data['time']}, Distance: {data['Distance']}mm")        distance = data['Distance']        time = data['time']        print(time, distance)    threading.Thread(target=handle_message).start()client = mqtt.Client()client.on_message = on_messageclient.connect("localhost", 1883, 60)client.subscribe("garage/distance")client.loop_forever()print("Stats:", time, distance)

Statistics: Posted by richard238 — Sun Jan 11, 2026 5:01 pm



Viewing all articles
Browse latest Browse all 1584

Trending Articles