【FastRTPS】Example--自定义Publisher和Subscriber

11 篇文章 8 订阅

例子来自FastRTPS文档。参考《FastRTPS User Manual.odt》

自定义Publisher:

class MyPublisher : public PublisherListener
{
    Participant* mp_participant;
    Publisher* mp_publisher;
    MyPublisher(){
	//Create participant(or receive it from somewhere else)
        //Type “TestType” must be registered (can be done outside the class).
	PublisherAttributes Wparam;
	Wparam.topic.topicKind = NO_KEY; //Other possible value: WITH_KEY
	Wparam.topic.topicDataType = "TestType";
	Wparam.topic.topicName = "Test_topic";
	    
        //Modify the rest of the parameters as you wish
	mp_publisher = Domain::createPublisher(mp_participant,Wparam,this);
	if(mp_publisher == nullptr)
    	    cout << "Publisher creation failed" << endl;
    }

    ~MyPublisher(){  Domain::removePublisher(mp_publisher);}

    void onPublicationMatched(Publisher* pub,MatchingInfo info)	{
        if(info.status == MATCHED_MATCHING)
	    cout << “Publication Matched” << endl;
    }

    void run(){
        if(mp_publisher!=nullptr){
            TestType obj;
            //Fill the structure
            mp_publisher->write(&obj);
        }
    }
};

自定义Subscriber:

class MySubscriber : public SubscriberListener
{
    Participant* mp_participant;
    Subscriber* mp_subscriber;
    MySubscriber(){
        //Create participant;
        //Type “TestType” must be registered (can be done outside the class).
	SubscriberAttributes Rparam;
	Rparam.topic.topicKind = NO_KEY; //Other possible value: NO_KEY
	Rparam.topic.topicDataType = "TestType";
	Rparam.topic.topicName = "Test_topic";
	//Modify the rest of the parameters as you wish
	mp_subscriber = Domain::createSubscriber(mp_participant,Rparam,this);
	if(mp_subscriber == nullptr)
    	cout << "Subscriber creation failed" << endl;
    }
    
    ~MySubscriber { Domain::removeSubscriber(mp_subscriber)  }
    
    void onSubscriptionMatched(Subscriber* sub,MatchingInfo info) {
	if(info.status == MATCHED_MATCHING)
	    cout << “Subscriber Matched” << endl;
    }
	
    void onNewDataMessage(Subscriber* sub){
        TestType obj;
	SampleInfo_t info;
	if(mp_subscriber->takeNextData(&obj,&info)) {
	    if(info.sampleKind == ALIVE){
		//print the data object fields
	    }
	}
    }
    
    //If you read or take the data in the onNewDataMessage callback you should 
    //avoid using waitForNewMessage() in you main loop because it would never exit.
    void run(){
        cout << "Enter number to exit: " << endl;
	int aux;
	cin >> aux;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值