Beispiel #1
0
uInt8 sim_ReadDigitalU8(uInt32 port)
{
	char buff[100];
	char lixo[100];
	uInt32 value;

	sprintf(buff,"%s %02X %02X","ReadDigitalU8", port, 0);
	
	sendMessage(buff);	

	receiveMessage(buff);

	
	sscanf(buff,"%s %02X %02X",lixo, &port, &value);
	return((uInt8) value);
}
Beispiel #2
0
        // Receives a message.
        // The message is represented as a list of byte arrays representing
        // a message's parts. If the message is not a multi-part message the
        // list will only contain one array.
        inline QList<QByteArray> receiveMessage()
        {
            QList<QByteArray> parts;

            ZMQMessage msg;
            while (receiveMessage(&msg))
            {
                parts += msg.toByteArray();
                msg.rebuild();

                if (!hasMoreMessageParts())
                    break;
            }

            return parts;
        }
Beispiel #3
0
// Receive notification that the SSL handshake has completed successfully
void Server::handshakeComplete()
{
  QSslSocket *socket = dynamic_cast<QSslSocket *>(sender());
  assert(socket);

  connect(socket, SIGNAL(disconnected()), this, SLOT(connectionClosed()));
  connect(socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));

  ui->logTextEdit->append(QString("[%1] Accepted connection from %2:%3")
                          .arg(QDateTime::currentDateTime().toString("hh:mm:ss.zzz ap"))
                          .arg(socket->peerAddress().toString())
                          .arg(socket->peerPort()));

  sockets.push_back(socket);
  users.push_back(socket->peerPort());
}
LocalSocketIpcClient::LocalSocketIpcClient(QString remoteServername, QObject *parent) :
        QObject(parent)
{

    m_socket = new QLocalSocket(this);
    m_serverName = remoteServername;

    connect(m_socket, SIGNAL(connected()), this, SLOT(socket_connected()));
    connect(m_socket, SIGNAL(disconnected()), this, SLOT(socket_disconnected()));

    m_socket->connectToServer(m_serverName, QLocalSocket::ReadWrite);

    connect(m_socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));
    connect(m_socket, SIGNAL(error(QLocalSocket::LocalSocketError)),
            this, SLOT(socket_error(QLocalSocket::LocalSocketError)));
}
Beispiel #5
0
NZMQT_INLINE QList<QByteArray> ZMQSocket::receiveMessage(ReceiveFlags flags_)
{
    QList<QByteArray> parts;

    ZMQMessage msg;
    while (receiveMessage(&msg, flags_))
    {
        parts += msg.toByteArray();
        msg.rebuild();

        if (!hasMoreMessageParts())
            break;
    }

    return parts;
}
Beispiel #6
0
Client::Client(QSqlDatabase _db, QString _nick, QString _ip, int _porta, QWidget *parent) :
	QMainWindow(parent)
{
	setupUi(this);
	db = _db;
	nick = _nick;
	ip = _ip;
	porta = _porta;

	personalizza();

	QDesktopWidget *widget = QApplication::desktop();
	QRect dim = widget->screenGeometry();
	setGeometry((dim.width() - width()) / 2, (dim.height() - height()) / 2, width(), height());

	socket = new QTcpSocket(this);
	buffer = new QBuffer(this);
	buffer->open(QIODevice::ReadWrite);

	connect(socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));
	connect(actionStatistiche, SIGNAL(triggered()), this, SLOT(mostraStatistiche()));
	connect(pushButtonG1C1, SIGNAL(clicked()), this, SLOT(cliccataCarta1()));
	connect(pushButtonG1C2, SIGNAL(clicked()), this, SLOT(cliccataCarta2()));
	connect(pushButtonG1C3, SIGNAL(clicked()), this, SLOT(cliccataCarta3()));
	connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errore(QAbstractSocket::SocketError)));

	socket->connectToHost(ip, porta);

	sendMessage("00" + nick + "|");

	// inizializza il vettore di puntatori a metodi
	metodo[0] = &Client::settaNickServer;
	metodo[1] = &Client::settaBriscola;
	metodo[2] = &Client::settaCarta;
	metodo[3] = &Client::settaNumCarte;
	metodo[4] = &Client::settaTurno;
	metodo[5] = &Client::settaCartaServer;
	metodo[6] = &Client::pulisciTavolo;
	metodo[7] = &Client::aggiornaPunti;
	metodo[8] = &Client::ultimaMano;
	metodo[9] = &Client::disabilitaCarte;
	metodo[10] = &Client::stabilisciVincitore;
	metodo[11] = &Client::attivaColorazione;
	metodo[12] = &Client::aggiustaMazzo;
	metodo[13] = &Client::serverAbbandonato;
}
Beispiel #7
0
void sendMessage(uint8_t send_list) {
  uint8_t i, tries, channel, send_mask;

  // send to only good channels
  send_list &= ALL_GOOD_CHANNELS;
    
  
  for (tries=TX_TRIES; tries>0; tries--) {

    handshake_retry_addition = (tries * RETRY_INCREMENT);

    //trying to make it do the sendMessage more times on failed channels
    send_mask = 0x01;
    for (channel=1; channel<=MAX_CHANNELS; channel++) {
      uint8_t good_tx = TRUE;
      if (send_list & send_mask) {
	//putnum_ud(channel);
	/*
	 * Check if the line to transmit on is already being used.
	 * If so, receive the message and then carry on.
	 */
	if (pollClockLine(channel) == 0) {
	  receiveMessage(channel);
	}
	for (i=0; i<num_bytes_in_tx_msg_buff; i++) {
	  if (sendByte(tx_msg_buff[i], channel) == FALSE) {
	    //the message was not received.
	    //mark this channel not to be cleared from sendList so it can be resent later.
	    good_tx = FALSE;
	    break;
	  }
	  else
	    good_tx = TRUE;
	}
      }
      if (good_tx == TRUE) {
	send_list &= ~send_mask;  //tx was good. clear the bit from sendList to avoid resending
      }
      send_mask <<= 1; // try sending to the next channel
    }
  }
  // update goodChannels to remove channels that did not succeed
  // this works because sendList keeps track of which channels have not received the message yet.
  good_channels &= ~send_list;
  num_bytes_in_tx_msg_buff = 0;
}
void * recebedorDados(void * lixo){
	char message[MAXSIZE];

	while(true){
		receiveMessage(fdSocket,message,sizeof(int));
		if((rand()%100)<95 ){
			printf("recebeu %s \n",message);
			if((rand()%100)<90 ){
				sendMessage(fdSocket,message,sizeof(int)); //Envia mensagem
				printf("confirmou %s \n",message);
			}else{
				printf("falha na confirmação\n");
			}
		}
	}
	printf("acabou recebedor \n");
}
/**
 * Execute a transaction with a Jaguar that gets some property.
 * 
 * Jaguar always generates a message with the same message ID when replying.
 * 
 * @param messageID The messageID to read from the CAN bus (device number is added internally)
 * @param data The up to 8 bytes of data that was received with the message
 * @param dataSize Indicates how much data was received
 */
