std_service/Empty型のサービス・クライアントのサンプルプログラムを記載します。
- サーバー(Python)
empty_service_server.py
# !/usr/bin/env python
from std_srvs.srv import Empty
from std_srvs.srv import EmptyResponse
import rospy
def handle(req):
print("service call")
return EmptyResponse()
def empty_server():
rospy.init_node('empty_service_server')
s = rospy.Service('empty_service', Empty, handle)
rospy.spin()
if __name__ == "__main__":
empty_server()
- クライアント(Python)
empty_service_client.py
# !/usr/bin/env python
from std_srvs.srv import Empty
import rospy
rospy.init_node('empty_service_client')
service_name = 'empty_service'
rospy.wait_for_service(service_name)
empty_service = rospy.ServiceProxy(service_name, Empty)
r = rospy.Rate(20)
while not rospy.is_shutdown() :
print("call")
empty_service()
r.sleep()
- サーバー(C++)
empty_service_server.cpp
# include "ros/ros.h"
# include "std_srvs/Empty.h"
# include "std_srvs/EmptyResponse.h"
bool handle(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res)
{
std::cout << "service call" << std::endl;
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "empty_service_server");
ros::NodeHandle n;
ros::ServiceServer service = n.advertiseService("empty_service", handle);
ros::spin();
}
- クライアント(C++)
empty_service_client.cpp
# include "ros/ros.h"
# include "std_srvs/Empty.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "empty_service_client");
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<std_srvs::Empty>("empty_service");
ros::Rate r(10);
std_srvs::Empty srv;
while (ros::ok())
{
client.call(srv);
r.sleep();
}
return 0;
}
- 上記c++プログラムの2つのcmakeファイル
CMakeLists.txt
cmake_minimum_required(VERSION 3.0.2)
project(empty_service)
find_package(catkin REQUIRED roscpp std_srvs)
catkin_package(
)
include_directories(
${catkin_INCLUDE_DIRS}
)
add_executable(empty_service_server src/empty_service_server.cpp)
target_link_libraries(empty_service_server
${catkin_LIBRARIES}
)
add_executable(empty_service_client src/empty_service_client.cpp)
target_link_libraries(empty_service_client
${catkin_LIBRARIES}
)