How to Establish MQTT Communication in ROS

1. Review:

Overview of ROS Communication Mechanism & Similarities and Differences with MQTT Communication

Overview of ROS Communication Mechanism

The main communication mechanisms in ROS are as follows:

1. Topics

○ Publish/Subscribe Model: In this communication method, nodes can publish messages to a topic or subscribe to a topic to receive messages. This method is anonymous; the publisher and subscriber do not need to know each other’s existence.

○ Messages: The data structure sent on a topic, defined as a combination of simple data types (such as integers, floats, strings, etc.), can also be more complex nested structures.

2. Services

○ Request/Response Model: A service is a synchronous communication method where one node can send a request to another node and wait for a response. A service defines the message types for the request and response.

○ Service Client and Service Server: Nodes can act as service servers to provide services or as service clients to call services.

3. Actions

○ Goal/Result Model: Used to handle tasks that may take a long time to complete. The client sends a goal to the action server and can choose to receive feedback, cancel the goal, or wait for the final result.

○ Action Client and Action Server: The action client can request the action server to perform a task and obtain feedback or results as needed.

4. Parameter Server

○ Parameter Storage: Nodes can store and retrieve global parameters. This server is used to store configuration parameters accessible by any node.

So how are these communication methods implemented?

1. Topics

○ Topic communication is implemented based on the publish/subscribe model. When a node publishes a message to a topic, the ROS middleware passes this message to all nodes subscribed to that topic.

○ Publisher: A node publishes messages to a specific topic through a publisher object.

○ Subscriber: A node receives messages from a specific topic through a subscriber object.

○ Master: The ROS master provides name resolution services, allowing publishers and subscribers to find each other.

○ roscore: The first thing that runs when ROS starts is roscore, which starts a Master, a parameter server, and a rosout logging node.

The underlying implementation communicates via TCP/IP (default) or UDP (through the UDP ROS packet protocol, UDPROS). When a node registers itself with the ROS Master as a publisher or subscriber for a topic, the Master helps the publisher and subscriber discover each other and establish a direct communication link.

How to Establish MQTT Communication in ROS

1. Services

○ Services are implemented based on the request/response model. One node acts as a server providing services, while another node acts as a client that can call this service and wait for a response.

○ Service Server: A node providing specific services, registered with the ROS master, waiting for service requests.

○ Service Client: A node that needs services, which queries the address of the ROS master server and sends a service request directly to the server, waiting for a response.

Service communication is typically also conducted via TCP/IP, ensuring communication reliability since service calls usually require a definitive response.

1. Actions

○ Action communication is a more complex communication mechanism used to handle tasks that may take a long time to execute. It adds the possibility of intermediate feedback to service communication.

○ Action Server: Executes long-running tasks and provides intermediate feedback and final results.

○ Action Client: Sends task requests to the action server, with the option to receive feedback, cancel the task, or wait for results.

Action communication internally actually uses multiple topics to implement its communication model, including topics for sending goals, receiving feedback, and results.

1. Parameter Server

○ The parameter server is a centralized service in ROS for storing parameter values, allowing nodes to read and write these parameters.

○ Parameter Server: Runs as a service storing global parameters, which can be started alongside roscore.

○ Nodes: Each node can obtain and set parameter values in the parameter server using the API provided by ROS.

Operations on the parameter server are typically implemented via XML-RPC, a simple remote procedure call protocol running over HTTP.

It can be seen that most communication methods rely on TCP communication. So how is TCP communication implemented in ROS?

TCP communication in ROS relies on the TCPROS protocol. TCPROS is the main protocol used for communication between nodes in ROS.

TCPROS:

When ROS nodes need to interact through topic communication or service communication, TCPROS is used as the default transport protocol. Here are the basic steps of how TCPROS works:

• Node Registration: When a node starts and creates a publisher or subscriber, it registers itself with the ROS Master, declaring the topic name and message type it will publish or subscribe to.

• Connection Establishment: The subscriber node requests the ROS Master for information about all nodes publishing to a specific topic. Using this information, the subscriber node establishes a TCP connection directly with the publisher node.

• Message Transmission: Once the TCP connection is established, the publisher node can start streaming messages to the subscriber node. Each message is guaranteed to arrive at the subscriber node in order and intact.

• Service Call: In service communication, the service client node establishes a TCP connection directly with the service server node, sending a service request through this connection and waiting for the server to process and return a response.

Characteristics of TCPROS

• Reliability: Since TCPROS is based on TCP, it guarantees reliable message delivery. If packets are lost or corrupted during transmission, the TCP protocol automatically retransmits these packets.

• Connection-Oriented: TCPROS requires a persistent connection to be established between the communicating nodes. This connection remains active until the publication or subscription of the topic ends or the service call is completed.

• Flow Control and Congestion Control: TCPROS inherits TCP’s flow control capabilities, dynamically adjusting the data transmission rate based on network conditions to avoid congestion.

• Message Serialization: In ROS, messages must be serialized before being sent via TCPROS. The serialized message is a byte stream that includes the message’s length and the message itself, ensuring the receiver can correctly deserialize and parse the message.

Similarities and Differences between ROS Communication and MQTT Communication:

Similarities

• Publish/Subscribe Model: Both ROS and MQTT use a publish/subscribe (pub/sub) message communication model. In this model, the publisher sends messages while the subscriber receives messages, and the publisher and subscriber do not need to know each other.

