Intermediate
• ~18 min read
Sending Data to MudPi
Send data to MudPi using MQTT from the command line, Python, or microcontrollers.
Overview
MQTT is a lightweight messaging protocol ideal for IoT devices. MudPi can receive sensor data and commands via MQTT, allowing you to integrate remote sensors, ESP32 boards, and other devices into your garden system.
Installing the MQTT Broker
Install Mosquitto, a popular MQTT broker, on your Raspberry Pi:
Shell
sudo apt update
sudo apt install -y mosquitto mosquitto-clients
sudo systemctl enable mosquitto
sudo systemctl start mosquitto
Note
Mosquitto runs on port 1883 by default. For production use, configure authentication and TLS encryption.
Command Line Tools
Mosquitto includes CLI tools for publishing and subscribing to MQTT topics.
Publishing Messages
Shell
# Publish a sensor reading
mosquitto_pub -h localhost -t "mudpi/sensor/outdoor_temp" -m '{"value": 72.5}'
# Publish with a specific QoS level
mosquitto_pub -h localhost -t "mudpi/sensor/moisture" -m '{"value": 45}' -q 1
Subscribing to Topics
Shell
# Subscribe to all MudPi sensor topics
mosquitto_sub -h localhost -t "mudpi/sensor/#"
# Subscribe to a specific topic
mosquitto_sub -h localhost -t "mudpi/sensor/outdoor_temp"
Python with paho-mqtt
Use the paho-mqtt library to publish sensor data from Python scripts:
mqtt_publish.py
import paho.mqtt.client as mqtt
import json
import time
client = mqtt.Client()
client.connect('localhost', 1883, 60)
while True:
data = {
'value': 23.5,
'unit': 'celsius',
'timestamp': time.time()
}
client.publish('mudpi/sensor/remote_temp', json.dumps(data))
print(f'Published: {data}')
time.sleep(30)
Tip
Install paho-mqtt with
pip install paho-mqtt. You can also use it to subscribe to MudPi events and build custom dashboards or alert systems.ESP32 / Arduino
Use the PubSubClient library to send data from an ESP32 or Arduino with WiFi to your MudPi MQTT broker:
Arduino (C++)
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
const char* mqtt_server = "192.168.1.100";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32_Garden_Node")) {
client.subscribe("mudpi/command/#");
} else {
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
int moisture = analogRead(34);
char payload[50];
snprintf(payload, 50, "{\"value\": %d}", moisture);
client.publish("mudpi/sensor/esp32_moisture", payload);
delay(30000);
}
Click to expand code…
WiFi Credentials
Never commit WiFi credentials or MQTT passwords to version control. Use environment variables or a separate configuration file that's excluded from your repository.