Exemple #1
0
/*
 * Clipboard change event slot and timeout for performing actions
 */
void ImodClipboard::clipboardChanged()
{
  if (Imod_debug) {
    QClipboard *cb = QApplication::clipboard();
    //cb->setSelectionMode(false);
    QString text = cb->text();
    imodPrintStderr("imodHCM in clipboardChanged - clipboard = %s\n", 
                    LATIN1(text));
    if (ImodInfoWin)
      wprint("clipboardChanged = %s\n", LATIN1(text));
  }
  // If already handling a change or the message is not for us, return
  if (mHandling || !handleMessage())
    return;

  // Otherwise create and start a timer to execute the action
  // Set flag because event comes in twice in Windows
  mHandling = true;
  QTimer::singleShot(10, this, SLOT(clipTimeout()));
}
// Removes the link between the "outPortIdx" port of the "rFrom"
// resource and its downstream counterpart. If the flow graph is not
// "started", this call takes effect immediately.  Otherwise, the call
// takes effect at the start of the next frame processing interval.
// Returns OS_SUCCESS if the link is removed.  Returns
// OS_INVALID_ARGUMENT if the caller specified an invalid port index.
OsStatus MpFlowGraphBase::removeLink(MpResource& rFrom, int outPortIdx)
{
   OsWriteLock    lock(mRWMutex);

   UtlBoolean      handled;
   MpFlowGraphMsg msg(MpFlowGraphMsg::FLOWGRAPH_REMOVE_LINK, NULL,
                      &rFrom, NULL, outPortIdx);

   if (outPortIdx < 0 || outPortIdx >= rFrom.maxOutputs())
      return OS_INVALID_ARGUMENT;

   if (mCurState == STARTED)
      return postMessage(msg);

   handled = handleMessage(msg);
   if (handled)
      return OS_SUCCESS;
   else
      return OS_UNSPECIFIED;
}
void BatchMessageHandler::handleMessage(QtMsgType type, const QString &description, const QUrl &identifier, const QSourceLocation &sourceLocation)
{
  QString title;
  switch (type)
  {
    case QtDebugMsg:
      title = tr("Information");
      break;
    case QtWarningMsg:
      title = tr("Warning");
      break;
    case QtCriticalMsg:
    case QtFatalMsg:
    default:
      title = tr("Error");
      break;
  }

  handleMessage(type, title, description, identifier, sourceLocation);
}
void LimeSDROutputGUI::handleInputMessages()
{
    Message* message;

    while ((message = m_inputMessageQueue.pop()) != 0)
    {
        if (DSPSignalNotification::match(*message))
        {
            qDebug("LimeSDROutputGUI::handleInputMessages: message: %s", message->getIdentifier());
            DSPSignalNotification* notif = (DSPSignalNotification*) message;
            m_sampleRate = notif->getSampleRate();
            m_deviceCenterFrequency = notif->getCenterFrequency();
            qDebug("LimeSDROutputGUI::handleInputMessages: DSPSignalNotification: SampleRate: %d, CenterFrequency: %llu", notif->getSampleRate(), notif->getCenterFrequency());
            updateSampleRateAndFrequency();

            delete message;
        }
        else if (LimeSDROutput::MsgConfigureLimeSDR::match(*message))
        {
            const LimeSDROutput::MsgConfigureLimeSDR& cfg = (LimeSDROutput::MsgConfigureLimeSDR&) *message;
            m_settings = cfg.getSettings();
            displaySettings();

            delete message;
        }
        else if (LimeSDROutput::MsgStartStop::match(*message))
        {
            LimeSDROutput::MsgStartStop& notif = (LimeSDROutput::MsgStartStop&) *message;
            blockApplySettings(true);
            ui->startStop->setChecked(notif.getStartStop());
            blockApplySettings(false);
            delete message;
        }
        else
        {
            if (handleMessage(*message)) {
                delete message;
            }
        }
    }
}
Exemple #5
0
	void RgAnalyser::HandleErrorMsg (GstMessage *msg)
	{
		GError *gerror = nullptr;
		gchar *debug = nullptr;
		gst_message_parse_error (msg, &gerror, &debug);

		const auto& msgStr = QString::fromUtf8 (gerror->message);
		const auto& debugStr = QString::fromUtf8 (debug);

		const auto code = gerror->code;
		const auto domain = gerror->domain;

		g_error_free (gerror);
		g_free (debug);

		qWarning () << Q_FUNC_INFO
				<< domain
				<< code
				<< msgStr
				<< debugStr;


		if (IsDraining_)
			return;

		IsDraining_ = true;
		const auto bus = gst_pipeline_get_bus (GST_PIPELINE (Pipeline_));
		while (const auto msg = gst_bus_timed_pop (bus, 0.01 * GST_SECOND))
			handleMessage (std::shared_ptr<GstMessage> (msg, gst_message_unref));
		IsDraining_ = false;

		gst_element_set_state (Pipeline_, GST_STATE_NULL);
		PopThread_->Resume ();

		const auto trackInfoPos = std::find_if (Result_.Tracks_.begin (), Result_.Tracks_.end (),
				[this] (const TrackRgResult& info) { return info.TrackPath_ == CurrentPath_; });
		if (trackInfoPos == Result_.Tracks_.end ())
			Result_.Tracks_.append ({ CurrentPath_, 0, 0 });

		CheckFinish ();
	}