void CANJaguar::getTransaction(UINT32 messageID, UINT8 *data, UINT8 *dataSize)
{
	UINT32 targetedMessageID = messageID | m_deviceNumber;
	INT32 status = 0;

	// Make sure we don't have more than one transaction with the same Jaguar outstanding.
	semTake(m_transactionSemaphore, WAIT_FOREVER);

	// Send the message requesting data.
	status = sendMessage(targetedMessageID, NULL, 0);
	wpi_assertCleanStatus(status);
	// Wait for the data.
	status = receiveMessage(&targetedMessageID, data, dataSize);
	wpi_assertCleanStatus(status);

	// Transaction complete.
	semGive(m_transactionSemaphore);
}
Beispiel #10
0
void Client::listMails() {
    std::string message = "LIST\n";

    sendReceive(message);	// status message
    receiveMessage(message);	// data

    if (message.length() == 3) {	// = ".CRLF"
        std::cout << "No new messages" << std::endl;
        return;
    }

    if (shortMessage) {
        // remove last dot + CRLF
        message.erase( message.length() - 3, 3);
    }

    std::cout << message;
}
Beispiel #11
0
    Message::Result Scene::sendMessage(const Message& message)
    {
        if (message.passFilter(getID()))
        {
            if ((message.passFilter(Message::Scene) || (this == &Engine::getSharedScene() && message.passFilter(Message::SharedScene))))
            {
                if (receiveMessage(message) == Message::Result::Escape)
                    return Message::Result::Escape;
            }
        }

        const unsigned short objectField = Message::Object | Message::Component;

        if (message.passFilter(objectField) && Object::sendMessage(message) == Message::Result::Escape)
            return Message::Result::Escape;

        return Message::Result::Continue;
    }
