import serial import pynmea2 import paho.mqtt.client as mqtt # Configuration GPS_PORT = '/dev/ttyS0' # change this if your GPS device is on a different port MQTT_BROKER = '65.108.199.212' MQTT_PORT = 1883 TOPIC = 'iiot/coordinates' def on_connect(client, userdata, flags, rc): """Callback for when the client connects to the broker.""" print(f"Connected with result code {rc}") client.subscribe(TOPIC) def on_message(client, userdata, msg): """Callback for when a message is received from the broker.""" print(f"Received message: {msg.payload.decode('utf-8')}") # Create MQTT client client = mqtt.Client() # Connect to MQTT broker client.on_connect = on_connect client.on_message = on_message try: client.connect(MQTT_BROKER, MQTT_PORT) except Exception as e: print(f"Error connecting to MQTT broker: {e}") exit() # Open GPS device serial port try: gps_dev = serial.Serial(GPS_PORT, 9600, timeout=1) # change baudrate and timeout if needed except serial.SerialException as e: print(f"Error opening GPS device serial port: {e}") exit() while True: try: line = gps_dev.readline().decode('utf-8') if line.startswith('$GPGGA'): msg = pynmea2.parse(line) latitude = msg.latitude longitude = msg.longitude print(f"Latitude: {latitude}, Longitude: {longitude}") client.publish(TOPIC, f"{latitude},{longitude}") except Exception as e: print(f"Error parsing GPS data or publishing to MQTT broker: {e}")