I am working on the services section (finding the wall) of the Rosject related to the ROS Basics in 5 Days C++ course. I am trying to get laser values from a subscriber and utilize them within a service server. However, it seems the subscriber is only called once and not continuously. How can I integrate a subscriber and publisher into my service callback?
#include "ros/duration.h"
#include "ros/rate.h"
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "rosject/FindWall.h"
#include <bits/stdc++.h>
#include <sensor_msgs/LaserScan.h>
class controller {
public:
controller(){
pub = nh.advertise<geometry_msgs::Twist>("cmd_vel", 1000);
sub = nh.subscribe("/scan", 1, &controller::laserCallback, this);
my_service = nh.advertiseService("/find_wall", &controller::find_Callback, this);
}
void laserCallback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
// Identify which laser ray is the shortest one. Assume that this is the one pointing to a wall.
laser_readings.clear();
// creating vector of laser distances
for (int i = 0; i < msg -> ranges.size(); i++) {
laser_readings.push_back(msg -> ranges[i]);
}
// finding index of min value in vector
laser_min = distance(laser_readings.begin(), min_element(laser_readings.begin(),laser_readings.end()));
}
bool find_Callback(rosject::FindWall::Request &req,
rosject::FindWall::Response &res)
{
ROS_INFO("find_Callback has been called"); // We print an string whenever the Service gets called
vel.angular.z = 0.05;
pub.publish(vel);
while(laser_min != 360){
ROS_INFO("%d\n Min Element = ", laser_min);
ROS_INFO("%f\n laser_readings[laser_min] = ", laser_readings[laser_min]);
ros::Duration(0.1).sleep();
}
vel.angular.z = 0;
pub.publish(vel);
ROS_INFO("find_Callback completed");
res.wallfound = true;
return true;
}
private:
ros::Subscriber sub;
ros::Publisher pub;
ros::NodeHandle nh;
ros::ServiceServer my_service;
std::string status_update;
geometry_msgs::Twist vel;
std::vector<float> laser_readings;
int laser_min;
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "find_wall");
controller ctrl;
ros::spin();
return 0;
}