Beispiel #12
0
Application::Application(int &argc, char *argv[])
    : QApplication(argc, argv)
    , d_ptr(new ApplicationPrivate)
{
    Q_D(Application);

    d->isRunning = false;
    d->sharedMemory.setKey(GUI_APPLICATION_SHARED_MEMORY_KEY);

    if (d->sharedMemory.attach()) {
        d->isRunning = true;
    } else {
        if (!d->sharedMemory.create(1))
            return;
        connect(&d->localServer, SIGNAL(newConnection()), SLOT(receiveMessage()));
        d->localServer.listen(GUI_APPLICATION_SHARED_MEMORY_KEY);
    }
}
Beispiel #13
0
//--------------------------------------------------------------
void ofApp::update(){
	if (client.isConnected() && started) {
		vector<ofxJSONElement> elements = receiveMessage();

		for (int i = 0; i < elements.size(); i++) {
			ofxJSONElement element = new ofxJSONElement();

			element = elements[i];

			//if data frame
			for (Json::ArrayIndex i = 0; i < element["DATA"].size(); i++) {
				//get element at index i
				ofxJSONElement sub = elements[i]["DATA"][i];
				//display value type and timestamp
				cout << "received " << sub["ID"].asString() << " at " << sub["Timestamp"].asFloat() << " ";

				//end line
				cout << endl;

				//store eeg values				
				if (sub["ID"].asString() == "eeg_alpha") fitEegData(sub, eegAlpha);
				if (sub["ID"].asString() == "eeg_beta") fitEegData(sub, eegBeta);
				if (sub["ID"].asString() == "eeg_theta") fitEegData(sub, eegTheta);

				//store eda values				
				if (sub["ID"].asString() == "eda_tonic") fitEdaData(sub, edaFasic);
				if (sub["ID"].asString() == "eda_fasic") fitEdaData(sub, edaTonic);

				//store ecg values
				if (sub["ID"].asString() == "ecg_hr") ecg = sub["Values"][0].asFloat();
				
			}
			if (element["STATUS"].asString() == "OK") {
				//if request accepted
				started = true;
				cout << "start request accepted." << endl;
			}
			else if (element["STATUS"].asString() == "Error") {
				//error in the server when receiving the message
				ofLogError(element["MSG"].asString());
			}
		}
	}	
}
Beispiel #14
0
Socket::Socket(std::string const &serv, int port)
{
  struct protoent	*pe;
  struct sockaddr_in	sockaddr;
  socklen_t		socksize;
  int			sock;
  int			okay;

  pe = getprotobyname("TCP");
  socksize = sizeof(struct sockaddr);
  if ((sock = socket(AF_INET, SOCK_STREAM, pe->p_proto)) == -1)
    {
      std::cerr << "Socket creation failed." << std::endl;
      exit(2);
    }
  sockaddr.sin_family = AF_INET;
  sockaddr.sin_port = htons(port);
  sockaddr.sin_addr.s_addr = inet_addr(serv.c_str());
  if ((connect(sock, reinterpret_cast<const struct sockaddr *>(&sockaddr), socksize)) != 0)
    {
      std::cerr << "Socket connection failed." << std::endl;
      exit(3);
    }
  m_sock = sock;
  m_fds.fd = m_sock;
  m_fds.events = POLLIN;
  okay = 0;
  if (toRead())
    {
      okay = 1;
      if (receiveMessage() != "BIENVENUE")
	okay = 0;
    }
  if (okay)
    {
      m_okay = true;
      sendMessage("GRAPHIC");
    }
  else
    {
      m_okay = false;
      std::cerr << "\'BIENVENUE\' not received..." << std::endl << "Exiting ..." << std::endl;
    }
}
Beispiel #15
0
//This does the actual sending of the message
//modifies: nothing
//effects: send message in the Q_tx_msg_buff on the channel
//NOTE: This method does NOT mess with or consider anything having to do with the channelQueuesArray at all
uint8_t rbSendMessageHelper(uint8_t channel, uint8_t message[], uint8_t messageLength) {
  if (channel <= 0 || channel > MAX_CHANNELS) {
    //putstring("\nINVALID CHANNEL PASSED TO rbSendMessageHelper:  ");  putnum_uh(channel);
    while (1) {
      blinkRed(14);
      blinkOrange(14);
    }
  }
  
  disableRTC2();
  
  if (pollClockLine(channel) == 0) {
    //putstring("\n about to ATTEMPT TO RECEIVE BEFORE SENDING on channel: "); putnum_ud(channel);
    ReceiveMessagePacket incomingPacket = receiveMessage(channel);
    if (incomingPacket.messageLength != 0) {
      //valid message, but it in the pending processing buffer
      //putstring("\nReceived Message before sending on channel "); putnum_ud(channel);
      //putstring("   Adding message to process pending queue");
      addProcessPendingMsg(incomingPacket);
    }
  }
  
  uint8_t i;
  uint8_t good_tx = TRUE;
  for (i = 0; i < messageLength; i++) {
    if (sendByte(message[i], channel) == FALSE) {
      //the message was not received.
      //putstring("failed to send a byte");
      good_tx = FALSE;
      break;
       }
    else
      good_tx = TRUE;

    refreshChannel(channel); //able to send at least 1 byte
  }
  
  /*if (channel == 1 && !good_tx)
   {
   putstring("\nch1 send failure\n");
   }*/
  enableRTC2();
  return good_tx;
}
Beispiel #16
0
 ReceiveMessageResponse*
 SQSConnection::receiveMessage (const std::string &aQueueUrl,
                                int aNumberOfMessages,
                                int aVisibilityTimeout,
                                bool aDecode) {
   ParameterMap lMap;
   if (aNumberOfMessages != 0) {
       std::stringstream s;
       s << aNumberOfMessages;
       lMap.insert (ParameterPair ("MaxNumberOfMessages", s.str()));
     }
   if (aVisibilityTimeout > -1) {
       std::stringstream s;
       s << aVisibilityTimeout;
       lMap.insert (ParameterPair ("VisibilityTimeout", s.str()));
     }
 
   return receiveMessage (aQueueUrl, lMap, aDecode);
 } 
