使用Obj消息(Python)

使用流程

1. 导入模块

1
from demo_msgs.msg import Team

Tip

python导入自定义消息模块,遵循一定的规范,from 模块名.msg import 具体的消息

2. 构建消息

1
2
3
4
team = Team()
team.name = "xx"
team.leader.name = "xx"
team.leader.age = 0

完整示例代码

Publisher代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env python
# coding:utf-8

import rospy
from demo_msgs.msg import Team

if __name__ == '__main__':
    nodeName = "topic_py_publisher2"
    rospy.init_node(nodeName)

    # 创建发布者
    topicName = "my_topic2"
    publisher = rospy.Publisher(topicName, Team, queue_size=1000)

    rate = rospy.Rate(1)
    index = 0
    while not rospy.is_shutdown():
        team = Team()
        team.name = "name-%d" % index
        team.leader.name = "name-%d" % index
        team.leader.age = index
        publisher.publish(team)

        rate.sleep()
        index += 1

    rospy.spin()

Subscriber代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env python
# coding:utf-8

import rospy
from demo_msgs.msg import Team


def callback(msg):
    if not isinstance(msg, Team):
        return
    print "name: %s" % msg.name
    print "leader name: %s" % msg.leader.name
    print "leader age: %d" % msg.leader.age
    print "--------------------"


if __name__ == '__main__':
    nodeName = "topic_py_subscriber"
    rospy.init_node(nodeName)

    # 创建订阅者
    topicName = "my_topic2"
    rospy.Subscriber(topicName, Team, callback)

    rospy.spin()