import paho.mqtt.client as mqtt
import time
import json
import random
# --- Configuration ---
MQTT_BROKER = "broker.hivemq.com" # Using a free public broker
MQTT_PORT = 1883
MQTT_TOPIC = "vehicle/tracker/BUS-01" # The topic to publish data to
SPEED_THRESHOLD = 80 # Speed limit in km/h
# --- Simulation Initial State ---
# Starting coordinates (e.g., near a city)
current_lat = 40.7128 # New York City Latitude
current_lon = -74.0060 # New York City Longitude
def connect_mqtt():
"""Connects to the MQTT broker."""
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id="vehicle_simulator_01")
client.connect(MQTT_BROKER, MQTT_PORT, 60)
client.loop_start() # Start the loop in a background thread
return client
def simulate_data():
"""Simulates GPS movement and speed."""
global current_lat, current_lon
# 1. Simulate movement by adding a small random "jitter"
# This makes the vehicle "wander" around the map
current_lat += random.uniform(-0.0005, 0.0005)
current_lon += random.uniform(-0.0005, 0.0005)
# 2. Simulate speed
# Mostly normal speed, with occasional bursts
if random.randint(0, 10) > 8:
speed = random.uniform(85, 100) # Overspeeding burst
else:
speed = random.uniform(50, 75) # Normal speed
# 3. Check for speed alert
alert = "none"
if speed > SPEED_THRESHOLD:
alert = f"OVERSPEEDING! Speed: {speed:.2f} km/h"
# 4. Create data payload
payload = {
"vehicle_id": "BUS-01",
"latitude": current_lat,
"longitude": current_lon,
"speed_kmh": round(speed, 2),
"alert_message": alert
}
return json.dumps(payload)
def publish_data(client):
"""Publishes simulated data every 3 seconds."""
while True:
try:
data = simulate_data()
result = client.publish(MQTT_TOPIC, data)
# Check if publish was successful
if result[0] == 0:
print(f"Published to {MQTT_TOPIC}: {data}")
else:
print(f"Failed to publish to {MQTT_TOPIC}")
time.sleep(3) # Wait for 3 seconds before sending next update
except KeyboardInterrupt:
print("Simulation stopped.")
client.loop_stop()
client.disconnect()
break
except Exception as e:
print(f"An error occurred: {e}")
client.loop_stop()
client.disconnect()
break
if __name__ == "__main__":
client = connect_mqtt()
publish_data(client)