使用自定义消息(Python)
使用自定义消息流程
1. 导入模块
| from demo_msgs.msg import Student
|
Tip
python导入自定义消息模块,遵循一定的规范,from 模块名.msg import 具体的消息
2. 构建消息
| stu = Student()
stu.name = "itheima"
stu.age = 13
|
或者
| stu = Student(name="itheima", age=13)
|
完整示例代码
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 | #!/usr/bin/env python
# coding:utf-8
import rospy
from demo_msgs.msg import Student
if __name__ == '__main__':
nodeName = "topic_py_publisher"
rospy.init_node(nodeName)
# 创建发布者
topicName = "topic_hello"
publisher = rospy.Publisher(topicName, Student, queue_size=1000)
rate = rospy.Rate(1)
index = 0
while not rospy.is_shutdown():
student = Student(name="name-%d" % index , age=index)
publisher.publish(student)
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 | #!/usr/bin/env python
# coding:utf-8
import rospy
from demo_msgs.msg import Student
def callback(msg):
if not isinstance(msg, Student):
return
print "name: %s" % msg.name
print "age: %d" % msg.age
print "--------------------"
if __name__ == '__main__':
nodeName = "topic_py_subscriber"
rospy.init_node(nodeName)
# 创建订阅者
topicName = "topic_hello"
rospy.Subscriber(topicName, Student, callback)
rospy.spin()
|