Search

ROS/Tutorials/CustomMessagePublisherSubscriber(python) - ROS Wiki

์ข…๋ฅ˜
๐ŸŒ ์ธ์šฉ์ •๋ณด (์ž๋™)
์ž‘์„ฑ์ผ
2021/12/13 06:39
4 more properties
Description: This tutorial covers how to write a publisher and subscriber using a custom message in python.
Keywords: custom message, publisher, subscriber, python
Tutorial Level: INTERMEDIATE

Writing the Custom Message

Before proceeding, a custom message should be defined following the Creating A Message tutorial.
The message used in this tutorial will be named Person.msg and have the following structure:
string name int32 age
Plain Text
๋ณต์‚ฌ

Writing the Publisher

Change directory the package that you wrote the custom message for. In this tutorial, the beginner_tutorials package will be used.
$ roscd beginner_tutorials
Plain Text
๋ณต์‚ฌ

The Code

Inside the scripts folder of the beginner_tutorials package, lets create a file custom_talker.py:
Don't forget to make the node executable:
$ chmod +x custom_talker.py
Plain Text
๋ณต์‚ฌ

The Code Explained

Now, lets look at how this code differs from the code created in the simple publisher.
If you recall, in the simple publisher, this line was:
We have simply changed the package from std_msgs to beginner_tutorials and changed name of the message that's imported from String to Person
This line is very similar to the simple publisher version:
However, there are two changes.
First, we changed the name of the topic from chatter to custom_chatter. This change was made so we don't publish two different message types to the same topic.
Second, we changed the specified message type from String to our custom message Person.
This line assigns our variable to message object that we imported.
These lines change the attributes of our message. If we recall the format of our message:
string name int32 age
Plain Text
๋ณต์‚ฌ
It contains the name and the age field. These fields are now accessible as attributes to our message

Writing the Subscriber

The Code

Back in the scripts directory:
roscd beginner_tutorials/scripts
Plain Text
๋ณต์‚ฌ
Lets create a file called custom_listener.py:
Don't forget to make the node executable:
$ chmod +x custom_listener.py
Plain Text
๋ณต์‚ฌ

The Code Explained

Again, we need to import the message type so that we can use it.
The message is given to this function by the variable that's passed in. In this case, data. As you can see in the loginfo() statement, we can access the attributes of the message as we would access the attributes of any type of object.

Building your nodes

Remember, in order for your messages to be generated, you must build your node.
Go to your catkin_workspace and run catkin_make:
$ cd ~/catkin_ws $ catkin_make
Plain Text
๋ณต์‚ฌ