Exemple #1
0
void* Forwarder(void* ignored)
{
	MessageManager mm;
	SDMData dat;
	mm.Async_Init(MYPORT2);
	char buf[BUFSIZE];
	
	SDMComponent_ID Receiver;
	Receiver.setAddress(inet_addr("127.0.0.1"));
	Receiver.setPort(MYPORT);
	
	while(1)
	{
		if (mm.IsReady())
		{
			if (mm.GetMessage(buf) == SDM_Data)
			{
				SDMData received;
				long Length = received.Unmarshal(buf);
				
				printf("(Forwarder)  Received SDMData with timestamp %ld, %ld length is %ld.\n",received.GetSecondsStamp(), received.GetSubSecondsStamp(), Length);
				
				
				Length = received.Forward(Receiver);
				printf("(Forwarder)  Forwarding message length is %ld.\n", Length);
				fflush(NULL);
			}
			else
				printf("(Forwarder)  Unknown message received.\n");
		}
		sleep(1);
	}
	return NULL;
}
Exemple #2
0
// wrapper around MessageManager::spin() that can be passed to
// pthread_create()
void*
spinFunc(void* arg)
{
  MessageManager* mgr = (MessageManager*)arg;
  mgr->spin();
  return NULL;
}
int main(int argc, char** argv)
{
  // Initialize ROS node "sm_talker"
  ros::init(argc, argv, "sm_listener");

  // Required to start timers for non-node ROS use.
  ros::Time::init();

  // Little message to know she's started
  ROS_INFO_STREAM("STARTING SM_MANAGER");

  // Create and execute manager
  // * Create a TCP server connection on TCP_PORT (see common.h)
  // * Initialize manager using server connection
  // * Initialize handler using server connection
  // * Add handler to manager
  // * Execute manager spin loop
  TcpServer server;
  server.init(TCP_PORT);

  MessageManager manager;
  MyHandler handler;

  manager.init(&server);

  // Handler initilaized with reply connection (typically the same as
  // incoming connection but now always)
  handler.init(&server);
  manager.add(&handler);
  manager.spin();

  return 0;
}
Exemple #4
0
TEST(MessageManagerSuite, init)
{
  MessageManager manager;
  TestClient client;

  EXPECT_TRUE(manager.init(&client));
  EXPECT_FALSE(manager.init(NULL));

}
Exemple #5
0
int main(int argc,char** argv)
{
	MessageManager mm;
	SDMData dat;
	SDMRegInfo info;
	SDMReqReg req_reg;
	char buf[BUFSIZE];
	long length;

	//initialize consumer
	SDMInit(argc,argv);
	my_port = getPort();
	mm.Async_Init(my_port);
	signal(SIGINT, SigHandler);

	printf("%s listening on port %ld\n",argv[0],my_port);

	while(1)
	{
		if (mm.IsReady())
		{
			switch(mm.GetMessage(buf,length))
			{
			case SDM_Data:
				dat.Unmarshal(buf,length);
				DataHandler(dat,length);
				break;
			case SDM_RegInfo:
				if(info.Unmarshal(buf)!=SDM_NO_FURTHER_DATA_PROVIDER)
				{
					RegInfoHandler(info);
				}
				break;
			default:
				printf("Unexpected message\n");
			}
		}
		else
		{	//check for data and service providers
			if(consume_msgs[0].source.getSensorID() == 0)
			{
				//request info on integer data providers
				//Set variable name
				strcpy(req_reg.item_name,"Total_Messages_Recd");
				//Set the quallist can be empty
				strcpy(req_reg.quallist,"< format=\"UINT32\"/>");
				req_reg.reply = SDM_REQREG_CURRENT_FUTURE_AND_CANCELLATIONS;
				req_reg.destination.setPort(my_port);
				req_reg.id = DATA_PROVIDER;
				req_reg.Send();
				printf("Searching for new data provider\n");
				sleep(2);
			}
			usleep(1000);
		}
	}
}
Exemple #6
0
void NewProjectAudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
{

	if(editorIsReady)
		newNotesFromAnalyser->sendActionMessage("N");


	if(analyseNewFile){

		analyseNewFile = false;

		MessageManager* mm = MessageManager::getInstance();


		void* dummy = this;

		void* d = mm->callFunctionOnMessageThread(loadNewWaveFile, dummy);
	}







    // This is the place where you'd normally do the guts of your plugin's
    // audio processing...
    for (int channel = 0; channel < getNumInputChannels(); ++channel)
    {


    }

    // In case we have more outputs than inputs, we'll clear any output
    // channels that didn't contain input data, (because these aren't
    // guaranteed to be empty - they may contain garbage).
    for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
    {
        buffer.clear (i, 0, buffer.getNumSamples());
    }

	AudioPlayHead* playHead = getPlayHead();

	AudioPlayHead::CurrentPositionInfo info;

	playHead->getCurrentPosition(info);

	float* channelData = buffer.getSampleData (0);
	if(soundEditor != 0 && !loadingNewComponent)
		soundEditor->getAudioSamplesToPlay(buffer, info.ppqPositionOfLastBarStart, getSampleRate(), currentSamplesPerBlock);
}
void* Listener(void * args)
{
	char buf[BUFSIZE];
	SDMSubreqst sub;
	SDMDeletesub del;
	MessageManager mm;
	mm.Async_Init(my_port);
	
	// Send one hearbeat, let the app fail
	SendHeartbeat();
	
	while(1)
	{
		if(mm.IsReady())
		{
			//SendHeartbeat();
#ifdef WIN32
			switch(mm.GetMsg(buf))
#else
			switch(mm.GetMessage(buf))
#endif
			{
			case SDM_Subreqst:
				sub.Unmarshal(buf);
				printf("Subscription Rec'd for %d\n",sub.msg_id.getInterfaceMessagePair()); fflush(NULL);
				pthread_mutex_lock(&subscription_mutex);
				subscriptions.AddSubscription(sub);
				pthread_mutex_unlock(&subscription_mutex);
				break;
			case SDM_Deletesub:
				printf("Cancel Rec'd\n");
				del.Unmarshal(buf);
				pthread_mutex_lock(&subscription_mutex);
				subscriptions.RemoveSubscription(del);
				pthread_mutex_unlock(&subscription_mutex);
				break;
			default:
				printf("Invalid Message found!\n");
				fflush(NULL);
				break;
			}
		}
		else
		{
			usleep(100000);
		}
	}
	return NULL;
}
//
///		NAME
//
///		SHORT DESCRIPTION
//
///		Description:
///			LONG DESCRIPTION
///
///		Return
///			VALUE and DESCRIPTION
//
STATUS SystemManager::triggerShutdown(void)
{
	SystemManagerMessage  message;
	MessageManager<SystemManagerMessage> messageManager;

	// Post an activate message
	message.major_type = SYSTEM_TRANSITION_TO_SHUTDOWN;
	messageManager.postMessage(SystemManager::queue_id, message, QUEUE_TIMEOUT_INFINITE);

	// Post an activate message
	message.major_type = SYSTEM_SHUTDOWN;
	messageManager.postMessage(SystemManager::queue_id, message, QUEUE_TIMEOUT_INFINITE);

	return STATUS_SUCCESS;
}
Exemple #9
0
/* -------------------------------------------------------------------------- */
void ImageManager::ShowMessageFromDirectory(const char* dirPath)
{
    if( imgTree.empty())
        return;
    tVecStr fileList = FileSystem::GetFiles(dirPath,File);
    if(fileList.empty())
        return;
    std::list<string> listNameMsg;
    
    string strDirPath(dirPath);
    StrToken::FormatPath(strDirPath);
    
    for( unsigned int i=0; i<fileList.size(); i++)
    {
    	string fullPath = strDirPath + fileList[i];
        KeyStr key(fileList[i]);
        ValueInt* vInt = dynamic_cast<ValueInt*>(imgTree.find(key));
        if( vInt == NULL)
           continue;
        ImgRegistry* imgReg = dynamic_cast<ImgRegistry*>(orgImages.GetRegistry(vInt->getValue()));
        tRegisterList* listIdMsg = this->orgListMsgs.GetList(imgReg->GetPtrFreeSpaceList());
        if( listIdMsg != NULL )
        {
            itRegisterList it;
            MessageManager* messageManager = MessageManager::GetInstance();
            for( it=listIdMsg->begin(); it != listIdMsg->end(); it++ )
            {
                ListMsgRegistry* listMsgReg = dynamic_cast<ListMsgRegistry*>(*it);
                ID_type idMsg = listMsgReg->GetIDMessage();
                std::string nameMsg = messageManager->GetNameMessage(idMsg);
                listNameMsg.push_back(nameMsg);
                delete listMsgReg;
            }
            delete listIdMsg;
        }
       
        delete vInt;
        delete imgReg;
        delete listIdMsg;
    }
    listNameMsg.unique();
    std::list<string>::iterator it;
    for(it=listNameMsg.begin(); it != listNameMsg.end(); it++)
    {
        std::cout << (*it) << "\n";
    }
}
Exemple #10
0
int main(int argc, char** argv)
{
	SDMInit(argc,argv);
	MessageManager mm;
	mm.Async_Init(my_port);
	signal(SIGINT,SigHandler);
	SDMReqReg request;
	SDMRegInfo info;
	char buf[BUFSIZE];
	long length;
	request.destination.setPort(my_port);
	request.id = 1;
	request.reply = SDM_REQREG_CURRENT_FUTURE_AND_CANCELLATIONS;
	printf("Sending ReqReg for Message_Count.\n");
	strcpy(request.item_name,"Message_Count");
	strcpy(request.quallist,"</>");
	request.Send();
	printf("Sending ReqReg for Enable_Logging.\n");
	strcpy(request.item_name,"Enable_Logging");
	request.Send();
	printf("Sending ReqReg for faults.\n");
	strcpy(request.item_name,"faultdata");
	request.Send();
	
	while(1)
	{
		if (mm.IsReady())
		{
			mm.GetMessage(buf,length);
			if (info.Unmarshal(buf) > 0)
			{
				printf("RegInfo received\n%s\n\n",info.msg_def);
			}
		}
		else
		{
			printf(".");
			sleep(1);
		}
	}
	
	
	request.reply = SDM_REQREG_CANCEL;
	request.Send();
	return 1;
}
Exemple #11
0
void* Sender(void* ignored)
{
	MessageManager mm;
	SDMData dat;
	for (int i = 0; i < 256; i++)
		dat.msg[i] = 0x45;
	dat.length = 256;
	mm.Async_Init(MYPORT);
	char buf[BUFSIZE];
	
	SDMComponent_ID Receiver;
	Receiver.setAddress(inet_addr("127.0.0.1"));
	Receiver.setPort(MYPORT2);
	
	while(1)
	{
		if (mm.IsReady())
		{
			if (mm.GetMessage(buf) == SDM_Data)
			{
				SDMData received;
				received.Unmarshal(buf);
				
				printf("(Sender)  Received SDMData with timestamp %ld, %ld.\n",received.GetSecondsStamp(), received.GetSubSecondsStamp());
				fflush(NULL);
				if (!DataCheck(received))
				{
					printf("(Sender)  ERROR message doesn't match!\n");
				}
			}
			else
				printf("(Sender)  Unknown message received.\n");
			
		}
		// Send the message
		printf("(Sender)  Sending message...\n");
		dat.SendTo(Receiver);
		
		sleep(1);
	}
	
	return NULL;
}
Exemple #12
0
/* -------------------------------------------------------------------------- */
void ImageManager::DeleteImage(ID_type idImg, tVecStr* imgErasedList, bool filterAll, bool removetoTree){

	ImgRegistry* img=dynamic_cast<ImgRegistry*>(orgImages.GetRegistry(idImg));
	FreeSpaceManager* fsManager = FreeSpaceManager::GetInstance();
	MessageManager* msgManager = MessageManager::GetInstance();
	
	//Obtener la lista de mensajes.
	if( img->GetPtrMsgList() > 0 )
	{
		tRegisterList* msgList = this->orgListMsgs.GetList(img->GetPtrMsgList());
		itRegisterList it = msgList->begin();

		//Eliminar mensajes asociados.
		while(it != msgList->end())
		{
			ListMsgRegistry* msgReg = dynamic_cast<ListMsgRegistry*>(*it);
			if(filterAll)
				msgManager->DeleteMessage(msgReg->GetIDMessage(),false, imgErasedList);
			else
				msgManager->DeleteMessage(msgReg->GetIDMessage(),true, imgErasedList);
			it++;
		}
	}
	
	//Eliminar Path
	string path=orgNamesImages.GetText(img->GetIDImagePath());
	orgNamesImages.DeleteText(img->GetIDImagePath());
	
	//Eliminar el espacio libre disponible.
	delete img;
	img = dynamic_cast<ImgRegistry*>(orgImages.GetRegistry(idImg));
	fsManager->RemoveFreeSpaceList(img->GetPtrFreeSpaceList());

	//Eliminar Registro Imagen.
	this->orgImages.DeleteRegistry(idImg);
	//Eliminar el arbol.
	KeyStr kImgTree(path.c_str());
	if (!imgTree.empty() && removetoTree)
		if (imgTree.exists(kImgTree))
			imgTree.remove(kImgTree);
}
int main(int argc, char** argv)
{
    char ip[1024] = "192.168.0.50"; // Robot IP address
    TcpClient connection;
    MessageManager manager;

    ros::init(argc, argv, "state_interface");
    ros::NodeHandle n;

    JointRelayHandler jr_handler(n);

    ROS_INFO("Setting up client");
    connection.init(ip, StandardSocketPorts::STATE);
    connection.makeConnect();

    jr_handler.init(&connection);

    manager.init(&connection);
    manager.add(&jr_handler);

    manager.spin();
}
Exemple #14
0
int main(int argc,char** argv)
{
	SDMData dat;
	

	SDMInit(argc,argv);
	my_port = getPort();
	if (my_port < 0)
	{
		printf("Error requesting port.\n");
		return -1;
	}
	mm.Async_Init(my_port);
	RegisterxTEDS();
	GetComponentID();
	CancelxTEDS();
}
Exemple #15
0
TEST(MessageManagerSuite, addHandler)
{
  MessageManager manager;
  TestClient client;
  PingHandler handler;

  EXPECT_EQ(0, (int)manager.getNumHandlers());

  ASSERT_TRUE(manager.init(&client));
  EXPECT_EQ(1, (int)manager.getNumHandlers());
  EXPECT_FALSE(manager.add(NULL));

  ASSERT_TRUE(handler.init(&client));
  EXPECT_FALSE(manager.add(&handler));
}
Exemple #16
0
void GetComponentID()
{
	char buf[BUFSIZE];
	SDMService service;
	SDMData data;
	
	service.source = DataManager;
	service.source.setSensorID(1);  //DataManager sensor_id is always 1
	service.destination.setPort(my_port);
	service.command_id = 264;  //Could be queried for by using a SDMReqReg with item_name = ReturnSensorID
	service.length = 4;
	PUT_INT(service.data,PID);
	service.Send();

	mm.BlockGetMessage(buf);
	data.Unmarshal(buf);

	my_PID = GET_LONG(data.msg);
	my_sensorID = GET_LONG(&data.msg[4]);  //Could be gotten from the Messagemanipulator
	printf("My PID is %ld\n",my_PID);
	printf("My sensor_id is %ld\n",my_sensorID);
}
Exemple #17
0
void* Listener(void * args)
{
	char buf[BUFSIZE];
	SDMSubreqst sub;
	SDMDeletesub del;
	MessageManager mm;
	mm.Async_Init(myPort);
	while(1)
	{
		pthread_testcancel();
		if(mm.IsReady())
		{
			SendHeartbeat();
#ifdef WIN32
			switch(mm.GetMsg(buf))
#else
			switch(mm.GetMessage(buf))
#endif
			{
			case SDM_ACK:
				printf("SDMAck received\n");
				helloReply = true;
				break;
			case SDM_Register:
				printf("SDMRegister received\n");
				waitForReg = false;
				break;
			case SDM_ID:
				printf("SDMID received\n");
				myID.Unmarshal(buf);
				printf("CompID: \n");
				printf("   SensorID: %li\n", myID.destination.getSensorID());
				printf("    Address: %lx\n", myID.destination.getAddress());
				printf("       Port: %i\n", myID.destination.getPort());
				waitForID = false;					
				break;
			case SDM_Subreqst:
				sub.Unmarshal(buf);
				printf("Subscription Rec'd for %d\n",sub.msg_id.getInterfaceMessagePair());
				pthread_mutex_lock(&subscription_mutex);
				subscriptions.AddSubscription(sub);
				pthread_mutex_unlock(&subscription_mutex);
				break;
			case SDM_Deletesub:
				printf("Cancel Rec'd\n");
				del.Unmarshal(buf);
				pthread_mutex_lock(&subscription_mutex);
				subscriptions.RemoveSubscription(del);
				pthread_mutex_unlock(&subscription_mutex);
				break;
			default:
				printf("Invalid Message found!\n");
				break;
			}
		}
		else
		{
			usleep(100000);
		}
	}
	return NULL;
}
Exemple #18
0
TEST(DISABLED_MessageManagerSuite, tcp)
{
  const int port = TEST_PORT_BASE + 201;
  char ipAddr[] = "127.0.0.1";

  TestClient* client = new TestClient();
  TestServer server;
  SimpleMessage pingRequest, pingReply;
  MessageManager msgManager;

  // MessageManager uses ros::ok, which needs ros spinner
  ros::AsyncSpinner spinner(0);
  spinner.start();

  ASSERT_TRUE(pingRequest.init(StandardMsgTypes::PING, CommTypes::SERVICE_REQUEST, ReplyTypes::INVALID));

  // TCP Socket testing

  // Construct server
  ASSERT_TRUE(server.init(port));

  // Construct a client
  ASSERT_TRUE(client->init(&ipAddr[0], port));

  // Connect server and client
  pthread_t serverConnectThrd;
  pthread_create(&serverConnectThrd, NULL, connectServerFunc, &server);

  ASSERT_TRUE(client->makeConnect());
  pthread_join(serverConnectThrd, NULL);

  // Listen for client connection, init manager and start thread
  ASSERT_TRUE(msgManager.init(&server));

  // TODO: The message manager is not thread safe (threads are used for testing,
  // but running the message manager in a thread results in errors when the
  // underlying connection is deconstructed before the manager
  //boost::thread spinSrvThrd(boost::bind(&MessageManager::spin, &msgManager));
  pthread_t spinSrvThrd;
  pthread_create(&spinSrvThrd, NULL, spinFunc, &msgManager);

  // Ping the server
  ASSERT_TRUE(client->sendMsg(pingRequest));
  ASSERT_TRUE(client->receiveMsg(pingReply));
  ASSERT_TRUE(client->sendAndReceiveMsg(pingRequest, pingReply));

  // Delete client and try to reconnect

  delete client;
  sleep(10); //Allow time for client to destruct and free up port
  client = new TestClient();

  ASSERT_TRUE(client->init(&ipAddr[0], port));
  ASSERT_TRUE(client->makeConnect());
  ASSERT_TRUE(client->sendAndReceiveMsg(pingRequest, pingReply));

  pthread_cancel(spinSrvThrd);
  pthread_join(spinSrvThrd, NULL);

  delete client;
}
Exemple #19
0
void MessageManagerPrototype::printToOutputPane(const QString &text, bool bringToForeground)
{
    MessageManager *mm = qscriptvalue_cast<MessageManager *>(thisObject());
    QTC_ASSERT(mm, return);
    mm->printToOutputPane(text, bringToForeground);
}
Exemple #20
0
int main()
{
	// A message manager 
	MessageModule* messageModule = Gnoll::Core::MessageModule::getInstancePtr();
	MessageManager* mymanager = messageModule->getMessageManager();

	// A message type called "string" 
	Messages::MessageType mytype("string");

	// A listener
	shared_ptr<MessageListener> mylistener(new MyMessageListener);




	/*
	 * We add a listner and send some messages
	 * Each of them are handle by the listener thanks to the message manager
	 */

		mymanager->addListener ( mylistener, mytype );
		cout << "Listener ajoute" << endl;

	shared_ptr<boost::any> texte (new boost::any(string("blablabla..."))) ;

	shared_ptr<Message>  mymessage (new Message(mytype, texte ));

	try
	{
		mymanager->queueMessage(mymessage);
		cout << "Message ajoute" << endl;

		mymanager->queueMessage(mymessage);
		cout << "Message ajoute" << endl;

		mymanager->queueMessage(mymessage);
		cout << "Message ajoute" << endl;
	}
	catch(...)
	{
	}

	messageModule->processQueue();




	/*
	 * If the listener is deleted, no one care about the message.
	 * The message manager rejects the message since there is no listener 
	 *  which care about this message type
	 */

	try
	{
		mymanager->delListener ( mylistener, mytype );
		cout << "Listener supprime" << endl;

		mymanager->queueMessage(mymessage);
		cout << "Message ajoute" << endl;
	}
	catch(...)
	{
	}

	messageModule->processQueue();

	/*
	 * We re-add the listener, send some messages and abort all of them.
	 */

	try
	{
		mymanager->addListener ( mylistener, mytype );
		cout << "Listener ajoute" << endl;
		mymanager->queueMessage(mymessage);
		cout << "Message ajoute" << endl;

		mymanager->queueMessage(mymessage);
		cout << "Message ajoute" << endl;

		mymanager->abortMessage(mytype, true); 
		cout << "Message annule" << endl;
	}
	catch(...)
	{
	}

	messageModule->processQueue();




	/*
	 * The listener is re-deleted and a message is sent
	* -> No one cares about this message
	 */

	try
	{
		mymanager->delListener ( mylistener, mytype );
		cout << "Listener supprime" << endl;

		mymanager->queueMessage(mymessage);
		cout << "Message ajoute" << endl;
	}
	catch(...)
	{
	}

	messageModule->processQueue();

	// Bye bye 
	cout << "Au revoir !" << endl;
	messageModule->destroy();
	return 0;
}
Exemple #21
0
int main(int argc,char** argv)
{
	MessageManager mm;
	SDMData dat;
	SDMRegInfo info;
	SDMReqReg req_reg;
	char buf[BUFSIZE];
	long length;
	bool infosDone = false;
	int numRecd = 0;

	//initialize consumer
	SDMInit(argc,argv);
	my_port = getPort();
	mm.Async_Init(my_port);

	printf("Consumer listening on port %ld\n",my_port);

	while(!infosDone)
	{
		if (mm.IsReady())
		{
			switch(mm.GetMessage(buf,length))
			{
			case SDM_RegInfo:
				if(info.Unmarshal(buf)!=SDM_NO_FURTHER_DATA_PROVIDER)
				{
					numRecd++;
					RegInfoHandler(info);
				}
				else
				{
					if (numRecd == 0)
					{
						printf("No log messages found.\n");
						fflush(NULL);
					}
					infosDone = true;
				}
				break;
			default:
				printf("Unexpected message\n");
			}
		}
		else
		{	//check for data and service providers
			if(data_provider.getSensorID() == 0)
			{
				//request info on integer data providers
				//Set variable name
				strcpy(req_reg.item_name,"Disable_Logging");
				//Set the quallist can be empty
				strcpy(req_reg.quallist,"< >");
				req_reg.reply = SDM_REQREG_CURRENT_AND_FUTURE;
				req_reg.destination.setPort(my_port);
				req_reg.id = DATA_PROVIDER;
				req_reg.Send();
				printf("Searching for log command...\n");
				sleep(2);
			}
			usleep(1000);
		}
	}
}
Exemple #22
0
void MessageManagerPrototype::displayStatusBarMessage(const QString &text, int ms)
{
    MessageManager *mm = qscriptvalue_cast<MessageManager *>(thisObject());
    QTC_ASSERT(mm, return);
    mm->displayStatusBarMessage(text, ms);
}
Exemple #23
0
int main (int argc, char ** argv)
{
	MessageManager mm;
	char buf[BUFSIZE];
	SDMSearchReply ReplyMsg;
	unsigned char type;
	char InfoSource[40];
	char MessageID[40];
	SDMInit(argc, argv);
	signal(SIGINT,SigHandler);
	
	myPort = getPort();
	if (myPort == SDM_PM_NOT_AVAILABLE)
	{
		myPort = 4059;
	}
	mm.Async_Init(myPort);
	
	printf("-------------------SDMSearch Tester-------------------\n");
	
	bool MenuFinished = false;
	
	while (!MenuFinished)
		MenuFinished = Menu();
		
	printf("Sending request...\n");
	Request.destination.setPort(myPort);
	Request.Send();
	
	int count = 1;
	bool Finished = false;
	if (Request.reply > SDM_SEARCH_CURRENT)
	{
		printf("Press CTRL+C to quit.\n");
		sleep(1);
	}
	while (!Finished || Request.reply > SDM_SEARCH_CURRENT)
	{
		type = mm.BlockGetMessage(buf);
		switch (type)
		{
			case SDM_SearchReply:
			{
				long length = ReplyMsg.Unmarshal(buf);
				if (length == SDM_NO_FURTHER_DATA_PROVIDER)
					Finished = true;
				else
				{
					ReplyMsg.source.IDToString(InfoSource, sizeof(InfoSource));
					printf("(%d) SearchReply received (%s):\n",count++, InfoSource);
					
					printf("\t---Captured Text Portion:---\n");
					
					bool nullFound = false;
					for (unsigned int i = 0; i < sizeof(ReplyMsg.captured_matches); i++)
					{
						if (isprint(ReplyMsg.captured_matches[i]))
						{
							printf("%c", ReplyMsg.captured_matches[i]);
							nullFound = false;
						}
						else if (ReplyMsg.captured_matches[i] == '\0')
						{
							printf("0");
							if (nullFound)
							{
								printf("\n");
								break;
							}
							nullFound = true;
						}
						
					}
				}
				break;
			}
			default:
				printf("Unexpected message (%d).\n",type);
		}
	}
	printf("End of SDMSearch messages.\n");	
	printf("-------------------SDMSearch Tester Finished-------------------\n");
	return 0;	
}
Exemple #24
0
int main(int argc,char** argv)
{
	SDMService service;
	SDMConsume con;
	MessageManager mm;
	char buf[BUFSIZE];
	char name[128];
	char ip[17];
	long port;
	SDMComponent_ID id;

	int pid = 0;
	SDMData dat;

	SDMInit(argc,argv);
	my_port = getPort();
	if (my_port < 0)
	{
		printf("Error getting port.\n");
		return -1;
	}
	mm.Async_Init(my_port);
	
	RegisterxTEDS();
	usleep(100);
	service.source.setSensorID(1);
	service.command_id = 264;
	service.destination.setPort(my_port);
	service.length = 4;
	pid = atoi(argv[3]);
	memcpy(service.data,&pid,4);
	service.Send();
	
	if (mm.BlockGetMessage(buf) != SDM_Data)
	{
		printf("Error, unknown message received.\n");
		return -1;
	}
	dat.Unmarshal(buf);
	
	pid = GET_LONG(dat.msg);
	printf("My SensorID is %d\n",pid);
	service.command_id = 262;
	memcpy(service.data,&pid,4);
	service.Send();
	
	if (mm.BlockGetMessage(buf) != SDM_Data)
	{
		printf("Error, unknown message received.\n");
		return -1;
	}
	dat.Unmarshal(buf);
	
	memset(name,0,128);
	strncpy(name,dat.msg,127);
	printf("My name is %s\n",name);
	service.command_id = 268;
	service.Send();
	
	if (mm.BlockGetMessage(buf) != SDM_Data)
	{
		printf("Error, unknown message received.\n");
		return -1;
	}
	dat.Unmarshal(buf);
	
	port = GET_LONG(dat.msg);
	strcpy(ip,&dat.msg[4]);
	printf("My port is %ld and my ip is %s\n",port,ip);
	service.command_id = 267;
	service.Send();
	service.command_id = 270;
	id.setSensorID(pid);
	id.setPort(port);
	id.setAddress(inet_addr(ip));
	id.Unmarshal(service.data,0);
	service.Send();
	
	if (mm.BlockGetMessage(buf) != SDM_Data)
	{
		printf("Error, unknown message received.\n");
		return -1;
	}
	dat.Unmarshal(buf);
	
	printf("My componentKey is %s\n",dat.msg);
	CancelxTEDS();
}
//
///     NAME
//
///     SHORT DESCRIPTION
//
///     Description:
///         LONG DESCRIPTION
///
///     Return
///         VALUE and DESCRIPTION
//
STATUS SystemManager::systemLoop(void) 
{
    STATUS                                  status = STATUS_FAILURE;
    MessageManager<SystemManagerMessage>    messageManager;
    SystemManagerMessage                    message;
    
    // Create a message queue
    QueueManager::createQueue(SystemManager::queue_id, MAX_QUEUE_SIZE_DEFAULT);
    
    // Post an activate message
    message.major_type = SYSTEM_ACTIVATE;
    messageManager.postMessage(SystemManager::queue_id, message, QUEUE_TIMEOUT_INFINITE);
    
    // Start loop
    while(1) 
    {
        status = messageManager.getMessage(SystemManager::queue_id,
                                           message,
                                           QUEUE_TIMEOUT_DEFAULT);
        
        if(status == STATUS_SUCCESS)
        {
            LogManager::logMessage(MODULE_SYSTEM_MANAGER,
                                   DEBUG_LEVEL,
                                   NULL,
                                   "Received Message, Major Type: %lu",
                                   message.major_type);
            
            switch(mState)
            {
                case SYSTEM_MANAGER_INIT:
                    status = initProcessing(message);
                    break;
                
                case SYSTEM_MANAGER_ACTIVE:
                    status = activeProcessing(message);
                    break;
                
                case SYSTEM_MANAGER_SHUTDOWN:
                    status = shutdownProcessing(message);
                    break;
                
                default:
                    break;
            }
            
            if(status == STATUS_SHUTDOWN_SUCCESS)
            {
                break;
            }
        }
    }
    
    mThreadGroup.join_all();
    
    LogManager::logMessage(MODULE_SYSTEM_MANAGER,
                           DEBUG_LEVEL,
                           NULL,
                           "All Threads Joined Succesfully.");
    
    return STATUS_SUCCESS;
}
Exemple #26
0
int main(int argc, char ** argv)
{
	unsigned long result = 0;
	int length = 0;
	int miss_count = 0;
	int num_toget = 0;
	char buf[BUFSIZE];
	SDMReady heartbeat;
	MessageManager mm;
	SDMComponent_ID tm;
	
	//Set monitor process address
	heartbeat.source.setSensorID(0);
	heartbeat.source.setAddress(inet_addr("127.0.0.1"));
	heartbeat.source.setPort(PORT_TM_MONITOR);
	
	//Set TM address
	tm.setAddress(inet_addr("127.0.0.1"));
	tm.setPort(PORT_TM);
	tm.setSensorID(0);
	
	signal(SIGINT, SigIntHandler);
	tm_handle = StartTM(argv);
	mm.Async_Init_Both(PORT_TM_MONITOR);
	
	/* If spawn was successful */
	if (tm_handle != NULL)		
	{
		/* Allow the TM to get started up */
		sleep(HEARTBEAT_INTERVAL);
		while (1)
		{
			//Send heartbeats via UDP
			heartbeat.SendTo(tm);
			length = heartbeat.Marshal(buf);
			sleep(HEARTBEAT_INTERVAL);
			
			//If Task Manager quit
			if (!GetExitCodeProcess(tm_handle,&result))
				printf("  Monitor:  Invalid handle for retrieving exit code.\n");
			/* If the TaskManager has quit for some reason */
			if (result != STILL_ACTIVE)
			{
				printf("  Monitor:  TM failed, restarting...\n");
				tm_handle = StartTM(argv);
				if (tm_handle != NULL)
				{
					/* Allow the TM to restart */
					sleep(HEARTBEAT_INTERVAL);
					/* Start over at while */
					continue;
				}
				/* Error re-starting TM */
				else
				{
					printf("  Monitor:  Could not restart the TM.\n");
					return -1;
				}
			}
			/* The TM is still running, check for responses to heartbeat messages */
			else if (mm.IsReady())
			{
				//Should respond with one message
				num_toget = 1;
				
				while (mm.IsReady())
				{
					num_toget--;
					/* Message is discarded, we only care that one was received */
					mm.GetMsg(buf);
				}
				if (num_toget > 0)
					miss_count++;
				else
					miss_count = 0;
			}
			/* The TM is still running, but no responses were received */
			else
			{
				//If no messages were received
				miss_count++;
				if (miss_count == NUM_HEARTBEAT_TRIES)
				{
					printf("  Monitor:  TM unresponsive, restarting...\n");
					/* If the Terminate fails and the TM is already dead */
					if (!TerminateProcess(tm_handle,0))
					{
						/* Get its return value */
						GetExitCodeProcess(tm_handle,&result);
					}
					/* Restart the TM */
					tm_handle = StartTM(argv);
					/* Success restarting */
					if (tm_handle != NULL)
					{
						/* Allow TM to get started */
						sleep(HEARTBEAT_INTERVAL);
						/* Start over at while loop */
						continue;
					}
					/* Error restarting */
					else
					{
						printf("  Monitor:  Could not restart the TM.\n");
						return -1;
					}
				}
			}
		}
	}
	else
	{
		printf("  Monitor:  Error starting the TM.\n");
		return -1;
	}
	return 0;
}
int main(int argc,char** argv)
{
	SDMSearch s;
	SDMSearchReply reply;
	SDMData dat;
	SDMConsume con;
	int result = 0;
	char buf[BUFSIZE];
	long length;
	MessageManager mm;
	int cur = 0;
	int count = 0;
	char c;
	unsigned long SID;
		
	signal(SIGINT,SigHandler);
	SDMInit(argc,argv);
	my_port = getPort();
	if(my_port == SDM_PM_NOT_AVAILABLE)
	{
		printf("Unable to get a port from the Process Manager!\n");
		exit(0);
	}
	mm.Async_Init(my_port);
	sleep(1);
	s.destination.setPort(my_port);
	s.destination.setAddress(DataManager.getAddress());  //This application must be run on the same node as the DM
	s.reply = SDM_SEARCH_CURRENT_AND_FUTURE;
	
	printf("\nSending SDMSearch for Device orientation\n");
	memset(s.reg_expr,0,512);
	strcpy(s.reg_expr,".*?<Orientation.*?axis=\"(.*?)\".*");
	s.id = ORIENTATION_SEARCH_ID;
	s.Send();
	
	con.destination = s.destination;
	con.source.setPort(PORT_DM);
	con.source.setAddress(DataManager.getAddress());
	con.source.setSensorID(1);
	con.msg_id = 0x103;
	con.Send();
	
	con.msg_id = 0x104;
	con.Send();
	while(1)
	{
		if (mm.IsReady())
		{
			c = mm.GetMessage(buf,length);
			cur = 0;
			switch(c)
			{
				case SDM_SearchReply:
					result = reply.Unmarshal(buf);
					if(result == SDM_NO_FURTHER_DATA_PROVIDER)
						continue;
					printf("\n");
					if (reply.id == ORIENTATION_SEARCH_ID)
						printf("Reply for orientation search:\n");
					if(count != 0)
						printf("\n");
					printf("Match(es) from %lu:%lu:%d\n",reply.source.getSensorID(),reply.source.getAddress(),reply.source.getPort());
					count++;
					while(reply.captured_matches[cur]!=0)
					{
						if(strlen(reply.captured_matches+cur)<32)
							printf("Match is %s\n",reply.captured_matches+cur);
						else
							printf("Match length of %d exceeds name length restriction of 32\n",strlen(reply.captured_matches+cur));
						cur += strlen(reply.captured_matches+cur)+1;
					}
					break;
				case SDM_Data:
					result = dat.Unmarshal(buf);
					if(dat.length > 4)
					{
						memcpy(&SID,&dat.msg[1],4);
						printf("xTEDS change of type %d on SID %ld\n",dat.msg[0],SID);
					}
					else
					{
						memcpy(&SID,&dat.msg[0],4);
						printf("xTEDS modificaton of SID %ld\n",SID);
					}
					break;
				default:
					printf("Unexpected message of type %c \n",c);
			}
		}
		else
		{
			printf(".");
			sleep(1);
			fflush(NULL);
		}
	}
}
Exemple #28
0
int main (int argc, char ** argv)
{
	char buf[BUFSIZE];
	long length;
	SDMRegInfo info;
	SDMData data;
	SDMInit(argc, argv);
	int Count = 0;
	MessageManager mm;
	mm.Async_Init(my_port);
	signal(SIGINT, SigHandler);
	
	while (1)
	{
		if (mm.IsReady())
		{
			switch(mm.GetMessage(buf, length))
			{
				case SDM_RegInfo:
					if (info.Unmarshal(buf) != SDM_NO_FURTHER_DATA_PROVIDER)
					{
						RegInfoHandler(info);
					}
					break;
				case SDM_Data:
					data.Unmarshal(buf);
					DataHandler(data);
					break;
				
			}
			
		}
		else if (!providers_found)
		{
			SendRegReqs();
			sleep(1);
		}
		else
		{
			sleep(1);
			/*	if (Count++ == 10)
			{
				printf("  Starting task %s...\n", START_TASKNAME);
				SDMCommand request;
				request.source = TMID;
				request.command_id = starttask_id;
				request.destination.setPort(my_port);
				const unsigned short ZERO = 0;
				PUT_USHORT(request.data, ZERO);
				PUT_INT(request.data + 2, 0);
				const unsigned int FILENAME_OFFSET = 6;
				strcpy(request.data + FILENAME_OFFSET, START_TASKNAME);
				request.length = 27;
				request.Send();
				Count = 0;
				}*/
		}
	}
	
	
	return 0;
}
Exemple #29
0
int main(int argc, char **argv)
{

    MessageManager msgmgr;
    
    static struct option long_options[] = {
        {"nozoom", 0, 0, 0},
        {"goto", 1, 0, 0},
        {"gotoright", 0, 0, 0},
        {"gotoleft", 0, 0, 0},
        {"gotoup", 0, 0, 0},
        {"gotodown", 0, 0, 0},
        {"mode", 1, 0, 0},
        {"acquire", 2, 0, 0},
        {"acquirecurrent", 0, 0, 0},
        {"stop", 0, 0, 0},
        {"gotocolumn", 1, 0, 0},
        {"gotorow", 1, 0, 0},
        {"view", 1, 0, 0},
        {"zoom", 0, 0, 0},
        {"reload", 0, 0, 0},
        {"changespeed", 1, 0, 0},
        {"zoomspeed", 1, 0, 0},
        {"dontexit", 0, 0, 0},
	{"noautofun", 0, 0, 0},
	{"revmousewheel", 0, 0, 0},
	{"swapmousebuttons", 0, 0, 0},
	{"altmousebuttons", 0, 0, 0},
	{"justswitch", 0, 0, 0},
        {"version", 0, 0, 0},
        {0, 0, 0, 0}
    };

    float tmp;
    int c;
    int option_index;
    while (1) {

        c = getopt_long (argc, argv, "v",
                         long_options, &option_index);
        if (c == -1)
            break;

        switch (c) {
        case 0: // long option

            switch (option_index) {
            case 0: // 'nozoom'
                msgmgr.msg.zoom = 0;
                break;
            case 1: // 'goto'  ---- use is deprecated (in favor of gotocolumn)
                msgmgr.msg.goto_column = atoi (optarg);
                if (msgmgr.msg.goto_column < 1) 
                    usage_and_bye();
                break;
            case 2: // 'gotoright'
                msgmgr.msg.goto_column = GOTO_FACE_RIGHT;
                break;
            case 3: // 'gotoleft'
                msgmgr.msg.goto_column = GOTO_FACE_LEFT;
                break;
            case 4: // 'gotonext'
                msgmgr.msg.goto_row = GOTO_FACE_UP;
                break;
            case 5: // 'gotoprev'
                msgmgr.msg.goto_row = GOTO_FACE_DOWN;
                break;
            case 6: // 'mode'
                if (strcmp(optarg, "cylinder") == 0) {
                    msgmgr.msg.face_type = FACE_TYPE_CYLINDER;
                } else if (strcmp(optarg, "linear") == 0) {
                    msgmgr.msg.face_type = FACE_TYPE_LINEAR;
                } else if (strcmp(optarg, "viewmaster") == 0) {
                    msgmgr.msg.face_type = FACE_TYPE_VIEWMASTER;
                } else if (strcmp(optarg, "carousel") == 0) {
                    msgmgr.msg.face_type = FACE_TYPE_CAROUSEL;
                } else if (strcmp(optarg, "priceisright") == 0) {
                    msgmgr.msg.face_type = FACE_TYPE_PRICEISRIGHT;
                } else if (strcmp(optarg, "flip") == 0) {
                    msgmgr.msg.face_type = FACE_TYPE_FLIP;
                } else if (strcmp(optarg, "random") == 0) {
                    msgmgr.msg.face_type = FACE_TYPE_RANDOM;
                } else {
                    usage_and_bye();
                }
                break;
            case 7: // 'acquire'
                msgmgr.msg.mtype = MTYPE_ACQUIRE;
                if (optarg) {
                    int tmpint = atoi (optarg);
                    // must be between 10ms and 3sec for now
                    if (10 < tmpint && tmpint < 3000)
                        msgmgr.msg.acquire_sleep = tmpint;
                } else {
                    msgmgr.msg.acquire_sleep = 700;
                }
                break;
            case 8: // 'acquirecurrent'
                msgmgr.msg.mtype = MTYPE_ACQUIRE_CURRENT;
                break;
            case 9: // 'stop'
                msgmgr.msg.mtype = MTYPE_STOP;
                printf ("Stopping 3ddesktop daemon...\n");
                break;
            case 10: // 'gotocolumn'
                msgmgr.msg.goto_column = atoi (optarg);
                if (msgmgr.msg.goto_column < 1) 
                    usage_and_bye();
                break;
            case 11: // 'gotorow'
                msgmgr.msg.goto_row = atoi (optarg);
                if (msgmgr.msg.goto_row < 1) 
                    usage_and_bye();
                break;
            case 12: // 'view'
                strcpy(msgmgr.msg.view, optarg);
                break;
            case 13: // 'zoom'
                msgmgr.msg.zoom = 1;
                break;
            case 14: // 'reload'
                msgmgr.msg.reload = 1;
                break;
            case 15: // 'changespeed'
                tmp = atof(optarg);
                if (tmp >= 1.0 && tmp <= 300.0) {
                  msgmgr.msg.face_change_steps = tmp;
                }
                break;
            case 16: // 'zoomspeed'
                tmp = atof(optarg);
                if (tmp >= 1.0 && tmp <= 300.0) {
                  msgmgr.msg.zoom_steps = tmp;
                }
                break;
            case 17: // 'dontexit'
                msgmgr.msg.disable_exit_after_goto = 1;
                break;
	    case 18: // 'noautofun'
		msgmgr.msg.disable_random_fun = 1;
                break;
	    case 19: // 'revmousewheel'
		msgmgr.msg.reverse_mousewheel = 1;
                break;
	    case 20: // 'swapmousebuttons'
		msgmgr.msg.swap_mousebuttons = 1;
                break;
	    case 21: // 'altmousebuttons'
		msgmgr.msg.alt_mousebuttons = 1;
                break;
            case 22: // 'justswitch'
                msgmgr.msg.mtype = MTYPE_JUSTSWITCH;
                break;
            case 23: // 'version'
                printf("3ddesktop %s (3ddesk client)\nWritten by Brad Wasson.\n\nCopyright (C) 2002 - 2005 Brad Wasson.\n"
                       "This is free software; see the source for copying conditions.  There is NO\n"
                       "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"
                       "This binary compiled %s %s.\n\n",
                       VERSION, __DATE__, __TIME__);
                exit(0);
                break;
            }
            break;
        case 'v':
            verbose = 1;
            break;
        default:
            usage_and_bye();
            break;
        }
    }


    if (msgmgr.open() < 0 || !server_running()) {
        if (msgmgr.msg.mtype == MTYPE_STOP) {
            // already stopped...
            fprintf(stderr, "Server not running.\n");
            exit (1);
        }

        fprintf(stderr, "Attempting to start 3ddesktop server.\n");
  
        if (start_daemon() < 0) {
            fprintf(stderr, "Could not start server.\n"
                    "Try starting manually (3ddeskd)\n\n");
            exit(1);
        }

        if (wait_for_server_to_start() == 0) {
            if (msgmgr.open() < 0) {
                fprintf(stderr, "Can't get message queue: %s\n", strerror(errno));
                fprintf(stderr, "Maybe 3ddeskd server not started?\n");
                exit (1);
            }
        } else {
            fprintf(stderr, "Could not find server.\n"
                    "Try starting manually (3ddeskd)\n\n");
            exit (1);
        }
    }

    if (msgmgr.send() < 0) {
        fprintf(stderr, "Failed to send server a message\n");
        exit (1);
    }

    return 0;
}