基本模型和roscpp类似
功能描述:两个node,一个发布模拟的GPS消息(格式为自定义,包括坐标和工作状态),另一个接受并处理该消息(计算到原点的距离)。
步骤:
$ cd ~/catkin_ws/src
$ catkin_create_pkg topic_demo roscpp rospy std_msgs
$ cd topic_demo/
$ mkdir msg
$ cd msg
$ vi gps.msg
# gps.msg
float32 x
float32 y
string state
完成msg的创建后,编译生成~/catkin_ws/devel/lib/python2.7/dis-packages/topic_demo/msg/__init__.py
文件。写代码import进去就可以
from topic_demo.msg import gps
#!/usr/bin/env python
import rospy
from topic_demo.msg import gps
def talker():
pub = rospy.Publisher( 'gps_info' , gps, queue_size=10)
rospy.init_node(' pytalker ', anonymous=True)
rate = rospy.Rate(1)
x = 1.0
y = 2.0
state = 'working'
while not rospy.is_shutdown():
rospy.loginfo( 'Talker: GPS: x = %f, y = %f')
pub.publish(gps(state,x,y)) # 构造了gps的临时对象,这样写更直观。
x = 1.03 * x
y = 1.01 * y
rate.sleep()
if __name__ == '__main__' :
talker()
}
#!/usr/bin/env python
import rospy
import math
from topic_demo.msg import gps
def callback(gps):
distance = math.sqrt(math.pow(gps.x, 2) + math.pow(gps.y, 2))
rospy.loginfo( 'Listener: GPS distance = %f, state: %s ', distance , gps.state)
def listener():
rospy.init_node('pylistener')
rospy.Subscribe( 'gps_info' , gps , callback)
rospy.spin()
if __name__ == '__main__' :
listener()
py程序不需要编译,在这里主要是为了编译msg文件
基本模型类似,可以参考该模板。
功能描述:两个node,一个发布请求(格式为自定义),另一个接受并处理该消息,并返回信息。
步骤:
$ cd ~/catkin_ws/src
$ catkin_create_pkg service_demo roscpp rospy std_msgs
$ cd service_demo/
$ mkdir srv
$ vi Greeting.srv
# Greeting.srv
string name
int32 age
---
string feedback
完成srv的创建后,编译生成~/catkin_ws/devel/lib/python2.7/dis-packages/service_demo/srv/__init__.py
文件。写代码import进去就可以
from service_demo.srv import *
#!/usr/bin/env python
import rospy
from service_demo.srv import *
def server_srv():
rospy.init_node(' greetings_server ')
s = rospy.Service( 'greetings', Greeting, handle_function) #定义程序的server端
rospy.loginfo(' Ready to handle the request:')
rospy.spin()
def handle_function(req):
rospy.loginfo( 'Request from' , req.name , 'with age' , req.age)
return GreetingResponse( 'Hi %s. I'm server !' %req.name)
if __name__ == '__main__' :
server_srv()
#!/usr/bin/env python
import rospy
from service_demo.srv import *
def client_srv():
rospy.init_node(' greetings_client ')
rospy.wait_for_service( 'greetings')
try:
greetings_client = rospy.ServiceProxy( 'greetings' ,Greeting)
rosp = greetings_client( 'HAN' , 20)
rospy.loginfo(' Message From Server: %s ' %rosp.feedback )
except rospy.ServiceException e:
rospy.logwarn( 'Service call failed: %s' %e)
if __name__ == '__main__' :
client_srv()
}
然后就可以编译(catkin_make)和运行(rosrun)了~
转载请注明出处。
本文总结于中国大学MOOC《机器人操作系统入门》
链接: link.
图片来自于课程视频截图