Exemple #6
0
void CPanasonicNode::Do_Work()
{
	m_Busy = true;
	if (DEBUG_LOGGING) _log.Log(LOG_NORM, "Panasonic Plugin: (%s) Entering work loop.", m_Name.c_str());
	int	iPollCount = 9;

	while (!m_stoprequested)
	{
		sleep_milliseconds(500);

		iPollCount++;
		if (iPollCount >= 10)
		{
			iPollCount = 0;
			try
			{
				std::string _volReply;
				std::string _muteReply;
				_volReply = handleWriteAndRead(buildXMLStringRendCtl("Get", "Volume"));
				if (_volReply != "ERROR")
				{
					m_CurrentStatus.Volume(handleMessage(_volReply));
				}

				//_muteReply = handleWriteAndRead(buildXMLStringRendCtl("Get", "Mute"));
				//_log.Log(LOG_NORM, "Panasonic Plugin: (%s) Mute reply - \r\n", m_Name.c_str(), _muteReply.c_str());
				//if (_muteReply != "ERROR")
				//{
				//	m_CurrentStatus.Muted((handleMessage(_muteReply)==0) ? false : true);
				//}
				UpdateStatus();
			}
			catch (std::exception& e)
			{
				_log.Log(LOG_ERROR, "Panasonic Plugin: (%s) Exception: %s", m_Name.c_str(), e.what());
			}
		}
	}
	_log.Log(LOG_NORM, "Panasonic Plugin: (%s) Exiting work loop.", m_Name.c_str());
	m_Busy = false;
}
Exemple #7
0
void doKNX(int l)
{
	int i,out;
	struct msgform msg;

	if(knxGateways[l].enabled)
		knxGateways[l].status='1'; //connecting
	printf("trying to connect to knx %s %d\n",
		knxGateways[l].address,knxGateways[l].port);

	knxGateways[l].sockfd=doConnectKnx(l);
	printf("address %s, port %d, knx connected\n",knxGateways[l].address, knxGateways[l].port);

	i=0;
	do
	{
		out=operateKnx(knxGateways[l].sockfd,l,2);

		if(out==-1)
		{
			handleMessage(0,0,knxGateways[l].id_knx_gateway,0,"GATEWAY DISCONNECTED",0,-1);

			knxGatewayDisconnected(l);
			close(knxGateways[l].sockfd);
			knxGateways[l].sockfd=-1;
			if(knxGateways[l].enabled)
			{
				printf("error in %s %d\nsleeping 5 seconds\n",knxGateways[l].address,knxGateways[l].port);
				sleep(5);
				printf("trying to connect\n");
			}
			knxGateways[l].sockfd=doConnectKnx(l);
			printf("address %s port %d, knx connected\n",knxGateways[l].address, knxGateways[l].port);
		}
		else
			knxGateways[l].status='0';	//connected
		i=(i+1)%2;
		usleep(50000);	//intervallo interrogazione scheda
	}
	while(1);
}
void handlePacket(TPacket *packet)
{
	switch(packet->packetType)
	{
		case PACKET_TYPE_COMMAND:
				// Only we send command packets, so ignore
			break;

		case PACKET_TYPE_RESPONSE:
				handleResponse(packet);
			break;

		case PACKET_TYPE_ERROR:
				handleErrorResponse(packet);
			break;

		case PACKET_TYPE_MESSAGE:
				handleMessage(packet);
			break;
	}
}
Exemple #9
0
ProcessThread::ProcessThread(const AudioFileModel &audioFile, const QString &outputDirectory, const QString &tempDirectory, AbstractEncoder *encoder, const bool prependRelativeSourcePath)
:
	m_audioFile(audioFile),
	m_outputDirectory(outputDirectory),
	m_tempDirectory(tempDirectory),
	m_encoder(encoder),
	m_jobId(QUuid::createUuid()),
	m_prependRelativeSourcePath(prependRelativeSourcePath),
	m_renamePattern("<BaseName>"),
	m_aborted(false)
{
	if(m_mutex_genFileName)
	{
		m_mutex_genFileName = new QMutex;
	}

	connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
	connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);

	m_currentStep = UnknownStep;
}
Exemple #10
0
int
main(int argc, char *argv[])
{
  if(argc != 3){
    fprintf(stderr,"usage: server <portnum> <filename>\n");
    exit(0);
  }
  
  int port = atoi(argv[1]);

  
  sprintf(file, argv[2]);

  sd = UDP_Open(port);
  assert(sd > -1);
  
  serverInit(file);
  memLoad();
  printf("waiting in loop\n");
  while (1) {
    //use this to get the socket address
    struct sockaddr_in y;
    s = y;
    char buffer[sizeof(msg_t)];
    int rc = UDP_Read(sd, &s, buffer, sizeof(msg_t));
 
    //figure out what kind of message this is - read, write, lookup etc
    //when done go ahead and reply to it
	
    if (rc > 0) {
      // char reply[BUFFER_SIZE];
      //sprintf(reply, "reply");
      handleMessage (buffer);
      //need a message struct casted as a char []
      rc =  UDP_Write(sd, &s, buffer, sizeof(msg_t));
    }
  }

  return 0;
}
void TcpConnection::run() {

	while (!shouldStop) {
		int networkOrderMessageSize;
		int readSize = recv(connectionSocket, &networkOrderMessageSize,
				sizeof(int), 0);
		int messageSize = ntohl(networkOrderMessageSize);
		if (readSize == 4) {
			if (messageSize > 0 && messageSize < 8192) { //We won't handle messages bigger than 8KB
				char* message = new char[messageSize + 1];
				message[messageSize] = '\0'; //Make it a cstring
				readSize = recv(connectionSocket, message, messageSize, 0);
				if (readSize == messageSize) {
					handleMessage(message);
				} else {
					logError("Connection error. Closing connection...");
					shouldStop = true;
					delete[] message;
				}
			} else {
				logError(
						"Received illegal message: Message to big\nClosing connection...");
				shouldStop = true;
			}
		} else if (readSize < 0) {
			logError("Connection error. Closing connection...");
			shouldStop = true;
		} else { //(readSize == 0)
			logDebug("Connection closed");
			shouldStop = true;
		}
	}

	shutdown(connectionSocket, SHUT_RDWR);
	connectionSocket = 0;
	connectionOpen = false;
	shouldStop = false;
	server->connectionClosed(this);
}
void SingleIRCNetworkPlugin::handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &/*xhtml*/) {
	if (m_sessions[user] == NULL) {
		LOG4CXX_WARN(logger, user << ": Message received for unconnected user");
		return;
	}

	// handle PMs
	std::string r = legacyName;
	if (legacyName.find("/") == std::string::npos) {
		r = legacyName.substr(0, r.find("@"));
	}
	else {
		r = legacyName.substr(legacyName.find("/") + 1);
	}

	LOG4CXX_INFO(logger, user << ": Forwarding message to " << r);
	m_sessions[user]->sendCommand(IrcCommand::createMessage(FROM_UTF8(r), FROM_UTF8(message)));

	if (r.find("#") == 0) {
		handleMessage(user, legacyName, message, TO_UTF8(m_sessions[user]->nickName()));
	}
}
/**
 * @brief Called when new data is received on the associated socket, if sufficient data is available, it will call the virtual method handleMessage(int)
 */
