Skip to content

Variable to store the latest location #50

Merged
merged 1 commit into from
Jul 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions location.py
Original file line number Diff line number Diff line change
Expand Up @@ -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