ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

I recently had the same problem and dumb me forgot to initialize my publisher, my solution is as follows:

#include <geometry_msgs/Twist.h>
#include <my_custom_srv_msg_pkg/MyCustomServiceMessage.h>
#include <ros/ros.h>

class MoveBB8 {
private:
  ros::Publisher pub;
  ros::NodeHandle nh;

ros::ServiceServer move_bb8_in_circle_custom;
  geometry_msgs::Twist twist;

public:

MoveBB8();
  bool circle_custom_callback(
      my_custom_srv_msg_pkg::MyCustomServiceMessage::Request &request,
      my_custom_srv_msg_pkg::MyCustomServiceMessage::Response &response);
};

MoveBB8::MoveBB8()
    : move_bb8_in_circle_custom{
          nh.advertiseService("/move_bb8_in_circle_custom",
                              &MoveBB8::circle_custom_callback, this)} {
  pub = nh.advertise<geometry_msgs::Twist>("cmd_vel", 10);     // I forgot to initialize this when I first got the error
}

bool MoveBB8::circle_custom_callback(
    my_custom_srv_msg_pkg::MyCustomServiceMessage::Request &request,
    my_custom_srv_msg_pkg::MyCustomServiceMessage::Response &response) {
  ROS_INFO("My callback has been called");
  ROS_INFO("Request duration is %d", request.duration);

  const int size = 1;
  ros::Publisher *pubs[size];

  pubs[0] = &pub;
  for (int i = 0; i < size; ++i) {
    twist.linear.x = 1;
    pubs[i]->publish(twist);
  }

  return true;
}

int main(int argc, char **argv) {

  ros::init(argc, argv, "move_bb8_in_circle_node");

  MoveBB8 move_bb8_in_circle;

  ros::spin();

  return 0;
}