void AbstractProtocol::newData()
{
    if (!active) {
        return;
    }

    qDebug() << "**** Start data ****";

    while (1) {


        qDebug() << "new data total size: " << socket->bytesAvailable();
        if (!headerRead) {
            if (socket->bytesAvailable() < SIZE_HEADER) {
                break;
            } else {
                header.read(socket);
                headerRead = true;
                qDebug() << "size: " << header.data.size;
                qDebug() << "Type: " << header.data.type;
            }
        }


        if (socket->bytesAvailable() < header.data.size) {
            break;
        }

        headerRead = false;
        int type = header.data.type;
        handleMessage(type);
        if (finishedReading()) {
            break;
        }
    }

    qDebug() << "**** End data *****";

}
Exemple #14
0
/**
 * Feeds serial data in CmdMessenger
 */
void CmdMessenger::feedinSerialData()
{
    while ( !pauseProcessing && comms->available() )
	{	   
		// The Stream class has a readBytes() function that reads many bytes at once. On Teensy 2.0 and 3.0, readBytes() is optimized. 
		// Benchmarks about the incredible difference it makes: http://www.pjrc.com/teensy/benchmark_usb_serial_receive.html

		size_t bytesAvailable = min(comms->available(),MAXSTREAMBUFFERSIZE);
		comms->readBytes(streamBuffer, bytesAvailable); 
		
		// Process the bytes in the stream buffer, and handles dispatches callbacks, if commands are received
		for (size_t byteNo = 0; byteNo < bytesAvailable ; byteNo++) 
		{   
		    int messageState = processLine(streamBuffer[byteNo]);

			// If waiting for acknowledge command
			if ( messageState == kEndOfMessage ) 
			{
				handleMessage();
			}
		}
	}
}
void SDRdaemonSinkGui::handleInputMessages()
{
    Message* message;

    while ((message = m_inputMessageQueue.pop()) != 0)
    {
        if (DSPSignalNotification::match(*message))
        {
            DSPSignalNotification* notif = (DSPSignalNotification*) message;
            m_sampleRate = notif->getSampleRate();
            qDebug("SDRdaemonSinkGui::handleInputMessages: DSPSignalNotification: SampleRate:%d, CenterFrequency:%llu", notif->getSampleRate(), notif->getCenterFrequency());
            updateSampleRate();

            delete message;
        }
        else
        {
            if (handleMessage(*message)) {
                delete message;
            }
        }
    }
}
Exemple #16
0
void recieveFromGS(void)
{
    ssize_t recsize;
    socklen_t fromlen;
    uint8_t udpInBuf[BUFFER_LENGTH];
    memset(udpInBuf, 0, BUFFER_LENGTH);

    recsize = recvfrom(sock, (void *)udpInBuf, BUFFER_LENGTH, 0, (SOCKADDR *)&locGSAddr, SOCKLEN_T_INT(&fromlen));
    if (recsize > 0) {
        MW_TRACE("\n")MW_TRACE(" <-- udp in GS <--\n")
        mavlink_message_t msgIn;
        mavlink_status_t status;
        for (int i = 0; i < recsize; ++i) {
            if (mavlink_parse_char(MAVLINK_COMM_0, udpInBuf[i], &msgIn, &status)) {
                // Packet received
                if (mavlinkState->verbose) {
                    printf("\nReceived packet: SYS: %d, COMP: %d, LEN: %d, MSG ID: %d\n", msgIn.sysid, msgIn.compid, msgIn.len, msgIn.msgid);
                }
                handleMessage(&msgIn);
            }
        }
    }
}
Exemple #17
0
/**
 * Receive data from UART.
 */
