Guide for connecting PI to MQTT server

Step 1: Prepare the Raspberry Pis

On both Raspberry Pis, open a terminal and ensure the MQTT library is installed. On modern Raspberry Pi OS, using apt is the safest way to avoid virtual environment errors:

sudo apt update
sudo apt install python3-paho-mqtt

Step 2: The Final Python Script

Create a file called telemetry.py on both Pis.
Copy and paste this code:

import paho.mqtt.client as mqtt
import struct
import time
import random

# --- NETWORK CONFIGURATION ---
BROKER_IP = "CHANGE TO THE PUBLIC IP" 
PORT = 1883
USERNAME = "my_pi_user" # the user name         
PASSWORD = "CHANGE TO THE PASSWORD"       

# --- TOPIC CONFIGURATION ---
# For Pi A, leave this exactly as is.
# For Pi B, swap these two variables!
MY_TOPIC = "pi/A/data"
OTHER_TOPIC = "pi/B/data"

# Struct format: > (Big Endian), ??? (3 booleans), hhh (3 signed 16-bit ints)
PACK_FORMAT = '>???hhh'

# --- CALLBACKS ---
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print(f"✅ Connected to Windows Broker at {BROKER_IP}!")
        client.subscribe(OTHER_TOPIC)
        print(f"🎧 Listening for data on: {OTHER_TOPIC}")
    else:
        print(f"❌ Connection failed with code {rc}")

def on_message(client, userdata, msg):
    try:
        # Unpack the 6 bytes of binary back into Booleans and Ints
        received_data = struct.unpack(PACK_FORMAT, msg.payload)
        print(f"📥 Received: {received_data}")
    except Exception as e:
        print(f"⚠️ Unpack error: {e}")

# --- MAIN SETUP ---
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

# Set the authentication credentials BEFORE connecting
client.username_pw_set(USERNAME, PASSWORD)

print("Connecting...")
client.connect(BROKER_IP, PORT, 60)
client.loop_start()

try:
    while True:
        # 1. Generate dummy payload data
        b1, b2, b3 = True, False, True
        i1, i2, i3 = random.randint(-1000, 1000), 400, -3200 

        # 2. Pack the data into a tiny binary string
        payload = struct.pack(PACK_FORMAT, b1, b2, b3, i1, i2, i3)

        # 3. Publish to the broker
        client.publish(MY_TOPIC, payload)
        print("📤 Sent telemetry package...")

        # 4. Wait 1 second
        time.sleep(1)

except KeyboardInterrupt:
    print("\nDisconnecting...")
    client.loop_stop()
    client.disconnect()
    print("Done.")

Step 3: Run the Test

On Pi A:

  1. Open the script and put in your Windows static IP and your Mosquitto password.
  2. Leave the topics as they are (MY_TOPIC = "pi/A/data").
  3. Run the script: python3 telemetry.py
  4. You should see it say ✅ Connected to Windows Broker and start sending packages. It won't receive anything yet because Pi B isn't online.

On Pi B:

  1. Open the script and put in your Windows IP and password.
  2. Crucial: Swap the topics!
    MY_TOPIC = "pi/B/data"
    OTHER_TOPIC = "pi/A/data"
    
  3. Run the script: python3 telemetry.py

Step 4: Verification

If everything is working, your terminal windows should light up.