• Message Passing: Both achieve communication by sending and receiving messages rather than using the traditional client-server model.

• Decoupling: In the communication of both ROS and MQTT, the components are decoupled. The sender and receiver do not need a direct network connection; the publisher does not need to know who the subscriber is, and vice versa.

Differences

• Design Purpose:

ROS: Designed specifically for robotic applications, providing a complete set of tools and libraries to help developers build complex robotic applications.

MQTT: A lightweight messaging protocol designed for communication between various devices in IoT applications, especially in environments with limited or unreliable network bandwidth.

• Protocol Layer Level:

ROS: Operates at the application layer, using TCP (default) or UDP for inter-node communication, providing a range of tools and libraries to assist development.

MQTT: An application layer protocol based on TCP/IP, typically running on lower bandwidth, high latency, or unreliable networks.

• Network Mode:

ROS: Mainly used for internal communication within a local area network (LAN), typically for communication within a single robotic system or between robots.

MQTT: Designed for wide area networks (WAN), capable of communicating over the Internet, suitable for remote monitoring and control.

Reliability:

ROS: Relies on TCPROS, providing reliable message transmission. However, it does not natively support message persistence or guarantee message delivery.

MQTT: Provides different levels of Quality of Service (QoS) guarantees. For example, QoS1 guarantees at least once message delivery, while QoS2 guarantees that messages are delivered exactly once.

• Middleware:

ROS: Uses the ROS Master as middleware for node discovery, but communication between each node is direct.

MQTT: Uses a central broker to handle all message delivery. All communication goes through this central broker.

Advantages of Establishing MQTT Communication in ROS and Application Scenarios:

• Cross-Network Communication: MQTT is designed for communication across network boundaries, meaning that through MQTT, ROS systems can easily communicate with other systems or devices on the Internet. This is very useful for application scenarios requiring remote monitoring or control of robots.

• Moreover, in practical applications, combining MQTT with ROS can ensure message delivery reliability while extending ROS’s communication capabilities to the Internet level, achieving broader device interconnectivity and data exchange. This combination is particularly suitable for robotic applications requiring remote operation, cloud service integration, or large-scale device management.

2. ROS MQTT Communication Node

Step 1: Create a Python file

How to Establish MQTT Communication in ROS

Write the following code in the file:

#!/usr/bin/env python
import rospy
import paho.mqtt.client as mqtt
from std_msgs.msg import String
# MQTT settings
MQTT_BROKER_ADDRESS = "broker.hivemq.com"  # Replace with your MQTT server address
MQTT_BROKER_PORT = 1883  # Replace with your MQTT server port
MQTT_TOPIC_SUBSCRIBE = "mqtt_topic_subscribe"  # The MQTT topic you want to subscribe to
MQTT_TOPIC_PUBLISH = "mqtt_topic_publish"  # The MQTT topic you want to publish to
# ROS settings
ROS_TOPIC_SUBSCRIBE = "ros_topic_subscribe"  # The ROS topic you want to subscribe to
ROS_TOPIC_PUBLISH = "ros_topic_publish"  # The ROS topic you want to publish to
# MQTT client callback function
def on_connect(client, userdata, flags, rc):    rospy.loginfo("Connected to MQTT Broker with result code " + str(rc))    client.subscribe(MQTT_TOPIC_SUBSCRIBE)

def on_message(client, userdata, msg):    rospy.loginfo("MQTT Message received: " + msg.topic + " " + str(msg.payload))    # Publish the received MQTT message to ROS    ros_publisher.publish(str(msg.payload))
# ROS subscriber callback function
def ros_subscriber_callback(data):    rospy.loginfo("ROS Message received: " + data.data)    # Publish the received ROS message to MQTT    mqtt_client.publish(MQTT_TOPIC_PUBLISH, data.data)
# Initialize ROS node
rospy.init_node('mqtt_bridge_node', anonymous=True)
# Initialize ROS publisher and subscriber
ros_publisher = rospy.Publisher(ROS_TOPIC_PUBLISH, String, queue_size=10)
ros_subscriber = rospy.Subscriber(ROS_TOPIC_SUBSCRIBE, String, ros_subscriber_callback)
# Initialize MQTT client
mqtt_client = mqtt.Client()
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
# Connect to MQTT server
mqtt_client.connect(MQTT_BROKER_ADDRESS, MQTT_BROKER_PORT, 60)
# Start MQTT client loop
mqtt_client.loop_start()
try:    # ROS main loop    rospy.spin()
except KeyboardInterrupt:    print("Shutting down")
# Stop MQTT client loop
mqtt_client.loop_stop()

This code defines a ROS node named mqtt_bridge_node, which also acts as an MQTT client. It subscribes to the ROS topic ros_topic_subscribe and the MQTT topic mqtt_topic_subscribe while publishing messages to the ROS topic ros_topic_publish and the MQTT topic mqtt_topic_publish.

We first publish the content of the ROS topic.

How to Establish MQTT Communication in ROS

Check the terminal to see the received messages and perform the MQTT forwarding operation.

How to Establish MQTT Communication in ROS

In MQTT.fx, you can see the status of the MQTT topic publishing.

How to Establish MQTT Communication in ROS
How to Establish MQTT Communication in ROS

How to Establish MQTT Communication in ROS

↑ Hot Course, Limited Time Coupon! 🎉 Claim Now ↑

How to Establish MQTT Communication in ROS

How to Establish MQTT Communication in ROS

Leave a Comment