From c6d5e92e42c8a38e9880d3943cedf7f1b550cda5 Mon Sep 17 00:00:00 2001 From: Daniel Date: Tue, 30 Jul 2024 11:48:42 +0100 Subject: [PATCH] Variable to store the latest location --- location.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/location.py b/location.py index d5303ee..16ef917 100644 --- a/location.py +++ b/location.py @@ -13,3 +13,31 @@ # Initialize MQTT client client = mqtt.Client() +# Variable to store the latest location +latest_location = None + +def on_connect(client, userdata, flags, rc): + print(f"Connected to MQTT broker with result code {rc}") + client.subscribe(MQTT_TOPIC_LOCATION) + +def on_message(client, userdata, msg): + global latest_location + try: + payload = json.loads(msg.payload) + if 'lat' in payload and 'lon' in payload: + latest_location = (payload['lat'], payload['lon']) + print(f"Updated location: {latest_location}") + publish_location() + except Exception as e: + print(f"Failed to parse MQTT message: {e}") + +def publish_location(): + global coordinates + if latest_location: + location_data = { + "latitude": latest_location[0], + "longitude": latest_location[1], + "timestamp": int(time.time()) + } + client.publish(MQTT_TOPIC_UPDATE, json.dumps(location_data)) + coordinates = location_data