ROS与Arduino学习(五)客户端与服务器

ROS与Arduino学习(五)客户端与服务器

Tutorial Level:用ROS中的Cmake编译程序

Next Tutorial:Logging日志

Tips 1 服务器

ros::ServiceServer<Test::Request,TestResponse> server("TEST",&CallBack);

 服务器对象声明,后面两个参数,一个是服务器名称,另一个是收到客户端内容后所调用的函数。对应的类型分别是Test::Request和TestResponse

void callback(const ::Request & req, Test::Response & res){
  if((i++)%2)
    res.output = "hello";
  else
    res.output = "world";
}

 回调函数,返回值为“hello world”

  nh.advertiseService(server);

 在setup函数中需要对服务器进行绑定。

案例程序如下

/*
 * rosserial Service Server
 */

#include <ros.h>
#include <std_msgs/String.h>
#include <std_msgs/Int16.h>
#include <rosserial_arduino/Test.h>

ros::NodeHandle  nh;
using rosserial_arduino::Test;

int i;
void callback(const ::Request & req, Test::Response & res){
  if((i++)%2)
    res.output = "hello";
  else
    res.output = "world";
}

ros::ServiceServer<Test::Request, Test::Response> server("test_srv",&callback);

std_msgs::String str_msg;
ros::Publisher chatter("chatter", &str_msg);

char hello[13] = "hello world!";

void setup()
{
  nh.initNode();
  nh.advertiseService(server);
  nh.advertise(chatter);
}

void loop()
{
  str_msg.data = hello;
  chatter.publish( &str_msg );
  nh.spinOnce();
  delay(10);
}

测试程序:

此程序完成的操作是服务器接受到指令后实现返回给客户段hello与word交替返回。

#新终端打开
$ roscore
#新终端打开
$  rosrun rosserial_python serial_node.py _port:=/dev/ttyUSB0
#新终端打开
$ rosservice call test_srv ""

Tips 2 客户端

ros::ServiceClient<Test::Request, Test::Response> client("test_srv");

 客户端对象声明    client是客户端的名称,“test_srv”是它所链接的服务器名称

nh.serviceClient(client);

 节点句柄绑定客户端。

Test::Request req;
Test::Response res;
client.call(req, res);

 服务器发送消息到客户端  req是发送参数,res是返回参数

测试程序

/*
 * rosserial Service Client
 */

#include <ros.h>
#include <std_msgs/String.h>
#include <rosserial_arduino/Test.h>

ros::NodeHandle  nh;
using rosserial_arduino::Test;

ros::ServiceClient<Test::Request, Test::Response> client("test_srv");

std_msgs::String str_msg;
ros::Publisher chatter("chatter", &str_msg);

char hello[13] = "hello world!";

void setup()
{
  nh.initNode();
  nh.serviceClient(client);
  nh.advertise(chatter);
  while(!nh.connected()) nh.spinOnce();
  nh.loginfo("Startup complete");
}

void loop()
{
  Test::Request req;
  Test::Response res;
  req.input = hello;
  client.call(req, res);
  str_msg.data = res.output;
  chatter.publish( &str_msg );
  nh.spinOnce();
  delay(100);
}

测试程序

#新终端打开
$ roscore
#新终端打开
$  rosrun rosserial_python serial_node.py _port:=/dev/ttyUSB0
#新终端打开
$ rosservice call test_srv ""
原文地址:https://www.cnblogs.com/flyingjun/p/8946785.html