1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

std_srvs/Empty型のサービス・クライアント作成 (Python/C++)

Last updated at Posted at 2021-07-12

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}
)
1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?