Guide Intermediate 15 min read

MQTT & Mosquitto: Pub/Sub Messaging for IoT

Learn MQTT messaging with Mosquitto broker. Install, configure, publish and subscribe to topics. Essential commands for IoT and real-time applications.

OceanSoft Solutions
mqttmosquittoiotmessagingpubsub
mosquitto@iot:~

What is MQTT?

MQTT (Message Queuing Telemetry Transport) is a lightweight publish/subscribe messaging protocol ideal for:

  • IoT devices — Low bandwidth, unreliable networks
  • Sensor networks — Many publishers, few subscribers
  • Mobile applications — Battery-constrained devices
  • Real-time systems — Low latency messaging

Key concepts:

  • Broker — Server that routes messages (e.g., Mosquitto)
  • Publisher — Sends messages to a topic
  • Subscriber — Receives messages from topics
  • Topic — Hierarchical address (e.g., home/livingroom/temperature)

Installing Mosquitto

Ubuntu/Debian

# Install broker and client tools
sudo apt update
sudo apt install mosquitto mosquitto-clients

# Start and enable service
sudo systemctl start mosquitto
sudo systemctl enable mosquitto

# Check status
sudo systemctl status mosquitto

macOS

brew install mosquitto
brew services start mosquitto

Docker

docker run -d --name mosquitto -p 1883:1883 -p 9001:9001 eclipse-mosquitto

Basic Publish & Subscribe

Subscribe to a Topic

# Subscribe to a topic
mosquitto_sub -t "sensors/temperature"

# Subscribe with verbose output
mosquitto_sub -t "sensors/temperature" -v

# Subscribe to multiple topics
mosquitto_sub -t "sensors/temperature" -t "sensors/humidity"

# Subscribe with wildcards
mosquitto_sub -t "sensors/#"         # All under sensors/
mosquitto_sub -t "home/+/temperature" # Any room temperature

Publish to a Topic

# Publish a message
mosquitto_pub -t "sensors/temperature" -m "23.5"

# Publish with debug output
mosquitto_pub -t "sensors/temperature" -m "23.5" -d

# Publish JSON payload
mosquitto_pub -t "sensors/data" -m '{"temp": 23.5, "humidity": 65}'

# Publish from a file
mosquitto_pub -t "config/update" -f config.json

Topic Wildcards

MQTT supports two wildcard characters for subscribing:

Wildcard Meaning Example
+ Single level home/+/temp matches home/kitchen/temp
# Multi-level (must be last) home/# matches all under home/
# Subscribe to all sensors
mosquitto_sub -t "sensors/#" -v

# Subscribe to temperature from any room
mosquitto_sub -t "home/+/temperature" -v

# Subscribe to all topics (use carefully!)
mosquitto_sub -t "#" -v

Authentication

Username/Password Authentication

# Create password file
sudo mosquitto_passwd -c /etc/mosquitto/passwd myuser

# Add more users
sudo mosquitto_passwd /etc/mosquitto/passwd anotheruser

Edit /etc/mosquitto/mosquitto.conf:

listener 1883
password_file /etc/mosquitto/passwd
allow_anonymous false
# Restart broker
sudo systemctl restart mosquitto

# Connect with credentials
mosquitto_sub -u myuser -P mypassword -t "sensors/#" -v
mosquitto_pub -u myuser -P mypassword -t "sensors/temp" -m "25"

Remote Connections

# Connect to remote broker
mosquitto_sub -h broker.example.com -t "sensors/#"

# Connect to specific port
mosquitto_sub -h broker.example.com -p 1884 -t "sensors/#"

# Connect to localhost explicitly
mosquitto_pub -A 127.0.0.1 -t "local/test" -m "hello"

Quality of Service (QoS)

MQTT supports three QoS levels:

QoS Guarantee Use Case
0 At most once (fire & forget) Sensor data, non-critical
1 At least once (may duplicate) Important messages
2 Exactly once Financial transactions
# Publish with QoS 1
mosquitto_pub -t "critical/alert" -m "System down" -q 1

# Subscribe with QoS 2
mosquitto_sub -t "orders/#" -q 2

Retained Messages

Retained messages are stored by the broker and sent to new subscribers immediately:

# Publish retained message
mosquitto_pub -t "config/version" -m "1.2.3" -r

# New subscribers immediately receive the last retained message
mosquitto_sub -t "config/version"

# Clear retained message (publish empty message with retain)
mosquitto_pub -t "config/version" -m "" -r

Last Will & Testament (LWT)

LWT is a message published by the broker when a client disconnects unexpectedly:

# Subscribe with LWT
mosquitto_sub -t "sensors/#" \
  --will-topic "sensors/device1/status" \
  --will-payload "offline" \
  --will-retain

# When this client disconnects abnormally,
# the broker publishes "offline" to sensors/device1/status

Bridge Configuration

Connect two MQTT brokers together. Edit /etc/mosquitto/mosquitto.conf:

# Bridge to remote broker
connection remote-bridge
address remote.broker.com:1883
topic sensors/# out 1
topic commands/# in 1
remote_username bridgeuser
remote_password bridgepass

Monitoring & System Topics

Mosquitto publishes broker statistics to $SYS topics:

# Subscribe to all system topics
mosquitto_sub -t '$SYS/#' -v

# Useful system topics:
# $SYS/broker/clients/connected - Connected client count
# $SYS/broker/messages/received - Total messages received
# $SYS/broker/uptime - Broker uptime in seconds
# $SYS/broker/load/messages/received/1min - Messages/minute

Monitor Bridge Status

# Bridge connection status (0 = disconnected, 1 = connected)
mosquitto_sub -t '$SYS/broker/connection/+/state' -v

Practical Examples

IoT Sensor Network

# Terminal 1: Subscribe to all sensor data
mosquitto_sub -t "sensors/#" -v

# Terminal 2: Simulate temperature sensor
while true; do
  TEMP=$((20 + RANDOM % 10))
  mosquitto_pub -t "sensors/room1/temperature" -m "$TEMP"
  sleep 5
done

# Terminal 3: Simulate humidity sensor
while true; do
  HUM=$((40 + RANDOM % 30))
  mosquitto_pub -t "sensors/room1/humidity" -m "$HUM"
  sleep 5
done

Home Automation

# Subscribe to all home events
mosquitto_sub -t "home/#" -v

# Publish light state
mosquitto_pub -t "home/livingroom/light" -m '{"state":"on","brightness":80}' -r

# Publish thermostat command
mosquitto_pub -t "home/hvac/setpoint" -m '{"temperature":22,"mode":"heat"}'

# Publish motion detection
mosquitto_pub -t "home/garage/motion" -m '{"detected":true,"timestamp":"2025-02-14T10:30:00Z"}'

Troubleshooting

# Check broker logs
sudo journalctl -u mosquitto -f

# Test local connection
mosquitto_pub -h localhost -t "test" -m "hello" -d

# Verbose debug output
mosquitto_sub -t "#" -v -d
Issue Solution
Connection refused Check if broker is running, firewall allows port 1883
Not authorized Check username/password, allow_anonymous setting
No messages received Verify topic names match exactly (case-sensitive)
Message not retained Use -r flag when publishing

Resources

Building an IoT solution? Contact us for development services.