Introduction
Weather apps, smart farming systems, or IoT-based environmental monitors often depend on a steady stream of sensor data. But what if you don’t have actual sensors yet? No problem. We’ll simulate a weather station that periodically reports temperature, humidity, and pressure via MQTT.
Whether you’re prototyping a dashboard, testing a backend, or learning MQTT for the first time, this guide will help you get your feet wet without needing to touch a single sensor. Let’s roll! 🚀
Prerequisites
Check installation:
- Linux/macOS:
python3 --version
- Windows:
python --version
Or download from python.org.
pip install paho-mqtt==1.6.1
Why 1.6.1? Newer versions have callback API changes that may cause unexpected issues.
Install a local broker for testing. For example:
Linux (Debian/Ubuntu)
sudo apt update
sudo apt install mosquitto mosquitto-clients
macOS (with Homebrew)
brew install mosquitto
brew services start mosquitto
Windows
Download from Mosquitto Downloads and run either as a service or via terminal:
"C:\Program Files\mosquitto\mosquitto.exe"
Simulate a Weather Station
Let’s simulate a weather station that publishes data every 5 seconds to an MQTT topic
weather/station1
.
Code: weather_simulator.py
import time
import random
import paho.mqtt.client as mqtt
BROKER = 'localhost'
PORT = 1883
TOPIC = 'weather/station1'
# Create client
client = mqtt.Client()
client.connect(BROKER, PORT, 60)
print("Weather station simulator started. Publishing to MQTT topic...")
while True:
temperature = round(random.uniform(20.0, 35.0), 2)
humidity = round(random.uniform(30.0, 70.0), 2)
pressure = round(random.uniform(990.0, 1025.0), 2)
message = {
"temperature": temperature,
"humidity": humidity,
"pressure": pressure
}
client.publish(TOPIC, str(message))
print(f"Published: {message}")
time.sleep(5)
Here, we simulate temperature, humidity, and pressure readings, then publish them as a
JSON-like string. Replace localhost
with your broker IP if needed.
View Your Data
To verify data is arriving using the Mosquitto CLI:
mosquitto_sub -h localhost -t weather/#
You should see:
{"temperature": 29.53, "humidity": 55.2, "pressure": 1011.34}
Wrap-Up
That’s it! You now have a virtual weather station chirping out sensor readings like a seasoned meteorologist. This simulation is perfect for testing dashboards, logging data, or learning MQTT without hardware.
Next up: subscribe to this topic and store data in a CSV or database. Happy IoT hacking! ☀️☔️