[rosserial] Advertise/subscribe within class with global node handle

asked 2019-07-09 11:51:45 -0500

updated 2019-07-09 12:17:53 -0500

gvdhoorn gravatar image

Hi guys,

I want to have a publisher/subscriber as a class member with a global node handle. However, unfortunately, the subscribe/advertise commands inside the classes don't seem to work. Any idea how I could fix this?

Thank you so much!

main.ino

#include <ros.h>    
#include <std_msgs/Bool.h>
#include "Arduino.h"
#include "MyClass.h"

void cb_1(const std_msgs::Bool &msg) {
  /* do something... */
}

ros::NodeHandle nh;
ros::Subscriber<std_msgs::Bool> sub_1("/bool1", &cb_1);
MyClass obj_1(nh, "/bool2");
MyClass obj_2(nh, "/bool3");

void setup() {
    nh.initNode();
    nh.subscribe(sub_1); // this works fine.
    obj_1.setup();
    obj_2.setup();
}

void loop() {
    nh.spinOnce();
}

MyClass.h

#ifndef MyClass_h
#define MyClass_h

#include "Arduino.h"
#include <ros.h>
class MyClass {
public:
  MyClass(ros::NodeHandle &nh, const String &topic);
  ~MyClass(){};
  void setup();
  void cb();

private:
  ros::NodeHandle nh_;
  String topic_;
  ros::Subscriber subscriber_;
};

#endif

MyClass.cpp

#include "Arduino.h"
#include "MyClass.h"

MyClass::MyClass(ros::NodeHandle &nh, const String &topic) : nh_(nh), topic_(topic), subscriber_(topic.c_str(), &MyClass::cb, this) {}

void MyClass::setup() {
   nh_.subscribe(subscriber_); // this does not work.
}

void MyClass::cb(const std_msgs::Bool &msg) {
  /* do something else. */
}
edit retag flag offensive close merge delete