Writing a Simple Publisher and Subscriber (Python)

Writing a Service Node

Here we‘ll create the service ("add_two_ints_server") node which will receive two ints and return the sum.

Change directory into the beginner_tutorials package, you created in the earlier tutorial, creating a package:

$ roscd beginner_tutorials

Please make sure you have followed the directions in the previous tutorial for creating the service needed in this tutorial, creating the AddTwoInts.srv (be sure to choose the right version of build tool you‘re using at the top of wiki page in the link).

Create the scripts/add_two_ints_server.py file within the beginner_tutorials package and paste the following inside it:

#!/usr/bin/env python

from beginner_tutorials.srv import *
import rospy

def handle_add_two_ints(req):
    print "Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b))
    return AddTwoIntsResponse(req.a + req.b)

def add_two_ints_server():
    rospy.init_node(‘add_two_ints_server‘)
    s = rospy.Service(‘add_two_ints‘, AddTwoInts, handle_add_two_ints)
    print "Ready to add two ints."
    rospy.spin()

if __name__ == "__main__":
    add_two_ints_server()

Don‘t forget to make the node executable:

chmod +x scripts/add_two_ints_server.py

Code Explained

We declare our node using init_node() and then declare our service:

s = rospy.Service(‘add_two_ints‘, AddTwoInts, handle_add_two_ints)

This declares a new service named add_two_ints with the AddTwoInts service type. All requests are passed to handle_add_two_ints function. handle_add_two_ints is called with instances of AddTwoIntsRequest and returns instances of AddTwoIntsResponse.

Just like with the subscriber example, rospy.spin() keeps your code from exiting until the service is shutdown.

Writing the Client Node

#!/usr/bin/env python

import sys
import rospy
from beginner_tutorials.srv import *

def add_two_ints_client(x, y):
    rospy.wait_for_service(‘add_two_ints‘)
    try:
        add_two_ints = rospy.ServiceProxy(‘add_two_ints‘, AddTwoInts)
        resp1 = add_two_ints(x, y)
        return resp1.sum
    except rospy.ServiceException, e:
        print "Service call failed: %s"%e

def usage():
    return "%s [x y]"%sys.argv[0]

if __name__ == "__main__":
    if len(sys.argv) == 3:
        x = int(sys.argv[1])
        y = int(sys.argv[2])
    else:
        print usage()
        sys.exit(1)
    print "Requesting %s+%s"%(x, y)
    print "%s + %s = %s"%(x, y, add_two_ints_client(x, y))

Don‘t forget to make the node executable:

chmod +x scripts/add_two_ints_client.p

Code Explained

For clients you don‘t have to call init_node(). We first call:

 rospy.wait_for_service(‘add_two_ints‘)

This is a convenience method that blocks until the service named add_two_ints is available. Next we create a handle for calling the service:

 add_two_ints = rospy.ServiceProxy(‘add_two_ints‘, AddTwoInts)

We can use this handle just like a normal function and call it:

        resp1 = add_two_ints(x, y)
        return resp1.sum

Because we‘ve declared the type of the service to be AddTwoInts, it does the work of generating the AddTwoIntsRequest object for you (you‘re free to pass in your own instead). The return value is an AddTwoIntsResponse object. If the call fails, a rospy.ServiceException may be thrown, so you should setup the appropriate try/except block.

Building your nodes

catkin_make

Try it out!

rosrun beginner_tutorials add_two_ints_server.py
rosrun beginner_tutorials add_two_ints_client.py
rosrun beginner_tutorials add_two_ints_client.py 4 5
Requesting 4+5
4 + 5 = 9
Returning [4 + 5 = 9]
时间: 2024-11-01 14:25:17

Writing a Simple Publisher and Subscriber (Python)的相关文章

ROS学习 Writing a Simple Publisher and Subscriber & Examining them

本文主要部分全部来源于ROS官网的Tutorials. 创建Publisher Node roscd beginner_tutorials mkdir -p src gedit src/talker.cpp & 复制如下代码,其大致流程如下: Initialize the ROS system Advertise that we are going to be publishing std_msgs/String messages on the chatter topic to the mast

Writing a Simple Publisher and Subscriber

Writing the Publisher Node #!/usr/bin/env python # license removed for brevity import rospy from std_msgs.msg import String def talker(): pub = rospy.Publisher('chatter', String, queue_size=10) rospy.init_node('talker', anonymous=True) rate = rospy.R

【11】Writing a Simple Publisher and Subscriber (C++)

Publisher #include "ros/ros.h" #include "std_msgs/String.h" #include <sstream> int main(int argc, char **argv) { ros::init(argc, argv, "talker");   //1.启动该节点 2.并设置其名称(名称要唯一) ros::NodeHandle n; //设置节点句柄 ros::Publisher ch

Writing a Simple Service and Client (C++)

Here we'll create the service ("add_two_ints_server") node which will receive two ints and return the sum. Change directories to your beginner_tutorials package you created in your catkin workspace previous tutorials: roscd beginner_tutorials Wr

Writing a Simple Action Server using the Execute Callback

fibonacci_server.cpp /* 黄金分割数列,指的是这样一个数列:1.1.2.3.5.8.13.21.--在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*) */ #include <ros/ros.h> #include <actionlib/server/simple_action_server.h>//action lib #include <learning_actionli

2018-11-3 星期六

English: listening.speaking.reading.writing.translation 1. Do you drink a lot of water? Well, I would like to think myself as a person who drinks a lot of water, but that is not true. Sometimes I got so busy. Sometimes I got occupied that I forgot to

Publisher/Subscriber(发布/订阅者)消息模式开发流程

该模式的作用是发布者和订阅者 可以相互发送消息 发布者和订阅者都充当 生产者和消费者 发布者 package publisher.to.subscriber; import java.awt.font.TextMeasurer; import javax.jms.Connection;import javax.jms.Destination; import javax.jms.JMSException;import javax.jms.MapMessage;import javax.jms.Me

python学习之第十天

本节内容 Gevent协程 Select\Poll\Epoll异步IO与事件驱动 Python连接Mysql数据库操作 RabbitMQ队列 Redis\Memcached缓存 Paramiko SSH Twsited网络框架 协程 协程,又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器上下文和栈.因此: 协程能保留上一次调用时的

Python学习之路--Day9-2

协程 协程,又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器上下文和栈.因此: 协程能保留上一次调用时的状态(即所有局部状态的一个特定组合),每次过程重入时,就相当于进入上一次调用的状态,换种说法:进入上一次离开时所处逻辑流的位置. 协程的好处: 无需线程上下文切换的开销 无需原子操作锁定及同步的开销 方便切换控制流,简化编程模型