Skip to content

Commit

Permalink
Merge pull request #50 from 4005CMD2425MAYSEP/Daniels_branch
Browse files Browse the repository at this point in the history
Variable to store the latest location
  • Loading branch information
ehiosud committed Jul 30, 2024
2 parents e99a9f0 + c6d5e92 commit 830f0e7
Showing 1 changed file with 28 additions and 0 deletions.
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

0 comments on commit 830f0e7

Please sign in to comment.