← Back to Blog
otheriotmqttcommunication

MQTT Protocol: Robot-to-Cloud Communication

MQTT protocol for robots and IoT — setting up brokers, QoS levels, topic design and sending telemetry from robots to cloud.

Nguyen Anh Tuan22 tháng 3, 20264 min read
MQTT Protocol: Robot-to-Cloud Communication

What is MQTT?

MQTT (Message Queuing Telemetry Transport) is a lightweight protocol designed for resource-constrained devices and unreliable networks. With only a 2-byte header, MQTT is the top choice for communication between robots, sensors, and cloud platforms.

Compared to HTTP REST API (hundreds of bytes header per request), MQTT saves significant bandwidth — critical when robots connect via 4G or industrial WiFi. It's the standard protocol when deploying IoT applications with Docker.

Pub/Sub Architecture

MQTT uses a Publish/Subscribe model with a central broker:

Robot A ──publish──→ ┌──────────┐ ──subscribe──→ Dashboard
Robot B ──publish──→ │  MQTT    │ ──subscribe──→ Cloud DB
Robot C ──publish──→ │  Broker  │ ──subscribe──→ Alert System
Dashboard ─publish─→ └──────────┘ ──subscribe──→ Robot A (commands)

Advantage: robots don't need to know who's listening; the broker handles message distribution. Adding new subscribers doesn't affect publishers.

IoT network connecting devices and systems

Installing Mosquitto Broker

# Install Mosquitto on Ubuntu
sudo apt install -y mosquitto mosquitto-clients

# Configure authentication
sudo nano /etc/mosquitto/conf.d/default.conf
# /etc/mosquitto/conf.d/default.conf
listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwd

# TLS for production
listener 8883
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
cafile /etc/mosquitto/certs/ca.crt
# Create user/password
sudo mosquitto_passwd -c /etc/mosquitto/passwd robot_user
sudo systemctl restart mosquitto

QoS Levels — Choose Wisely

QoS Guarantee Use Case
0 — At most once Message may be lost High-frequency sensor data (temperature every second)
1 — At least once Sent at least once, may duplicate Important telemetry (battery level, error logs)
2 — Exactly once Exactly once, slowest Control commands (start/stop, emergency stop)

Rule of thumb: Use QoS 0 for high-frequency data streams, QoS 1 for telemetry, QoS 2 for commands.

Topic Design for Robot Fleet

Clean topic structure is key to scalable systems:

fleet/{fleet_id}/robot/{robot_id}/telemetry/battery
fleet/{fleet_id}/robot/{robot_id}/telemetry/position
fleet/{fleet_id}/robot/{robot_id}/telemetry/status
fleet/{fleet_id}/robot/{robot_id}/command/velocity
fleet/{fleet_id}/robot/{robot_id}/command/mission
fleet/{fleet_id}/robot/{robot_id}/alert/collision
fleet/{fleet_id}/robot/+/telemetry/#    ← wildcard subscribe

Python Code for Robot

import paho.mqtt.client as mqtt
import json
import time

class RobotMQTTClient:
    def __init__(self, robot_id: str, broker: str, port: int = 1883):
        self.robot_id = robot_id
        self.client = mqtt.Client(client_id=f"robot-{robot_id}")
        self.client.username_pw_set("robot_user", "secure_password")
        self.client.on_connect = self._on_connect
        self.client.on_message = self._on_message
        self.client.will_set(
            f"fleet/1/robot/{robot_id}/status",
            payload=json.dumps({"status": "offline"}),
            qos=1, retain=True
        )
        self.client.connect(broker, port)

    def _on_connect(self, client, userdata, flags, rc):
        # Subscribe to commands
        client.subscribe(f"fleet/1/robot/{self.robot_id}/command/#", qos=2)
        # Announce online
        self.publish_status("online")

    def _on_message(self, client, userdata, msg):
        payload = json.loads(msg.payload)
        if "velocity" in msg.topic:
            self.handle_velocity(payload)
        elif "mission" in msg.topic:
            self.handle_mission(payload)

    def publish_telemetry(self, battery: float, x: float, y: float):
        payload = json.dumps({
            "battery": battery, "position": {"x": x, "y": y},
            "timestamp": time.time()
        })
        self.client.publish(
            f"fleet/1/robot/{self.robot_id}/telemetry/position",
            payload, qos=0
        )

    def publish_status(self, status: str):
        self.client.publish(
            f"fleet/1/robot/{self.robot_id}/status",
            json.dumps({"status": status}), qos=1, retain=True
        )

Last Will and Testament

MQTT supports Last Will — a message automatically sent when a client loses connection unexpectedly. This is how to detect robot offline without complex heartbeat logic (already configured above with will_set).

Retained Messages

Use retain=True for status messages. When a new dashboard connects, it immediately receives the last state of each robot without waiting for new messages.

Server and network infrastructure for MQTT systems

Production Security

  1. Always use TLS (port 8883) for internet connections
  2. Per-robot certificates: Each robot has its own client certificate
  3. ACL (Access Control List): Robots can only publish to their own topics
  4. Bridge broker: Edge broker in factory, bridges to cloud broker

MQTT is the backbone of modern IoT and robot fleet systems. With proper topic design and correct QoS settings, you can build reliable communication for hundreds of robots. Combined with Kubernetes and K3s for robot fleets, MQTT creates complete infrastructure for fleet management at scale.

Related Articles

Related Posts

Triển khai ứng dụng IoT với Docker và Docker Compose
devopsdockeriot

Triển khai ứng dụng IoT với Docker và Docker Compose

Hướng dẫn triển khai ứng dụng IoT với Docker và Docker Compose trên edge devices — đóng gói, quản lý nhất quán và dễ bảo trì.

15/7/20254 min read