Beispiel #17
0
int OsPooledTask::run(void* pArg)
{
  while (!_isTerminated)
  {
    OsMsg* pMsg = 0;
    
    if (OS_SUCCESS == receiveMessage((OsMsg*&) pMsg) && pMsg)
    {
      if (!_isTerminated)
      {
        if (_synchronizeHandler)
        {
          mutex_lock lock(_mutex);
          handleMessage(*pMsg);
        }
        else
        {
          handleMessage(*pMsg);
        }
      }
    }
    else
    {
      break;
    }

    //
    // Check if the request is a shutdown message
    //
    if (pMsg->getMsgType() == OsMsg::OS_SHUTDOWN)
    {
      if (!pMsg->getSentFromISR())
       pMsg->releaseMsg();
      break;
    }
    else if (!pMsg->getSentFromISR())
    {
       pMsg->releaseMsg();  // free the message
    }
  }
  _isTerminated = true;
  return 0;
}
Beispiel #18
0
void ClientInterface::waitUntilReady(Checksum* checksum){
	
	NetworkMessageReady networkMessageReady;
	Chrono chrono;

	chrono.start();

	//send ready message
	sendMessage(&networkMessageReady);

	//wait until we get a ready message from the server
	while(true){
		
		NetworkMessageType networkMessageType= getNextMessageType();

		if(networkMessageType==nmtReady){
			if(receiveMessage(&networkMessageReady)){
				break;
			}
		}
		else if(networkMessageType==nmtInvalid){
			if(chrono.getMillis()>readyWaitTimeout){
				throw runtime_error("Timeout waiting for server");
			}
		}
		else{
			throw runtime_error("Unexpected network message: " + intToStr(networkMessageType) );
		}

		// sleep a bit
		sleep(waitSleepTime);
	}

	//check checksum
	if(Config::getInstance().getBool("NetworkConsistencyChecks")){
		if(networkMessageReady.getChecksum()!=checksum->getSum()){
			throw runtime_error("Checksum error, you don't have the same data as the server");
		}
	}

	//delay the start a bit, so clients have nore room to get messages
	sleep(GameConstants::networkExtraLatency);
}
Beispiel #19
0
Slave::Slave( const Ipc::Id &masterId, const Ipc::Id &slaveId ) :
	QTcpSocket(),
	m_slaveId( slaveId ),
	m_pingTimer( this ),
	m_lastPingResponse( QTime::currentTime() )
{
	connect( this, SIGNAL( readyRead() ),
				this, SLOT( receiveMessage() ) );
	connect( this, SIGNAL( error( QAbstractSocket::SocketError ) ),
				QCoreApplication::instance(), SLOT( quit() ) );

	m_pingTimer.setInterval( 1000 );
	connect( &m_pingTimer, SIGNAL( timeout() ),
				this, SLOT( masterPing() ) );
	connect( this, SIGNAL( connected() ),
				&m_pingTimer, SLOT( start() ) );

	connectToHost( QHostAddress::LocalHost, masterId.toInt() );
}
Beispiel #20
0
void Summoners::on_btn_login_clicked()
{
    quint32 port = ui.edit_port->text().toUInt();
    QHostAddress addr(ui.edit_addr->text());

    Socket = new QTcpSocket;
    Socket->connectToHost(addr, port);

    connect(Socket, SIGNAL(connected()), this, SLOT(processConnection()));
    connect(Socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));

    timer_heart = startTimer(1000);		//假设每秒1次心跳。不同的游戏,心跳间隔不一样。

    QByteArray datagram;
    QDataStream iStream(&datagram, QIODevice::WriteOnly);
    iStream.setByteOrder(QDataStream::LittleEndian);
    iStream << CS_Login;
    Socket->write(datagram);
}
Beispiel #21
0
changepassword::changepassword(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::changepassword)
{
    ui->setupUi(this);
    setWindowTitle("Change Password");
    changesocket = new QTcpSocket(this);
    buffer = new QBuffer(this);
    buffer->open(QIODevice::ReadWrite);

    connect(changesocket, SIGNAL(readyRead()), SLOT(receiveMessage()));
    connect(this, SIGNAL(connectworked(QString*)), SLOT(sendMessage(QString*)));
    connect(this, SIGNAL(logconnect()), SLOT(toggleConnection()));
    connect(this, SIGNAL(receivedthis(string)), this , SLOT(checkiftrue(string)));


    this->connect(ui->submit,SIGNAL(clicked()), this, SLOT(changepass()));
    this->connect(ui->cancel,SIGNAL(clicked()), this, SLOT(cancel()));
}
Beispiel #22
0
EchoThread::~EchoThread()
{
  // Try to get any messages left on the line
  try
  {
    while(true)
      receiveMessage();
  }
  catch(std::logic_error&)
  {
    // A logic error is thrown when receive is called with nothing to receive
    // This is just to make sure we clear out the whole queue
  }

  // If this runs out of space, oh well
  sendReplies();

  LogInfo("Echo thread performed " << m_iterationCount << " iterations");
}
Beispiel #23
0
Application::Application() :
    moteDataHolder(*this),
    window(NULL, *this),
    sdataWidget(NULL, *this) ,    
    dataRecorder(*this) ,
    connectWidget(NULL, *this)
{
    window.resize(800,400);
    window.show();

    //sdataWidget.show();

    sdataWidget.initLeft(false);

    connect(&moteDataHolder, SIGNAL(loadFinished()), &window, SLOT(onLoadFinished()));    
    connect(&moteDataHolder, SIGNAL(sampleAdded(int)), &window, SLOT(onOnlineSampleAdded(int)));
    connect(&serialListener, SIGNAL(receiveMessage(ActiveMessage)), &moteDataHolder, SLOT(createSampleFromOnline(ActiveMessage)), Qt::DirectConnection);

}
NO_RETURN void SeccompBroker::runLoop(int socket)
{
#ifndef NDEBUG
    int i = STDERR_FILENO + 1;
#else
    int i = 0;
#endif
    // Close all inherited file descriptors other
    // than the socket to the sandboxed process.
    for (; i < FD_SETSIZE; ++i)
        if (i != socket)
            close(i);

    while (true) {
        char buffer[messageMaxSize];
        ssize_t receivedBytes = receiveMessage(socket, &buffer, sizeof(buffer));
        if (receivedBytes == -EINTR)
            continue;

        if (receivedBytes <= 0)
            exit(receivedBytes ? EXIT_FAILURE : EXIT_SUCCESS);

        auto decoder = std::make_unique<IPC::ArgumentDecoder>((const uint8_t*) buffer, receivedBytes);
        std::unique_ptr<Syscall> syscall = Syscall::createFromDecoder(decoder.get());
        if (!syscall)
            exit(EXIT_FAILURE);

        std::unique_ptr<SyscallResult> result = syscall->execute(m_policy);
        if (!result)
            exit(EXIT_FAILURE);

        auto encoder = std::make_unique<IPC::ArgumentEncoder>();
        encoder->encode(*result);

        Vector<IPC::Attachment> attachments = encoder->releaseAttachments();
        int fd = attachments.size() == 1 ? attachments[0].fileDescriptor() : -1;

        // The client is down, the broker should go away.
        if (sendMessage(socket, encoder->buffer(), encoder->bufferSize(), fd) < 0)
            exit(EXIT_SUCCESS);
    }
}
Beispiel #25
0
/*!
    Creates of sungle application object
    \param argc Nuber of command line arguments
    \param argv Array of command line argwuments
    \param uniqueKey String key fo unicue shared data indefier
 */
