ROS C++ 서비스 서버와 클라이언트
2019. 10. 24. 11:05ㆍ드론
토픽과는 다르게 일회성 메세지 통신으로, 응답 요청이 있을 때만 응답하는 서비스 서버와 요청하고 응답받는 서비스 클라이언트로 나뉜다. 이러한 서비스는 로봇에 특정 동작을 수행하도록 요청할 때 많이 사용된다. 네트워크 부하가 적기 때문에 토픽을 대체하는 수단으로 매우 유용한 통신 수단이다
즉, 예를 들어 서버는 지속적으로 동작 중인 상태고 클라이언트는 한 번 서비스를 주고 결과를 받은 후 프로그램을 종료하는 코드를 동작시킬 수 있다
예시로 피보나치 수열을 서비스 노드로 짜보려고 한다
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "ros/ros.h" | |
#include "ros_tutorials_service/SrvTutorial.h" | |
#include <cstdlib> | |
int main(int argc, char **argv) | |
{ | |
ros::init(argc, argv, "service_client"); | |
if (argc != 3) | |
{ | |
ROS_INFO("cmd : rosrun ros_tutorials_service service_client arg0 arg1"); | |
ROS_INFO("arg0: double number, arg1: double number"); | |
return 1; | |
} | |
ros::NodeHandle nh; | |
ros::ServiceClient ros_tutorials_service_client = nh.serviceClient<ros_tutorials_service::SrvTutorial>("ros_tutorial_srv"); | |
ros_tutorials_service::SrvTutorial srv; | |
srv.request.a = atoll(argv[1]); | |
srv.request.b = atoll(argv[2]); | |
int count = 0; | |
while (ros_tutorials_service_client.call(srv) && ++count < 100) | |
{ | |
ROS_INFO("send srv, srv.Request.a and b: %ld, %ld", (long int)srv.request.a, (long int)srv.request.b); | |
ROS_INFO("receive srv, srv.Response.result: %ld", (long int)srv.response.result); | |
srv.request.a = srv.request.b; | |
srv.request.b = srv.response.result; | |
} | |
ROS_INFO("end!"); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "ros/ros.h" | |
#include "ros_tutorials_service/SrvTutorial.h" | |
bool calculation(ros_tutorials_service::SrvTutorial::Request &req, | |
ros_tutorials_service::SrvTutorial::Response &res) | |
{ | |
res.result = req.a + req.b; | |
ROS_INFO("request: x=%ld, y=%ld", (long int)req.a, (long int)req.b); | |
ROS_INFO("sending back response: %ld", (long int)res.result); | |
return true; | |
} | |
int main(int argc, char **argv) { | |
ros::init(argc, argv, "service_server"); | |
ros::NodeHandle nh; | |
ros::ServiceServer ros_tutorials_service_server = nh.advertiseService("ros_tutorial_srv", calculation); | |
ROS_INFO("ready srv server!"); | |
ros::spin(); | |
return 0; | |
} |
[출처] ROS 로봇 프로그래밍 표윤석
'드론' 카테고리의 다른 글
roslaunch에서 param 설정해서 노드 제어하기 (0) | 2019.10.25 |
---|---|
roslaunch command line args (0) | 2019.10.24 |
ROS C++ topic 구현 (0) | 2019.10.23 |
ROS rosbag으로 turtlesim 재생하기 (0) | 2019.10.22 |
ROS package.xml, CMakelist 구성 (0) | 2019.10.21 |