하루의 쉼터

[ROS] ROS Service Tutorial 본문

프로그래밍 - 개발/ROS

[ROS] ROS Service Tutorial

Changun An 2020. 12. 18. 17:04
반응형

| ROS Service 사용

OS ubuntu 18.04
ROS Version Melodic
Board Raspberry 4

Service File : SrvTutorial.srv

int64 a
int64 b
---
int64 result

 

server.cpp 

#include"ros/ros.h"
#include"ros_service_demo/SrvTutorial.h"

bool calculation(ros_service_demo::SrvTutorial::Request &req, ros_service_demo::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_service_demo_server=nh.advertiseService("ros_demo_srv",calculation);
	ROS_INFO("ready srv server!");
	ros::spin();
	return 0;
}

 

client.cpp

#include"ros/ros.h"
#include"ros_service_demo/SrvTutorial.h"
#include<cstdlib>

int main(int argc, char**argv){
	ros::init(argc,argv,"service_client");
	if(argc != 3){
		ROS_INFO("cmd : rosrun ros_demo_service service_client arg0 arg1");
		return 1;
	}
	ros::NodeHandle nh;
	ros::ServiceClient ros_service_demo_client=nh.serviceClient<ros_service_demo::SrvTutorial>("ros_demo_srv");
	
	ros_service_demo::SrvTutorial srv;
	srv.request.a =atoll(argv[1]);
	srv.request.b =atoll(argv[2]);

	if(ros_service_demo_client.call(srv)){
		ROS_INFO("send srv, srv.Request.a and b: %ld, %ld",(long int)srv.request.a,(long)srv.request.b);
		ROS_INFO("receive srv result : %ld",(long int)srv.response.result);
	}
	else{
		ROS_ERROR("Failed to call service ros_service_demo");
		return 1;
	}
	return 0;
}

 

1. 컴파일 후 srv_server 구동

 

2. srv_client 사용

 

3. srv_server 확인

반응형
Comments