SingleApp::SingleApp(int& argc, char* argv[], const QString keyString) : QApplication(argc, argv), uniqueKey(keyString)
{
        sharedMemory.setKey(uniqueKey);
        if (sharedMemory.attach())
                runned = true;
        else
        {
                runned = false;
                // create shared memory.
                if (!sharedMemory.create(1))
                {
                        qDebug("Unable to create single instance.");
                        return;
                }
                // create local server and listen to incomming messages from other instances.
                localServer = new QLocalServer(this);
                connect(localServer, SIGNAL(newConnection()), this, SLOT(receiveMessage()));
                localServer->listen(uniqueKey);
        }
}
bool SessionManager::parseMessageItem(QTreeWidgetItem *item)
{
    QMap<QString, QString> info = getAttrList(item);

    /*jid(node@domain/resource)*/
    QString jid = info["from"];
    QString message;

    for(int k=0; k<item->childCount(); k++)
    {
        if(item->child(k)->text(0) == "body")
        {
            message.append(item->child(k)->text(1));
            status = MESSAGE;
        }//end if
    }//end for

    emit receiveMessage(jid, message);
    return true;
}
Beispiel #27
0
NZMQT_INLINE void SocketNotifierZMQSocket::socketWriteActivity()
{
    socketNotifyWrite_->setEnabled(false);

    try
    {
        while (isConnected() && (events() & EVT_POLLIN))
        {
            const QList<QByteArray> & message = receiveMessage();
            emit messageReceived(message);
        }
    }
    catch (const ZMQException& ex)
    {
        qWarning("Exception during write: %s", ex.what());
        emit notifierError(ex.num(), ex.what());
    }

    socketNotifyWrite_->setEnabled(true);
}
	void storeFile(ClientThreadResource * res , ListenSocket * clientSocket){
		int result = 0;
		DWORD bytesRead , position;
		char * readBuffer = (char *)allocateMemory( res->heapHandler , FILE_CHUNK );
		HANDLE newFile = getFileHandle(res->argument);

		_tprintf("====> Llego al STOR...\n");

		position = SetFilePointer(newFile, 0 , NULL , FILE_END);
		LockFile(newFile, position , 0 , strlen(readBuffer) , 0);
			
		do {
			readBuffer = receiveMessage(clientSocket , res->heapHandler , &result);
		    position = SetFilePointer(newFile, 0 , NULL , FILE_END);
			WriteFile(newFile, readBuffer , strlen(readBuffer) , &bytesRead , NULL);
		} while( readBuffer > 0 );
			
		UnlockFile(newFile , position , 0 , strlen(readBuffer) , 0);
		CloseHandle(newFile);
	}
Beispiel #29
0
bool MAVLink::getIDFromHeartbeat() {
	std::map<std::string,MAVLinkMessage>::iterator it;
	for (int i = 0; i<1000; i++) {
		receiveMessage();
		for (it = MessageMapIn.begin(); it != MessageMapIn.end(); it++) {
			int s, c, k = -1;
			sscanf((it->first).c_str(),"%d:%d %d", &s, &c, &k);
			if (k == 0) {
				this->targetSystemId = s;
				this->targetComponentId = c;
				return true;
			}
		}
		Sleep(10);
	}

	this->targetSystemId = -1;
	this->targetComponentId = -1;
	return false;
}
static void *networkThread(void *args) {
	thread_args *a = (thread_args *)args;
	char *msg;
	mqueue_enqueue(a->dispEvents, "Network thread started", 23 * sizeof(char));

	while (1) {
		receiveMessage(a->sock, &msg);
		msg_command *mc = malloc(sizeof(msg_command));
		if (mc == NULL) {
			fprintf(stderr, "Error allocating memory\n");
			exit(1);
		}
		mc->source = MSG_OUTGOING;
		mc->command = msg;
		mqueue_enqueue(a->events, (void *)mc, sizeof(msg_command));
		free(mc);
		free(msg);
	}

	return NULL;
}