自定义 话题消息与使用 C++实现
/
learning_topic/Person personmsg
/
Person.msg
string name
uint8 sex
uint8 age
uint8 woman =0
uint8 man =1
uint8 manplus =2
package.xml
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
CMakeListen.txt
find_package(catkin REQUIRED COMPONENTS
geometry_msgs
roscpp
rospy
std_msgs
message_generation
)
add_message_files(
FILES
Person.msg
)
catkin_package(
# INCLUDE_DIRS include
# LIBRARIES learning_topic
CATKIN_DEPENDS geometry_msgs roscpp rospy std_msgs message_runtime
# DEPENDS system_lib
)
Person_Publisher.py
#!/usr/bin/env python
#coding: utf-8
# learning/Person personmsg
import rospy
from learning_topic.msg import Person
def Person_Publisher():
rospy.init_node('Person_publisher', anonymous = True)
pub = rospy.Publisher('Personmsg', Person, queue_size = 10)
rate = rospy.Rate(5)
while not rospy.is_shutdown():
msg = Person()
msg.name = "Lee";
msg.age = 18;
msg.sex = Person.man;
pub.publish(msg)
rospy.loginfo("this publish person message;[ %s, %d, %d]",
msg.name, msg.age ,msg.sex)
rate.sleep()
if __name__ == '__main__':
try:
Person_Publisher()
except rospy.ROSInterruptException:
pass
Person_Subscriber.py
#!/usr/bin/env python
# coding: utf-8
# 本代码是以Person_Publisher话题,消息类型为learning_topic::Person
import rospy
from learning_topic.msg import Person
def PublishInfoCallback(msg):
rospy.loginfo("this is Person Publisher messgae:[name:%s, age:%d, sex:%d]",msg.name, msg.age, msg.sex)
def Person_Subscriber():
# ROS节点初始化
rospy.init_node('Person_Subscriber', anonymous=True)
# 创建一个Subscriber,订阅名为Personmsg的topic,注册回调函数personInfoCallback
rospy.Subscriber("Personmsg", Person, PublishInfoCallback)
# 循环等待回调函数
rospy.spin()
if __name__ == '__main__':
Person_Subscriber()
运行结果: