Hi, I want to wrap the publisher inside a C++ class,the error is "Call to publish() on an invalid Publisher"

asked 2023-02-22 01:29:05 -0500

I find the error is not define the publisher in internet,but i have defined it in my class. The following is a part of the code.

class planner
{
private:
    ros::Publisher setpoint_raw_local_pub;
pubilc:
    void send_pos_setpoint(const Eigen::Vector3d& pos_sp, float yaw_sp);
}

planner::planner(ros::NodeHandle* nodehandle):nh(*nodehandle)
{
    calc_timer = nh.createTimer(ros::Duration(0.05), &planner::calc_cb, this); 
}

void planner::init_publisher()
{
    setpoint_raw_local_pub = nh.advertise<mavros_msgs::PositionTarget>
    ("/mavros/setpoint_raw/local", 10, this);
}

And I defined a class member function call publisher

void planner::send_pos_setpoint(const Eigen::Vector3d& pos_sp, float yaw_sp)
{
mavros_msgs::PositionTarget pos_setpoint; 
pos_setpoint.type_mask = 0b100111111000;  // 100 111 111 000  xyz + yaw

pos_setpoint.coordinate_frame = 1;

pos_setpoint.position.x = pos_sp[0];
pos_setpoint.position.y = pos_sp[1];
pos_setpoint.position.z = pos_sp[2];

pos_setpoint.yaw = yaw_sp;

setpoint_raw_local_pub.publish(pos_setpoint);
}

When i want to call the "send_pos_setpoint" function,it will throw an error in "setpoint_raw_local_pub.publish" .

I also put the definitions all in pubilc,it didn't work. but when i turn publisher definitions and the "send_pos_setpointinto" function into global variables,it workes.

However, i also want to konw how can i slove this question.(i think the changed code is not graceful,haha

Thanks for incoming answers, sorry for my vocabulary i'm not native english.

edit retag flag offensive close merge delete

Comments

The code in the question does not call init_publisher. If you did not call init_publisher, then calling it might improve things.

miura gravatar image miura  ( 2023-02-25 23:29:16 -0500 )edit