Skip to content

2.1.4 Topic Communication Custom msg Call

Requirement:

Write a publish-subscribe implementation where the publisher publishes custom messages at 1Hz (once per second), and the subscriber subscribes to the custom messages and prints the message content.

Analysis:

In the model implementation, ROS master does not need to be implemented, and the connection establishment is already encapsulated. The key points to focus on are three:

  1. Publisher
  2. Subscriber
  3. Data (here, custom message)

Process:

  1. Write the publisher implementation;
  2. Write the subscriber implementation;
  3. Add execute permissions to the Python files;
  4. Edit the configuration file;
  5. Compile and execute.

0. vscode configuration

To facilitate code hints and avoid false exceptions, first configure vscode by adding the previously generated Python file path to settings.

json
{
    "python.autoComplete.extraPaths": [
        "/opt/ros/noetic/lib/python3/dist-packages",
        "/xxx/yyy_workspace/devel/lib/python3/dist-packages"
    ]
}

1. Publisher

py
#! /usr/bin/env python
"""
    Publisher:
        Loop to send messages

"""
import rospy
from demo02_talker_listener.msg import Person


if __name__ == "__main__":
    #1.Initialize ROS node
    rospy.init_node("talker_person_p")
    #2.Create publisher object
    pub = rospy.Publisher("chatter_person",Person,queue_size=10)
    #3.Organize message
    p = Person()
    p.name = "葫芦瓦"
    p.age = 18
    p.height = 0.75

    #4.Write message publishing logic
    rate = rospy.Rate(1)
    while not rospy.is_shutdown():
        pub.publish(p)  #Publish message
        rate.sleep()  #Sleep
        rospy.loginfo("Name:%s, Age:%d, Height:%.2f",p.name, p.age, p.height)

2. Subscriber

py
#! /usr/bin/env python
"""
    Subscriber:
        Subscribe to messages

"""
import rospy
from demo02_talker_listener.msg import Person

def doPerson(p):
    rospy.loginfo("Received person information:%s, %d, %.2f",p.name, p.age, p.height)


if __name__ == "__main__":
    #1.Initialize node
    rospy.init_node("listener_person_p")
    #2.Create subscriber object
    sub = rospy.Subscriber("chatter_person",Person,doPerson,queue_size=10)
    rospy.spin() #4.Loop

3. Permission settings

Navigate to scripts in the terminal and execute: chmod +x *.py

4. Configure CMakeLists.txt

cmake
catkin_install_python(PROGRAMS
  scripts/talker_p.py
  scripts/listener_p.py
  scripts/person_talker.py
  scripts/person_listener.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

5. Execution

  1. Start roscore;
  2. Start the publisher node;
  3. Start the subscriber node.

The running result is similar to demonstration case 2 in the introduction section.


PS: You can use rqt_graphto view node relationships.