static void *receiveloop(void *arg)
{
	int uart_fd = *((int*)arg);

	const int timeout = 1000;
	uint8_t ch;

	mavlink_message_t msg;

	prctl(PR_SET_NAME, "mavlink uart rcv", getpid());

	while (!thread_should_exit) {

		if (mavlink_exit_requested) break;

		struct pollfd fds[] = { { .fd = uart_fd, .events = POLLIN } };

		if (poll(fds, 1, timeout) > 0) {
			/* non-blocking read until buffer is empty */
			int nread = 0;

			do {
				nread = read(uart_fd, &ch, 1);

				if (mavlink_parse_char(chan, ch, &msg, &status)) { //parse the char
					/* handle generic messages and commands */
					handleMessage(&msg);

					/* Handle packet with waypoint component */
					mavlink_wpm_message_handler(&msg, &global_pos, &local_pos);

					/* Handle packet with parameter component */
					mavlink_pm_message_handler(MAVLINK_COMM_0, &msg);
				}
			} while (nread > 0);
		}
	}
void MessageManager::onPrivateMessage(const ChatMessagePtr& aMessage) {
	bool myPM = aMessage->getReplyTo()->getUser() == ClientManager::getInstance()->getMe();
	const UserPtr& user = myPM ? aMessage->getTo()->getUser() : aMessage->getReplyTo()->getUser();
	size_t wndCnt;
	{
		WLock l(cs);
		wndCnt = chats.size();
		auto i = chats.find(user);
		if (i != chats.end()) {
			i->second->handleMessage(aMessage); //We should have a listener in the frame
			return;
		}
	}

	auto c = aMessage->getFrom()->getClient();
	if (wndCnt > 200 || (!myPM && isIgnoredOrFiltered(aMessage, c.get(), true))) {
		DisconnectCCPM(user);
		return;
	}

	const auto& identity = aMessage->getReplyTo()->getIdentity();
	if ((identity.isBot() && !SETTING(POPUP_BOT_PMS)) || (identity.isHub() && !SETTING(POPUP_HUB_PMS))) {
		c->Message(STRING(PRIVATE_MESSAGE_FROM) + " " + identity.getNick() + ": " + aMessage->format());
		return;
	}

	auto chat = addChat(HintedUser(user, aMessage->getReplyTo()->getClient()->getHubUrl()), true);
	chat->handleMessage(aMessage);

	if (AirUtil::getAway() && (!SETTING(NO_AWAYMSG_TO_BOTS) || !user->isSet(User::BOT))) {
		ParamMap params;
		aMessage->getFrom()->getIdentity().getParams(params, "user", false);

		string error;
		chat->sendMessage(AirUtil::getAwayMessage(c->get(HubSettings::AwayMsg), params), error, false);
	}
}
void *read_input(void *socket)
{
	int n, read_size;
        int sock = *(int *)socket;

   	bzero(buffer,256);

   while ((n = read(sock,buffer,255 )) > 1)
   {

   //printf("Register N:%d\n",n);

   if (n < 0)
      {
      perror("ERROR reading from socket");
      exit(1);
      }
   // printf("Here is the message: %s\n",buffer);

   // Parsing input string
   pthread_mutex_lock(&lock);
   handleMessage(buffer, sock);
   pthread_mutex_unlock(&lock);
   /*printf("--------------------------------------------------------\n");
   printStatus();
   printf("--------------------------------------------------------\n");
   */
	/* Write a response to the client */
   n = write(sock,"I got your message",20);
   bzero(buffer,256);
   if (n < 0)
      {
      perror("ERROR writing to socket");
      //exit(1);
      }
   }
}
void ProtoClientConnection::readData()
{
	_receiveBuffer += _socket->readAll();

	// check if we can read a message size
	if (_receiveBuffer.size() <= 4)
	{
		return;
	}

	// read the message size
	uint32_t messageSize =
			((_receiveBuffer[0]<<24) & 0xFF000000) |
			((_receiveBuffer[1]<<16) & 0x00FF0000) |
			((_receiveBuffer[2]<< 8) & 0x0000FF00) |
			((_receiveBuffer[3]    ) & 0x000000FF);

	// check if we can read a complete message
	if ((uint32_t) _receiveBuffer.size() < messageSize + 4)
	{
		return;
	}

	// read a message
	proto::HyperionRequest message;
	if (!message.ParseFromArray(_receiveBuffer.data() + 4, messageSize))
	{
		sendErrorReply("Unable to parse message");
	}

	// handle the message
	handleMessage(message);

	// remove message data from buffer
	_receiveBuffer = _receiveBuffer.mid(messageSize + 4);
}
Exemple #21
0
// The entry point for the task.
// This method executes a message processing loop until either
// requestShutdown(), deleteForce(), or the destructor for this object
// is called.
int OsServerTask::run(void* pArg)
{
   OsMsg*    pMsg = NULL;
   OsStatus  res;

   do
   {
      res = receiveMessage((OsMsg*&) pMsg);          // wait for a message
      assert(res == OS_SUCCESS);

      if (!handleMessage(*pMsg))                  // process the message
      {
         OsServerTask::handleMessage(*pMsg);
      }

      if (!pMsg->getSentFromISR())
      {
         pMsg->releaseMsg();                         // free the message
      }
   }
   while (isStarted());

   return 0;        // and then exit
}
/**
 * \brief arrival of a new message to be handled
 *
 */
void eveMessageChannel::newQueuedMessage()
{
	bool fastEmpty = true, normalEmpty = true;
	eveMessage * message;

	recLock.lockForWrite();
	if ((fastEmpty=receiveFastMessageList.isEmpty())) normalEmpty=receiveMessageList.isEmpty();
	recLock.unlock();

	while ((!fastEmpty) || (!normalEmpty)){
		recLock.lockForWrite();
		if (!fastEmpty)
			message = receiveFastMessageList.takeFirst();
		else
			message = receiveMessageList.takeFirst();
		recLock.unlock();

		handleMessage(message);

		recLock.lockForWrite();
		if ((fastEmpty=receiveFastMessageList.isEmpty())) normalEmpty=receiveMessageList.isEmpty();
		recLock.unlock();
	}
}
Exemple #23
0
UDTTest::UDTTest(int& argc, char** argv) :
    QCoreApplication(argc, argv)
{
    qInstallMessageHandler(LogHandler::verboseMessageHandler);
    
    parseArguments();
    
    // randomize the seed for packet size randomization
    srand(time(NULL));

    _socket.bind(QHostAddress::AnyIPv4, _argumentParser.value(PORT_OPTION).toUInt());
    qDebug() << "Test socket is listening on" << _socket.localPort();
    
    if (_argumentParser.isSet(TARGET_OPTION)) {
        // parse the IP and port combination for this target
        QString hostnamePortString = _argumentParser.value(TARGET_OPTION);
        
        QHostAddress address { hostnamePortString.left(hostnamePortString.indexOf(':')) };
        quint16 port { (quint16) hostnamePortString.mid(hostnamePortString.indexOf(':') + 1).toUInt() };
        
        if (address.isNull() || port == 0) {
            qCritical() << "Could not parse an IP address and port combination from" << hostnamePortString << "-" <<
                "The parsed IP was" << address.toString() << "and the parsed port was" << port;
            
            QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
        } else {
            _target = HifiSockAddr(address, port);
            qDebug() << "Packets will be sent to" << _target;
        }
    }
    
    if (_argumentParser.isSet(PACKET_SIZE)) {
        // parse the desired packet size
        _minPacketSize = _maxPacketSize = _argumentParser.value(PACKET_SIZE).toInt();
        
        if (_argumentParser.isSet(MIN_PACKET_SIZE) || _argumentParser.isSet(MAX_PACKET_SIZE)) {
            qCritical() << "Cannot set a min packet size or max packet size AND a specific packet size.";
            QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
        }
    } else {
        
        bool customMinSize = false;
        
        if (_argumentParser.isSet(MIN_PACKET_SIZE)) {
            _minPacketSize = _argumentParser.value(MIN_PACKET_SIZE).toInt();
            customMinSize = true;
        }
        
        if (_argumentParser.isSet(MAX_PACKET_SIZE)) {
            _maxPacketSize = _argumentParser.value(MAX_PACKET_SIZE).toInt();
            
            // if we don't have a min packet size we should make it 1, because we have a max
            if (customMinSize) {
                _minPacketSize = 1;
            }
        }
        
        if (_maxPacketSize < _minPacketSize) {
            qCritical() << "Cannot set a max packet size that is smaller than the min packet size.";
            QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
        }
    }
    
    if (_argumentParser.isSet(MAX_SEND_BYTES)) {
        _maxSendBytes = _argumentParser.value(MAX_SEND_BYTES).toInt();
    }
    
    if (_argumentParser.isSet(MAX_SEND_PACKETS)) {
        _maxSendPackets = _argumentParser.value(MAX_SEND_PACKETS).toInt();
    }
    
    if (_argumentParser.isSet(UNRELIABLE_PACKETS)) {
        _sendReliable = false;
    }

    if (_argumentParser.isSet(ORDERED_PACKETS)) {
        _sendOrdered = true;
    }
    
    if (_argumentParser.isSet(MESSAGE_SIZE)) {
        if (_argumentParser.isSet(ORDERED_PACKETS)) {
            static const double BYTES_PER_MEGABYTE = 1000000;
            _messageSize = (int) _argumentParser.value(MESSAGE_SIZE).toInt() * BYTES_PER_MEGABYTE;
            
            qDebug() << "Message size for ordered packet sending is" << QString("%1MB").arg(_messageSize / BYTES_PER_MEGABYTE);
        } else {
            qWarning() << "message-size has no effect if not sending ordered - it will be ignored";
        }
    }
    
    
    // in case we're an ordered sender or receiver setup our random number generator now
    static const int FIRST_MESSAGE_SEED = 742272;
    
    int messageSeed = FIRST_MESSAGE_SEED;
    
    if (_argumentParser.isSet(MESSAGE_SEED)) {
        messageSeed = _argumentParser.value(MESSAGE_SEED).toInt();
    }
    
    // seed the generator with a value that the receiver will also use when verifying the ordered message
    _generator.seed(messageSeed);
    
    if (!_target.isNull()) {
        sendInitialPackets();
    } else {
        // this is a receiver - in case there are ordered packets (messages) being sent to us make sure that we handle them
        // so that they can be verified
        _socket.setMessageHandler(
            [this](std::unique_ptr<udt::Packet> packet) {
                auto messageNumber = packet->getMessageNumber();
                auto it = _pendingMessages.find(messageNumber);

                if (it == _pendingMessages.end()) {
                    auto message = std::unique_ptr<Message>(new Message { messageNumber, packet->readAll() });
                    message->data.reserve(_messageSize);
                    if (packet->getPacketPosition() == udt::Packet::ONLY) {
                        handleMessage(std::move(message));
                    } else {
                        _pendingMessages[messageNumber] = std::move(message);
                    }
                } else {
                    auto& message = it->second;
                    message->data.append(packet->readAll());

                    if (packet->getPacketPosition() == udt::Packet::LAST) {
                        handleMessage(std::move(message));
                        _pendingMessages.erase(it);
                    }
                }

        });
    }
    _socket.setMessageFailureHandler(
        [this](HifiSockAddr from, udt::Packet::MessageNumber messageNumber) {
            _pendingMessages.erase(messageNumber);
        }
    );
    
    // the sender reports stats every 100 milliseconds, unless passed a custom value
    
    if (_argumentParser.isSet(STATS_INTERVAL)) {
        _statsInterval = _argumentParser.value(STATS_INTERVAL).toInt();
    }
    
    QTimer* statsTimer = new QTimer(this);
    connect(statsTimer, &QTimer::timeout, this, &UDTTest::sampleStats);
    statsTimer->start(_statsInterval);
}
Exemple #24
0
void defaultMessageHandler(QtMsgType type, const char *msg)
{
    handleMessage(type, msg, false);
}
Exemple #25
0
void debugMessageHandler(QtMsgType type, const char *msg)
{
    handleMessage(type, msg, true);
}
Exemple #26
0
TEST(handleMessage, reloadConfig_shall_be_called_on_timeout) {
    SUBSTITUTE(time, fake_time);
    SUBSTITUTE(reloadConfig, mock_reloadConfig);
    handleMessage(Message());
    EXPECT_EQ(reloadConfigCalled, true);
}
/*
 * Class:     sun_nio_ch_SctpChannelImpl
 * Method:    receive0
 * Signature: (ILsun/nio/ch/SctpResultContainer;J*Z)I
 */
JNIEXPORT jint JNICALL Java_sun_nio_ch_SctpChannelImpl_receive0
  (JNIEnv *env, jclass klass, jint fd, jobject resultContainerObj,
   jlong address, jint length, jboolean peek) {
    SOCKADDR sa;
    int sa_len = sizeof(sa);
    ssize_t rv = 0;
    jlong *addr = jlong_to_ptr(address);
    struct iovec iov[1];
    struct msghdr msg[1];
    char cbuf[CMSG_SPACE(sizeof (struct sctp_sndrcvinfo))];
    int flags = peek == JNI_TRUE ? MSG_PEEK : 0;

    /* Set up the msghdr structure for receiving */
    memset(msg, 0, sizeof (*msg));
    msg->msg_name = &sa;
    msg->msg_namelen = sa_len;
    iov->iov_base = addr;
    iov->iov_len = length;
    msg->msg_iov = iov;
    msg->msg_iovlen = 1;
    msg->msg_control = cbuf;
    msg->msg_controllen = sizeof(cbuf);
    msg->msg_flags = 0;

    do {
        if ((rv = recvmsg(fd, msg, flags)) < 0) {
            if (errno == EWOULDBLOCK) {
                return IOS_UNAVAILABLE;
            } else if (errno == EINTR) {
                return IOS_INTERRUPTED;

#ifdef __linux__
            } else if (errno == ENOTCONN) {
                /* ENOTCONN when EOF reached */
                rv = 0;
                /* there will be no control data */
                msg->msg_controllen = 0;
#endif /* __linux__ */

            } else {
                handleSocketError(env, errno);
                return 0;
            }
        }

        if (msg->msg_flags & MSG_NOTIFICATION) {
            char *bufp = (char*)addr;
            union sctp_notification *snp;
            jboolean allocated = JNI_FALSE;

            if (rv > SCTP_NOTIFICATION_SIZE) {
                JNU_ThrowInternalError(env, "should not reach here");
                return -1;
            }

            if (!(msg->msg_flags & MSG_EOR) && length < SCTP_NOTIFICATION_SIZE) {
                char* newBuf;
                int rvSAVE = rv;

                if ((newBuf = malloc(SCTP_NOTIFICATION_SIZE)) == NULL) {
                    JNU_ThrowOutOfMemoryError(env, "Out of native heap space.");
                    return -1;
                }
                allocated = JNI_TRUE;

                memcpy(newBuf, addr, rv);
                iov->iov_base = newBuf + rv;
                iov->iov_len = SCTP_NOTIFICATION_SIZE - rv;
                if ((rv = recvmsg(fd, msg, flags)) < 0) {
                    handleSocketError(env, errno);
                    return 0;
                }
                bufp = newBuf;
                rv += rvSAVE;
            }
#ifdef __sparc
              else if ((intptr_t)addr & 0x3) {
                /* the given buffer is not 4 byte aligned */
                char* newBuf;
                if ((newBuf = malloc(SCTP_NOTIFICATION_SIZE)) == NULL) {
                    JNU_ThrowOutOfMemoryError(env, "Out of native heap space.");
                    return -1;
                }
                allocated = JNI_TRUE;

                memcpy(newBuf, addr, rv);
                bufp = newBuf;
            }
#endif
            snp = (union sctp_notification *) bufp;
            if (handleNotification(env, fd, resultContainerObj, snp, rv,
                                   (msg->msg_flags & MSG_EOR),
                                   (struct sockaddr*)&sa ) == JNI_TRUE) {
                /* We have received a notification that is of interest to
                   to the Java API. The appropriate notification will be
                   set in the result container. */
                if (allocated == JNI_TRUE) {
                    free(bufp);
                }
                return 0;
            }

            if (allocated == JNI_TRUE) {
                free(bufp);
            }

            // set iov back to addr, and reset msg_controllen
            iov->iov_base = addr;
            iov->iov_len = length;
            msg->msg_control = cbuf;
            msg->msg_controllen = sizeof(cbuf);
        }
    } while (msg->msg_flags & MSG_NOTIFICATION);

    handleMessage(env, resultContainerObj, msg, rv,
            (msg->msg_flags & MSG_EOR), (struct sockaddr*)&sa);
    return rv;
}
Exemple #28
0
	void VkAccount::handleMessage (const MessageInfo& info)
	{
		handleMessage ({}, info);
	}
void aComboBox::update()
{
	if ( showWindow )
	{
		aObject::update();
		
		if (userInput->isLeftClick())
		{
			int cx = userInput->getMouseX();
			int cy = userInput->getMouseY();

			if (expandButton.pointInside(cx, cy)) {
				handleMessage(aMSG_BUTTONCLICKED, (unsigned long)(&expandButton));
			}

			// lose focus if appropriate
			else if ( ListBox().isShowing() && 
				( !pointInside( userInput->getMouseX(), userInput->getMouseY() )
				|| (  ListBox().pointInside(userInput->getMouseX(), userInput->getMouseY() ) )
				&& !ListBox().pointInScrollBar(userInput->getMouseX(), userInput->getMouseY()) ) )
			{
				listBox.showGUIWindow(false);
				rects[2].showGUIWindow(false);
			}
		}
		if (0 <= ListBox().GetSelectedItem())
		{
			selectionIndex = ListBox().GetSelectedItem();

			aListItem *pListItem = ListBox().GetItem(selectionIndex);
			aTextListItem *pTextListItem = dynamic_cast<aTextListItem *>(pListItem);
			if (0 != pTextListItem)
			{
				entry.setEntry(pTextListItem->getText());
			}
			if ( pListItem )
			{
				
				if (listBox.isShowing())
				{
					listBox.showGUIWindow(false);
					rects[2].showGUIWindow(false);
				}

				if ( getParent() )
					getParent()->handleMessage( aMSG_SELCHANGED, ID );
			}
			ListBox().SelectItem(-1);
		}
		else if (listBox.isShowing())
		{
			if (userInput->getKeyDown( KEY_RETURN ) )
			{
				listBox.showGUIWindow(false);
				rects[2].showGUIWindow(false);
			}
		}
	}

	ListBox().setHelpID( helpID );
}
Exemple #30
0
//--------------------------------------------------------------
void ofApp::update(){
    
    if( sendMessages )
    {
        // check for waiting messages
        
        //----8001----
        while(receiver8001.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8001.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8002----
        while(receiver8002.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8002.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8003----
        while(receiver8003.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8003.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8004----
        while(receiver8004.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8004.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8005----
        while(receiver8005.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8005.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8006----
        while(receiver8006.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8006.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8007----
        while(receiver8007.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8007.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8008----
        while(receiver8008.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8008.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8009----
        while(receiver8009.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8009.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8010----
        while(receiver8010.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8010.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8011----
        while(receiver8011.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8011.getNextMessage(&mess);
            
            handleMessage(mess);
        }
        
        //----8012----
        while(receiver8012.hasWaitingMessages()){
            // get the next message
            ofxOscMessage mess;
            receiver8012.getNextMessage(&mess);
            
            handleMessage(mess);
        }
    }
}