c++serviceclientrossrv

ROS-server client srv not printing uint8


So I am learning ROS and I am having an issue in writing a simple service client code.

The srv_server.cpp is:

#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;
}

The srv_client.cpp is:

#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;
}

The srv directory contains the addInts.srv (please ignore the files naming quality)

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

The issue is, when I rosrun the code, I don't see any value printed for the actual age and double age.

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

I can't see why the age is not printed, give the name is printed correctly. Please help!


Solution

  • Since it is a uint8 on the ROS side, it's actually being saved as a char when it hits c++ code. This means you're trying to print out the ASCII value of of your age field. Instead you should convert the value directly to an int when printing like:

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