1、在C++中通过创建一个类,这个类的子函数可以传递信息,并根据需要进行转换(如需要的话),并且可以在这个类中直接publish msg
举例如下:
class Publish
{
public:
ros::NodeHandle n_;
SubscribeAndPublish()
{
//Topic you want to publish
pub_ = n_.advertise("/doa_theta", 1);
//Topic you want to subscribe
sub_ = n_.subscribe("/theta", 1, &Publish::theta_roscallback, this);
sub1_ = n_.subscribe("/wakeupword", 1, &Publish::wakeup_callback, this);
}
void theta_roscallback(const std_msgs::Float32::ConstPtr& msg){
ROS_INFO("Updating weights for angle: %f", msg->data);
doa_input = msg->data;
}
void wakeup_callback(const std_msgs::String::ConstPtr& msg){
std_msgs::Int16 output;
if (msg->data.find("")){
doa_output = CqlibGetAngle(cqi);
//printf("%s%d\n","DOA:", doa_output);
ROS_INFO("DOA: %d", doa_output);
//std::cout << doa_output << std::endl;
output.data = doa_output;
pub_.publish(output);
}
}
private:
// ros::NodeHandle n_;
ros::Publisher pub_;
ros::Subscriber sub_;
ros::Subscriber sub1_;
}
2、通过创建进程子函数来发送信息,其中需要用到lpread.h该头文件,在进程中不需要回调该信息可直接发送(publish msg)。
以下为创建进程的例子(注意根据需要创建子进程):
void* vel_ctr(void* arg)
{
while(true)
{
if(resultFlag){
resultFlag=0;
std_msgs::String msg;
msg.data=result;
pub.publish(msg);
msg.data="00";
ros::spinOnce();
sleep(2);
pthread_exit(NULL);}
}
return 0;
}
void callback(const std_msgs::String::ConstPtr& msg)
{
cout<<"收到:"<data.c_str()<data.c_str();
if(str1 == str2)
{
pthread_create(&pth_[0],NULL,vel_ctr,NULL);
}
}
前面两种满足大部分需要,也是经常用到的形式,一般遇到该类问题会使用第一种,
接下来介绍第三种用法,不常用。
3、第三种直接创建一个子函数,在调用该子函数的时候,将pub和msg作为参数传送进去,详细见以下代码实现:
int run_rx(RtpSession *session,OpusDecoder *decoder, snd_pcm_t *snd,const unsigned int channels,
const unsigned int rate,float *pcm, ros::Publisher Pub , jack_msgs::JackAudio msg)
//注意该写法。。
{
int ts = 0;
short in_shorts[1920];
for (;;)
{
int r, have_more;
char buf[32767];
void *packet;
r = rtp_session_recv_with_ts(session, (uint8_t *)buf,
sizeof(buf), ts, &have_more);
assert(r >= 0);
assert(have_more == 0);
if (r == 0) {
packet = NULL;
if (0)//(verbose > 1)
fputc('#', stderr);
} else {
packet = buf;
if(0)//(verbose > 1)
fputc('.', stderr);
}
r = play_one_frame(packet, r, decoder, snd, channels,pcm);
if (r == -1)
return -1;
ts += r * 8000 / rate;
for(int ii = 0;ii
(完)欢迎批评和指正!