ROS 服务器客户端 srv 不打印 uint8

ROS-server client srv not printing uint8

所以我正在学习 ROS,但在编写简单的服务客户端代码时遇到了问题。

srv_server.cpp是:

#include<iostream>
#include<string>
#include<ros/ros.h>
#include<std_msgs/String.h>
#include "msg_srv_basics/addInts.h"

bool callback_function(msg_srv_basics::addInts::Request &req, msg_srv_basics::addInts::Response &res){
    res.complete_name = req.first_name + " " + req.last_name;
    res.double_age = 2 * req.age;

    ROS_INFO_STREAM("Secret number is: " << res.secret_num);
    ROS_INFO_STREAM("Requested score is: " << req.score);
    ROS_INFO_STREAM("Actual age is: " << req.age);
    ROS_INFO_STREAM("Double age is: " << res.double_age);
    ROS_INFO_STREAM("Complete name is: " << res.complete_name);

    return true;
}

int main(int argc, char** argv){
    ros::init(argc, argv, "srv_server");
    ros::NodeHandle nodehandle;

    ros::ServiceServer service = nodehandle.advertiseService("server_client", callback_function);
    ROS_INFO_STREAM("Service publishing");
    ros::spin();

    return 0;
}

srv_client.cpp是:

#include<iostream>
#include<ros/ros.h>
#include<std_msgs/String.h>
#include<msg_srv_basics/addInts.h>

int main(int argc, char** argv){
    ros::init(argc, argv, "srv_client");
    ros::NodeHandle nodehandle;

    ros::ServiceClient client = nodehandle.serviceClient<msg_srv_basics::addInts>("server_client");
    msg_srv_basics::addInts service_node;
    service_node.request.age = 23;
    service_node.request.first_name = "Madyln";
    service_node.request.last_name = "Monroe";
    
    client.call(service_node);

    return 0;
}

srv目录包含addInts.srv(请忽略文件命名质量)

string last_name
string first_name
uint8 age
uint32 score=10     #request a constant
---
uint8 double_age
string complete_name
uint32 secret_num=1234     #response constants

问题是,当我 rosrun 代码时,我没有看到任何实际年龄和双倍年龄的打印值。

rosrun msg_srv_basics msg_srv_basics_server 
[ INFO] [1646657193.346883143]: Service publishing
[ INFO] [1646657197.717564001]: Secret number is: 1234
[ INFO] [1646657197.717584344]: Requested score is: 10
[ INFO] [1646657197.717593796]: Actual age is: 
[ INFO] [1646657197.717599339]: Double age is: .
[ INFO] [1646657197.717632206]: Complete name is: Madyln Monroe

我不明白为什么没有打印年龄,名字打印正确。请帮忙!

因为它在ROS端是一个uint8,所以当它命中c++代码时,它实际上被保存为一个char。这意味着您正在尝试打印出 age 字段的 ASCII 值。相反,您应该在打印时将值直接转换为 int:

ROS_INFO_STREAM("Actual age is: " << int(req.age));
ROS_INFO_STREAM("Double age is: " << int(res.double_age));