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

how to create a subscriber node that also publishes message?

asked 2016-02-24 19:50:19 -0500

edmond320 gravatar image

Hi everyone, I'm wondering if it's possible to create a node that serves both as a subscriber and a publisher at the same time? It will receive some messages and publish some messages to other topic.

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
#include <nav_msgs/OccupancyGrid.h>

void mapConvert(const nav_msgs::OccupancyGrid::ConstPtr& msg)
{
  ROS_INFO("I heard:1");
  pub.publish(msg->info.width);//or just simply pub.publish(1);
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "map_converter");
  ros::NodeHandle n;
  ros::Subscriber sub = n.subscribe("map", 1000, mapConvert);
  ros::Publisher pub = n.advertise<int>("mapconverted", 1000);
  ros::Rate loop_rate(10);

 int count = 0;
  while (ros::ok())
  {
     ros::spinOnce();
     loop_rate.sleep();
  }
  ros::spin();
  return 0;
}

I have tried this structure but it did not work.Please Help! Thank You in advance!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2016-02-25 03:03:17 -0500

yasagitov gravatar image

updated 2016-02-25 03:05:24 -0500

Looks like you need to implement a service.

But if you really need to use publisher, you should make publisher accessable from function by making global pointer.

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
#include <nav_msgs/OccupancyGrid.h>

ros::Publisher * pub;

void mapConvert(const nav_msgs::OccupancyGrid::ConstPtr& msg)
{
      ROS_INFO("I heard:1");
      pub->publish(msg->info.width);//or just simply pub.publish(1);
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "map_converter");
  ros::NodeHandle n;
  ros::Subscriber sub = n.subscribe("map", 1000, mapConvert);
  pub = new ros::Publisher(n.advertise<int>("mapconverted", 1000));
  ros::Rate loop_rate(10);

 int count = 0;
  while (ros::ok())
  {
     ros::spinOnce();
     loop_rate.sleep();
  }
  ros::spin();
  delete pub;
  return 0;
}
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2016-02-24 19:50:19 -0500

Seen: 327 times

Last updated: Feb 25 '16