void
CContentWindowContainer::DataReceived(const isab::DataGuiMess* aMess,
      const char *aUrl)
{
   list<class CResolveItem*>::iterator it = iReqList.begin();
   if (iBrCtlInterface) {
      class CResolveItem* item = NULL;
      while (it != iReqList.end()) {
         item = *it;
         HBufC* url = WFTextUtil::AllocLC(aUrl);
         if (!url->Find(item->getUrl())) {
            CleanupStack::PopAndDestroy(url);
            iReqList.erase(it);
            DataReceived(item->getLinkContent(), aMess, aUrl);
            delete item;
            return;
         }
         CleanupStack::PopAndDestroy(url);
         it++;
      }
   }
   class CResolveItem* item;
   while (it != iReqList.end()) {
      item = *it;
      it++;
      iReqList.pop_front();
      delete item; 
   }
}
Ejemplo n.º 2
0
int WSocket::ReceiveBuffer()
{
	unsigned int num_read;
	unsigned int num_to_read;

	while(m_num_read<m_read_data_buf_len)
	{
		// Read the data in 4K at a time to avoid the NOBUFS error
		if((m_read_data_buf_len-m_num_read)>4096)
		{
			num_to_read=4096;
		}
		else
		{
			num_to_read=m_read_data_buf_len-m_num_read;
		}

		num_read=Receive(p_read_data_buf+m_num_read,num_to_read);
				
		if(num_read==SOCKET_ERROR)
		{
			int error_code=GetLastError();

			// The assumption is that not all the data was sent if we get a WSAEWOULDBLOCK, and that a later
			// OnReceive will pick the rest of it up when it is sent.
			if(error_code==WSAEWOULDBLOCK)
			{
				return 0;
			}
			else
			{
				return error_code;
			}
		}

		if(num_read==0)	// assume that this is crap
		{
			return SOCKET_ERROR;
		}
		
		m_num_read+=num_read;
	}

	DataReceived(m_num_read);

	return 0;
}
Ejemplo n.º 3
0
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: on_clearButton_clicked(); break;
        case 1: on_getLastTempButton_clicked(); break;
        case 2: on_getTempButton_clicked(); break;
        case 3: on_getTempAllButton_clicked(); break;
        case 4: DataReceived((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 5: ConnectError(); break;
        case 6: timerEvent((*reinterpret_cast< QTimerEvent*(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 8;
    }
    return _id;
}
Ejemplo n.º 4
0
void
TCPPort::OnRead(const boost::system::error_code &ec, size_t nbytes)
{
  if (ec == boost::asio::error::operation_aborted)
    /* this object has already been deleted; bail out quickly without
       touching anything */
    return;

  if (ec) {
    connection.close();
    AsyncAccept();
    StateChanged();
    Error(ec.message().c_str());
    return;
  }

  DataReceived(input, nbytes);

  AsyncRead();
}
Ejemplo n.º 5
0
MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags)
	: QMainWindow(parent, flags)
{
	ui.setupUi(this);
	cntPkt = cntErr = cntWtf = 0;
	QObject::connect(ui.portOpenButton, SIGNAL(clicked()),this, SLOT(openPort()));
	QObject::connect(ui.portCloseButton, SIGNAL(clicked()),this, SLOT(closePort()));
	QObject::connect(ui.nodeSettingsSetButton, SIGNAL(clicked()),this, SLOT(nodeUpdateSettings()));
	QObject::connect(&port, SIGNAL(DataReceived(quint64)),this, SLOT(DataInput(quint64)));
	QObject::connect(&timer, SIGNAL(timeout()),this, SLOT(timeout()));


	QStringList ports = port.EnumeratePorts();
	ports.sort();
	ui.portSelectCombo->insertItems(0, ports);

	nodeUpdateSettings();
	//timer.setInterval(1);//in fact it should be ~230usec
	//port.SetReadTimeout(1);//and still to much
}
Ejemplo n.º 6
0
void
TCPClientPort::OnRead(const boost::system::error_code &ec, size_t nbytes)
{
  if (ec == boost::asio::error::operation_aborted)
    /* this object has already been deleted; bail out quickly without
       touching anything */
    return;

  if (ec) {
    socket.close();
    state = PortState::FAILED;
    StateChanged();
    Error(ec.message().c_str());
    return;
  }

  DataReceived(input, nbytes);

  socket.async_receive(boost::asio::buffer(input, sizeof(input)),
                       std::bind(&TCPClientPort::OnRead, this,
                                 std::placeholders::_1,
                                 std::placeholders::_2));
}
Ejemplo n.º 7
0
void ServerNetwork::readyRead() {
	QTcpSocket *socket = static_cast<QTcpSocket*>(sender());
	u32 clientId = clientManager->GetClient(socket);
	QByteArray *buffer = buffers.value(socket);
	qint32 size = socket->bytesAvailable();

	while (socket->bytesAvailable() > 0) {
		buffer->append(socket->readAll());

		while ((size == 0 && buffer->size() >= 4) || (size > 0 && buffer->size() >= size)) {
			if (size == 0 && buffer->size() >= 4) {
				size = ArrayToInt(buffer->mid(0, 4));
				buffer->remove(0, 4);
			}
			if (size > 0 && buffer->size() >= size) {
				QByteArray data = buffer->mid(0, size);
				buffer->remove(0, size);
				size = 0;

				emit DataReceived(data, clientId);
			}
		}
	}
}
Ejemplo n.º 8
0
void CEMSocket::OnReceive(int nErrorCode)
{
    // the 2 meg size was taken from another place
    static char GlobalReadBuffer[2000000];

    // Check for an error code
    if (nErrorCode != 0)
    {
        OnError(nErrorCode);
        return;
    }

    // Check current connection state
    if (byConnected == ES_DISCONNECTED)
    {
        TRACE("->%s: the sock is disconnected\n",__FUNCTION__);
        return;
    }
    else
    {
        byConnected = ES_CONNECTED; // ES_DISCONNECTED, ES_NOTCONNECTED, ES_CONNECTED
    }

    // CPU load improvement
    if (downloadLimitEnable == true && downloadLimit == 0)
    {
#ifdef _DEBUG_CPU        
		TRACE("->%s: CPU load improvement\n",__FUNCTION__);
#endif
        pendingOnReceive = true;

        //Receive(GlobalReadBuffer + pendingHeaderSize, 0);
        return;
    }

    // Remark: an overflow can not occur here
    uint32 readMax = sizeof(GlobalReadBuffer) - pendingHeaderSize;
    if (downloadLimitEnable == true && readMax > downloadLimit)
    {
        readMax = downloadLimit;
    }

    // We attempt to read up to 2 megs at a time (minus whatever is in our internal read buffer)
    uint32 ret = Receive(GlobalReadBuffer + pendingHeaderSize, readMax);
	GlobalReadBuffer[pendingHeaderSize+ret] = 0;

    if (ret == SOCKET_ERROR || byConnected == ES_DISCONNECTED)
    {
        return;
    }

    // Bandwidth control
    if (downloadLimitEnable == true)
    {
        // Update limit
        downloadLimit -= GetRealReceivedBytes();
    }

    // CPU load improvement
    // Detect if the socket's buffer is empty (or the size did match...)
    pendingOnReceive = m_bFullReceive;

    if (ret == 0)
        return;

    // Copy back the partial header into the global read buffer for processing
    if (pendingHeaderSize > 0)
    {
        memcpy(GlobalReadBuffer, pendingHeader, pendingHeaderSize);
        ret += pendingHeaderSize;
        pendingHeaderSize = 0;
    }

    if (IsRawDataMode())
    {
        DataReceived((BYTE*)GlobalReadBuffer, ret);
        return;
    }

    char *rptr = GlobalReadBuffer; // floating index initialized with begin of buffer
    const char *rend = GlobalReadBuffer + ret; // end of buffer

    // Loop, processing packets until we run out of them
    while ((rend - rptr >= PACKET_HEADER_SIZE) || ((pendingPacket != NULL) && (rend - rptr > 0)))
    {
        // Two possibilities here:
        //
        // 1. There is no pending incoming packet
        // 2. There is already a partial pending incoming packet
        //
        // It's important to remember that emule exchange two kinds of packet
        // - The control packet
        // - The data packet for the transport of the block
        //
        // The biggest part of the traffic is done with the data packets.
        // The default size of one block is 10240 bytes (or less if compressed), but the
        // maximal size for one packet on the network is 1300 bytes. It's the reason
        // why most of the Blocks are splitted before to be sent.
        //
        // Conclusion: When the download limit is disabled, this method can be at least
        // called 8 times (10240/1300) by the lower layer before a splitted packet is
        // rebuild and transferred to the above layer for processing.
        //
        // The purpose of this algorithm is to limit the amount of data exchanged between buffers

        if (pendingPacket == NULL)
        {
            pendingPacket = new Packet(rptr); // Create new packet container.
            rptr += 6;                        // Only the header is initialized so far

            // Bugfix We still need to check for a valid protocol
            // Remark: the default eMule v0.26b had removed this test......
            switch (pendingPacket->prot)
            {
            case OP_EDONKEYPROT:
            case OP_PACKEDPROT:
            case OP_EMULEPROT:
                break;
            default:
                EMTrace("CEMSocket::OnReceive ERROR Wrong header");
                delete pendingPacket;
                pendingPacket = NULL;
                OnError(ERR_WRONGHEADER);
                return;
            }

            // Security: Check for buffer overflow (2MB)
            if (pendingPacket->size > sizeof(GlobalReadBuffer))
            {
                delete pendingPacket;
                pendingPacket = NULL;
                OnError(ERR_TOOBIG);
                return;
            }

            // Init data buffer
            pendingPacket->pBuffer = new char[pendingPacket->size + 1];
            pendingPacketSize = 0;
        }

        // Bytes ready to be copied into packet's internal buffer
        ASSERT(rptr <= rend);
        uint32 toCopy = ((pendingPacket->size - pendingPacketSize) < (uint32)(rend - rptr)) ?
                        (pendingPacket->size - pendingPacketSize) : (uint32)(rend - rptr);

        // Copy Bytes from Global buffer to packet's internal buffer
        memcpy(&pendingPacket->pBuffer[pendingPacketSize], rptr, toCopy);
        pendingPacketSize += toCopy;
        rptr += toCopy;

        // Check if packet is complet
        ASSERT(pendingPacket->size >= pendingPacketSize);
        if (pendingPacket->size == pendingPacketSize)
        {
#ifdef EMSOCKET_DEBUG
            EMTrace("CEMSocket::PacketReceived on %d, opcode=%X, realSize=%d",
                    (SOCKET)this, pendingPacket->opcode, pendingPacket->GetRealPacketSize());
#endif

            // Process packet
            bool bPacketResult = PacketReceived(pendingPacket);
            delete pendingPacket;
            pendingPacket = NULL;
            pendingPacketSize = 0;

            if (!bPacketResult)
                return;
        }
    }

    // Finally, if there is any data left over, save it for next time
    ASSERT(rptr <= rend);
    ASSERT(rend - rptr < PACKET_HEADER_SIZE);
    if (rptr != rend)
    {
        // Keep the partial head
        pendingHeaderSize = rend - rptr;
        memcpy(pendingHeader, rptr, pendingHeaderSize);
    }
}
Ejemplo n.º 9
0
void
SerialPort::Run()
{
  assert(Thread::IsInside());

  DWORD dwBytesTransferred;
  BYTE inbuf[1024];

  // JMW added purging of port on open to prevent overflow
  Flush();

#ifndef _WIN32_WCE
  OverlappedEvent osStatus, osReader;
  if (!osStatus.Defined() || !osReader.Defined())
     // error creating event; abort
     return;
#endif

  // Specify a set of events to be monitored for the port.
  if (is_widcomm)
    SetRxTimeout(180);
  else {
    ::SetCommMask(hPort, EV_RXCHAR);
    SetRxTimeout(0);
  }

  while (!CheckStopped()) {

#ifndef _WIN32_WCE

    WaitResult result = WaitDataPending(osStatus, INFINITE);
    switch (result) {
    case WaitResult::READY:
      break;

    case WaitResult::TIMEOUT:
      continue;

    case WaitResult::FAILED:
    case WaitResult::CANCELLED:
      ::Sleep(100);
      continue;
    }

    int nbytes = GetDataPending();
    if (nbytes <= 0) {
      ::Sleep(100);
      continue;
    }

    // Start reading data

    if ((size_t)nbytes > sizeof(inbuf))
      nbytes = sizeof(inbuf);

    if (!::ReadFile(hPort, inbuf, nbytes, &dwBytesTransferred,
                    osReader.GetPointer())) {
      if (::GetLastError() != ERROR_IO_PENDING) {
        // Error in ReadFile() occured
        ::Sleep(100);
        continue;
      }

      if (osReader.Wait() != OverlappedEvent::FINISHED) {
        ::CancelIo(hPort);
        ::SetCommMask(hPort, 0);
        osReader.Wait();
        continue;
      }

      if (!::GetOverlappedResult(hPort, osReader.GetPointer(),
                                 &dwBytesTransferred, FALSE))
        continue;
    }

#else

    if (is_widcomm) {
      /* WaitCommEvent() doesn't work with the Widcomm Bluetooth
         driver, it blocks for 11 seconds, regardless whether data is
         received.  This workaround polls for input manually.
         Observed on an iPaq hx4700 with WM6. */
    } else {
      // Wait for an event to occur for the port.
      DWORD dwCommModemStatus;
      if (!::WaitCommEvent(hPort, &dwCommModemStatus, 0)) {
        // error reading from port
        Sleep(100);
        continue;
      }

      if ((dwCommModemStatus & EV_RXCHAR) == 0)
        /* no data available */
        continue;
    }

    // Read the data from the serial port.
    if (!ReadFile(hPort, inbuf, 1024, &dwBytesTransferred, NULL) ||
        dwBytesTransferred == 0) {
      Sleep(100);
      continue;
    }
#endif

    DataReceived(inbuf, dwBytesTransferred);
  }

  Flush();
}
Ejemplo n.º 10
0
int NetworkCommunication::LoadNetworkSettings(QString filename)
{
    if(QFile(filename).exists())
    {
        QSettings* settings;
        settings= new QSettings(filename,QSettings::IniFormat);

        if(telegramHandler != NULL)
        {
            delete telegramHandler;
        }

        if(telegramData != NULL)
        {
            delete telegramData;
        }

        if(telegramTrigger != NULL)
        {
            delete telegramTrigger;
        }

        if(telegramStatus != NULL)
        {
            delete telegramStatus;
        }

        if(!CheckIfSettingsExist(settings, "UDPport"))
            return(1);
        UDPport=settings->value("UDPport").toInt();

        telegramHandler = new QCoDeSysNetVarUDP(QHostAddress::Any,UDPport);

        if(!CheckIfSettingsExist(settings, "VariableIndexIonCurrent"))
            return(1);
        variableIndexIonCurrent = settings->value("VariableIndexIonCurrent").toInt();

        if(!CheckIfSettingsExist(settings, "VariableIndexMagneticField"))
            return(1);
        variableIndexMagneticField = settings->value("VariableIndexMagneticField").toInt();

        if(!CheckIfSettingsExist(settings, "DataIonCurrentCoefA"))
            return(1);
        ionCurrentCoefA = settings->value("DataIonCurrentCoefA").toDouble();

        if(!CheckIfSettingsExist(settings, "DataIonCurrentCoefB"))
            return(1);
        ionCurrentCoefB = settings->value("DataIonCurrentCoefB").toDouble();

        if(!CheckIfSettingsExist(settings, "DataIonCurrentCoefC"))
            return(1);
        ionCurrentCoefC = settings->value("DataIonCurrentCoefC").toDouble();


        if(!CheckIfSettingsExist(settings, "VariableIndexTriggerReceived"))
            return(1);
        variableIndexTriggerReceived = settings->value("VariableIndexTriggerReceived").toInt();

        if(!CheckIfSettingsExist(settings, "VariableIndexScanCompleted"))
            return(1);
        variableIndexScanCompleted = settings->value("VariableIndexScanCompleted").toInt();


        if(!CheckIfSettingsExist(settings, "DataMagneticFieldCoefA"))
            return(1);
        magneticFieldCoefA = settings->value("DataMagneticFieldCoefA").toDouble();

        if(!CheckIfSettingsExist(settings, "DataMagneticFieldCoefB"))
            return(1);
        magneticFieldCoefB = settings->value("DataMagneticFieldCoefB").toDouble();

        if(!CheckIfSettingsExist(settings, "DataMagneticFieldCoefC"))
            return(1);
        magneticFieldCoefC = settings->value("DataMagneticFieldCoefC").toDouble();

        telegramData = new QCoDeSysNVT(0);

        if(!CheckIfSettingsExist(settings, "DataTelegramFormat"))
            return(1);
        telegramData->StringToVariableList(settings->value("DataTelegramFormat").toString());

        if(!CheckIfSettingsExist(settings, "DataTelegramCobID"))
            return(1);
        telegramData->setCobId(settings->value("DataTelegramCobID").toInt());

        telegramStatus = new QCoDeSysNVT(0);

        if(!CheckIfSettingsExist(settings, "StatusTelegramFormat"))
            return(1);
        telegramStatus->StringToVariableList(settings->value("StatusTelegramFormat").toString());

        if(!CheckIfSettingsExist(settings, "StatusTelegramCobID"))
            return(1);
        telegramStatus->setCobId(settings->value("StatusTelegramCobID").toInt());


        telegramTrigger = new QCoDeSysNVT(1);

        if(!CheckIfSettingsExist(settings, "TriggerTelegramFormat"))
            return(1);
        telegramTrigger->StringToVariableList(settings->value("TriggerTelegramFormat").toString());

        if(!CheckIfSettingsExist(settings, "TriggerTelegramCobID"))
            return(1);
        telegramTrigger->setCobId(settings->value("TriggerTelegramCobID").toInt());

        if(!CheckIfSettingsExist(settings, "TriggerTelegramValues"))
            return(1);
        telegramTrigger->StringToData(settings->value("TriggerTelegramValues").toString());

        telegramTrigger->setPort(UDPport);
        telegramTrigger->setIP(QHostAddress::Broadcast);

        if(!CheckIfSettingsExist(settings, "VariableIndexScanFrom"))
            return(1);
        variableIndexScanFrom=settings->value("VariableIndexScanFrom").toInt();

        if(!CheckIfSettingsExist(settings, "VariableIndexScanTo"))
            return(1);
        variableIndexScanTo=settings->value("VariableIndexScanTo").toInt();

        if(!CheckIfSettingsExist(settings, "VariableIndexScanTime"))
            return(1);
        variableIndexScanTime=settings->value("VariableIndexScanTime").toInt();


        if(!CheckIfSettingsExist(settings, "VariableIndexSolFrom"))
            return(1);
        variableIndexSolFrom=settings->value("VariableIndexSolFrom").toInt();

        if(!CheckIfSettingsExist(settings, "VariableIndexSolTo"))
            return(1);
        variableIndexSolTo=settings->value("VariableIndexSolTo").toInt();



        if(!CheckIfSettingsExist(settings, "TriggerTimeOut"))
            return(1);
        triggerTimeOut=settings->value("TriggerTimeOut").toInt();



        if(!CheckIfSettingsExist(settings, "ScanTimeOut"))
            return(1);
        scanTimeOut=settings->value("ScanTimeOut").toInt();

        if(!CheckIfSettingsExist(settings, "HeartBeatTimeInterval"))
            return(1);
        heartBeatTimeInterval=settings->value("HeartBeatTimeInterval").toInt();

        connect(telegramData,SIGNAL(updated()),this,SLOT(DataReceived()));
        connect(telegramStatus,SIGNAL(updated()),this,SLOT(StatusReceived()));

        telegramHandler->telegrams.append(telegramStatus);
        telegramHandler->telegrams.append(telegramData);

        return(0);
    }
    else
    {
        qDebug() << "NetworkCommunication::LoadNetworkSettings: File " << filename << " does not exist!";
        return(1);
    }


}
Ejemplo n.º 11
0
  void RoundTest_MultiRound(CreateSessionCallback callback, CreateGroupGenerator cgg)
  {
    Timer::GetInstance().UseVirtualTime();

    int count = Random::GetInstance().GetInt(TEST_RANGE_MIN, TEST_RANGE_MAX);
    int leader = Random::GetInstance().GetInt(0, count);
    int sender0 = Random::GetInstance().GetInt(0, count);
    int sender1 = Random::GetInstance().GetInt(0, count);
    while(sender0 != sender1) {
      sender1 = Random::GetInstance().GetInt(0, count);
    }

    QVector<TestNode *> nodes;
    Group *group;
    ConstructOverlay(count, nodes, group);

    Id leader_id = nodes[leader]->cm.GetId();
    Id session_id;

    CreateSessions(nodes, *group, leader_id, session_id, callback, cgg);

    Library *lib = CryptoFactory::GetInstance().GetLibrary();
    QScopedPointer<Dissent::Utils::Random> rand(lib->GetRandomNumberGenerator());

    QByteArray msg(512, 0);
    rand->GenerateBlock(msg);
    nodes[sender0]->session->Send(msg);

    SignalCounter sc;
    for(int idx = 0; idx < count; idx++) {
      QObject::connect(&nodes[idx]->sink, SIGNAL(DataReceived()), &sc, SLOT(Counter()));
      nodes[idx]->session->Start();
    }

    TestNode::calledback = 0;
    qint64 next = Timer::GetInstance().VirtualRun();
    while(next != -1 && sc.GetCount() < count && TestNode::calledback < count) {
      Time::GetInstance().IncrementVirtualClock(next);
      next = Timer::GetInstance().VirtualRun();
    }

    sc.Reset();

    for(int idx = 0; idx < count; idx++) {
      EXPECT_EQ(msg, nodes[idx]->sink.Last().first);
    }

    rand->GenerateBlock(msg);
    nodes[sender1]->session->Send(msg);

    TestNode::calledback = 0;
    next = Timer::GetInstance().VirtualRun();
    while(next != -1 && sc.GetCount() < count && TestNode::calledback < count * 2) {
      Time::GetInstance().IncrementVirtualClock(next);
      next = Timer::GetInstance().VirtualRun();
    }

    for(int idx = 0; idx < count; idx++) {
      EXPECT_EQ(msg, nodes[idx]->sink.Last().first);
    }

    CleanUp(nodes);
    delete group;
  }
Ejemplo n.º 12
0
void
SerialPort::Run()
{
  assert(Thread::IsInside());

  DWORD dwBytesTransferred;
  BYTE inbuf[1024];

  // JMW added purging of port on open to prevent overflow
  Flush();

  OverlappedEvent osStatus, osReader;
  if (!osStatus.Defined() || !osReader.Defined())
     // error creating event; abort
     return;

  // Specify a set of events to be monitored for the port.
  ::SetCommMask(hPort, EV_RXCHAR);
  SetRxTimeout(0);

  while (!CheckStopped()) {

    WaitResult result = WaitDataPending(osStatus, INFINITE);
    switch (result) {
    case WaitResult::READY:
      break;

    case WaitResult::TIMEOUT:
      continue;

    case WaitResult::FAILED:
    case WaitResult::CANCELLED:
      ::Sleep(100);
      continue;
    }

    int nbytes = GetDataPending();
    if (nbytes <= 0) {
      ::Sleep(100);
      continue;
    }

    // Start reading data

    if ((size_t)nbytes > sizeof(inbuf))
      nbytes = sizeof(inbuf);

    if (!::ReadFile(hPort, inbuf, nbytes, &dwBytesTransferred,
                    osReader.GetPointer())) {
      if (::GetLastError() != ERROR_IO_PENDING) {
        // Error in ReadFile() occured
        ::Sleep(100);
        continue;
      }

      if (osReader.Wait() != OverlappedEvent::FINISHED) {
        ::CancelIo(hPort);
        ::SetCommMask(hPort, 0);
        osReader.Wait();
        continue;
      }

      if (!::GetOverlappedResult(hPort, osReader.GetPointer(),
                                 &dwBytesTransferred, FALSE))
        continue;
    }

    DataReceived(inbuf, dwBytesTransferred);
  }

  Flush();
}