MOOS学习笔记4——独立线程不同回调
MOOS学习笔记4——独立线程不同回调
/**
* @fn 独立线程不同回调
* @version v1.0
* @author
*/
#include "MOOS/libMOOS/Comms/MOOSAsyncCommClient.h"
#include "MOOS/libMOOS/Utils/CommandLineParser.h"
//控制改变字体颜色的类 内部定义了许多颜色
#include "MOOS/libMOOS/Utils/ConsoleColours.h"
#include "MOOS/libMOOS/Utils/ThreadPrint.h"
MOOS::ThreadPrint gPrinter ( std :: cout ) ;
bool OnConnect(void *pParam) {
CMOOSCommClient *pC = reinterpret_cast<CMOOSCommClient*>(pParam) ;
pC->Register ( "X", 0.0 ) ;
pC->Register ( "Y", 0.0 ) ;
pC->Register ( "Z", 0.0 ) ;
return true ;
}
bool OnMail (void *pParam){
CMOOSCommClient *pC = reinterpret_cast<CMOOSCommClient*>(pParam);
MOOSMSG_LIST M ; // get the mail
pC->Fetch (M);
MOOSMSG_LIST::iterator q ; // process it
for ( q=M.begin () ; q!=M.end () ; q++){
//Getsource():返回发布通知的进程名称
//SimplyPrintTimeAndMessage():输出线程安全的格式化信息,第一个参数为要输出的数据
//第二个参数为颜色,默认为NULL
gPrinter.SimplyPrintTimeAndMessage ( "mail:"+q->GetSource(), MOOS::ThreadPrint::GREEN) ;
}
return true;
}
bool funcX (CMOOSMsg &M , void *TheParameterYouSaidtoPassOnToCallback)
{
gPrinter.SimplyPrintTimeAndMessage ( "call back for X" , MOOS :: ThreadPrint::CYAN) ;
return true ;
}
bool funcY ( CMOOSMsg &M , void *TheParameterYouSaidtoPassOnToCallback )
{
gPrinter.SimplyPrintTimeAndMessage ( "call back for Y" , MOOS::ThreadPrint::MAGENTA) ;
return true ;
}
int main( int argc , char *argv [] ) {
// understand the commandline
MOOS::CommandLineParser P (argc,argv);
std::string db_host="localhost" ;
P.GetVariable ( "--moos_host" , db_host);
int db_port =9000;
P.GetVariable( "--moos_port" , db_port);
std::string my_name ="ex40" ;
P.GetVariable ( "--moos_name" , my_name) ;
// configure the comms
MOOS::MOOSAsyncCommClient Comms;
Comms.SetOnMailCallBack(OnMail ,&Comms) ;
Comms.SetOnConnectCallBack(OnConnect ,&Comms);
/**
* @name AddMessageCallBack()
* @fn 加入每一条信息的回调函数
* @param[in]
* 第一个是该channel的别名
* 第二个是回调发生时想要传递的变量
* @note 使用该函数调用该函数指定的,不使用该函数则调用默认的Onmail()
*/
Comms.AddMessageCallBack("callback_X","X",funcX,NULL) ;
Comms.AddMessageCallBack("callback_Y","Y",funcY,NULL) ;
// start the comms running
Comms . Run(db_host , db_port , my_name) ;
// forever loop sending data
std :: vector<unsigned char>X(1000) ;
for ( ; ; ) {
MOOSPause (1000) ;
Comms.Notify ( "X",X) ; // for callback_X
Comms.Notify ( "Y","This is Y"); // for callback_Y
Comms.Notify ( "Z",7.0); //no callback
}
return 0 ;
}
本文为保持文章完整性可能使用了其他作者的文字,如果影响到您的权益,请与我联系,谢谢理解!
转载本文请注明出处,非作者授权不得用于商业用途。