Пример #1
0
void labPort::read()
{
    if( _closing )
    {
        return;
    }

    if( _minBytesRead == -10 )
    {
        while( _port.canReadLine() )
        {
            emit dataReceived( _port.readLine() );
        }
    }
    else
    {
        while( _port.bytesAvailable() >= _minBytesRead
               && _port.bytesAvailable() > 0 )
        {
            if( _minBytesRead > 0 )
            {
                int bytesRead = _port.read( _buffer, _minBytesRead );
                emit dataReceived( QByteArray( _buffer, bytesRead ) );
            }
            else
            {
                emit dataReceived( _port.readAll() );
            }
        }
    }
}
Пример #2
0
    void DBClientCursor::requestMore() {
        verify( cursorId && batch.pos == batch.nReturned );

        if (haveLimit) {
            nToReturn -= batch.nReturned;
            verify(nToReturn > 0);
        }
        BufBuilder b;
        b.appendNum(opts);
        b.appendStr(ns);
        b.appendNum(nextBatchSize());
        b.appendNum(cursorId);

        Message toSend;
        toSend.setData(dbGetMore, b.buf(), b.len());
        auto_ptr<Message> response(new Message());

        if ( _client ) {
            _client->call( toSend, *response );
            this->batch.m = response;
            dataReceived();
        }
        else {
            verify( _scopedHost.size() );
            ScopedDbConnection conn(_scopedHost);
            conn->call( toSend , *response );
            _client = conn.get();
            this->batch.m = response;
            dataReceived();
            _client = 0;
            conn.done();
        }
    }
Пример #3
0
void DBClientCursor::requestMore() {
    assert( cursorId && pos == nReturned );

    if (haveLimit) {
        nToReturn -= nReturned;
        assert(nToReturn > 0);
    }
    BufBuilder b;
    b.append(opts);
    b.append(ns.c_str());
    b.append(nextBatchSize());
    b.append(cursorId);

    Message toSend;
    toSend.setData(dbGetMore, b.buf(), b.len());
    auto_ptr<Message> response(new Message());

    if ( connector ) {
        connector->call( toSend, *response );
        m = response;
        dataReceived();
    }
    else {
        assert( _scopedHost.size() );
        ScopedDbConnection conn( _scopedHost );
        conn->call( toSend , *response );
        connector = conn.get();
        m = response;
        dataReceived();
        connector = 0;
        conn.done();
    }
}
Пример #4
0
qint64 LimitedNodeList::readDatagram(QByteArray& incomingPacket, QHostAddress* address = 0, quint16 * port = 0) {
    qint64 result = getNodeSocket().readDatagram(incomingPacket.data(), incomingPacket.size(), address, port);

    SharedNodePointer sendingNode = sendingNodeForPacket(incomingPacket);
    if (sendingNode) {
        emit dataReceived(sendingNode->getType(), incomingPacket.size());
    } else {
        emit dataReceived(NodeType::Unassigned, incomingPacket.size());
    }

    return result;
}
Пример #5
0
void medPacsDataSource::onPacsMove( const QVector<medMoveCommandItem>& cmdList)
{
    medPacsMover* mover = new medPacsMover(cmdList);
    connect(mover, SIGNAL(import(QString)), this, SIGNAL(dataReceived(QString)));
    medJobManager::instance()->registerJobItem(mover, tr("Moving"));
    QThreadPool::globalInstance()->start(mover);
}
Пример #6
0
void QtNetworkReplyThreadSafeProxy::localForwardData()
{
    if (m_reply->bytesAvailable()) {
        QByteArray data = m_reply->read(m_reply->bytesAvailable());
        emit dataReceived(data);
    }
}
Пример #7
0
void YAQSProxy::processPendingDatagrams()
{
    while (udpSocket.hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket.pendingDatagramSize());
        udpSocket.readDatagram(datagram.data(), datagram.size());
        QList<QByteArray> LstData = datagram.split('|');

        switch(LstData[0].toInt())
        {
        case ModuleType::IO:
            IO_dperc_WheelPos = LstData[1].toDouble();
            IO_dperc_ThrottlePos = LstData[2].toDouble();
            break;
        case ModuleType::SYSTEMS:
            SYST_kmhSpeed = LstData[1].toDouble();
            SYST_rpmEngine = LstData[2].toDouble();
            SYST_degmn_Latitude = LstData[3].toDouble();
            SYST_degmn_Longitude = LstData[4].toDouble();
            SYST_deg_Heading = LstData[5].toDouble();
            break;
        }

        emit dataReceived();
    }
}
Пример #8
0
// This function is going to use uIP's protosockets to handle the connection.
// This means it must return int, because of the way the protosockets work.
// In a nutshell, when a PSOCK_* macro needs to wait for something, it will
// return from handle_connection so that other work can take place.  When the
// event is triggered, uip_callback() will call this function again and the
// switch() statement (see below) will take care of resuming execution where
// it left off.  It *looks* like this function runs from start to finish, but
// that's just an illusion to make it easier to code :-)
int
UIPClient::handle_connection(uip_tcp_appstate_t *s)
{
  // All protosockets must start with this macro.  Its internal implementation
  // is that of a switch() statement, so all code between PSOCK_BEGIN and
  // PSOCK_END is actually inside a switch block.  (This means for example,
  // that you can't declare variables in the middle of it!)

  struct psock *p = &s->p;
  uip_userdata_t *u = (uip_userdata_t *) s->user;

  PSOCK_BEGIN(p);

    if (uip_newdata() && readyToReceive(s))
      {
        PSOCK_READBUF_LEN(p, 0); //TODO check what happens when there's more new data incoming than space left in UIPClients buffer (most likely this is just discarded, isn't it?)
        dataReceived(s);
      }

    if (readyToSend(s))
      {
        PSOCK_SEND(p, u->out_buffer, u->out_len);
        dataSent(s);
      }

    if (isClosed(s))
      {
        // Disconnect.
        PSOCK_CLOSE(p);
      }

    // All protosockets must end with this macro.  It closes the switch().
  PSOCK_END(p);
}
Пример #9
0
void Server::readyRead()
{
  QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
  QByteArray* buffer = buffers.value(socket);
  qint32* s = sizes.value(socket);
  qint32 size = *s;
  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));
        *s = size;
        buffer->remove(0, 4);
      }
      if(size > 0 && buffer->size() >= size)
      {
        QByteArray data = buffer->mid(0, size);
        buffer->remove(0, size);
        size = 0;
        *s = size;
        emit dataReceived(socket, data);
      }
    }
  }
}
Пример #10
0
void MainResourceLoader::didFinishLoading(double finishTime)
{
    // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
    // See <rdar://problem/6304600> for more details.
#if !USE(CF)
    ASSERT(!defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_documentLoader->frame()));
#endif

    // The additional processing can do anything including possibly removing the last
    // reference to this object.
    RefPtr<MainResourceLoader> protect(this);
    RefPtr<DocumentLoader> dl = documentLoader();

#if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
    if (m_filter) {
        int length;
        const char* data = wkFilterDataComplete(m_filter, &length);
        WebFilterEvaluator *filter = m_filter;
        // Remove this->m_filter early so didReceiveData doesn't see it.
        m_filter = 0;
        if (data)
            dataReceived(m_resource.get(), data, length);
        wkFilterRelease(filter);
    }
#endif

    if (m_loadingMultipartContent)
        dl->maybeFinishLoadingMultipartContent();

    documentLoader()->timing()->setResponseEnd(finishTime ? finishTime : (m_timeOfLastDataReceived ? m_timeOfLastDataReceived : monotonicallyIncreasingTime()));
    documentLoader()->finishedLoading();

    dl->applicationCacheHost()->finishedLoadingMainResource();
}
Пример #11
0
TcpClientSocket::TcpClientSocket(QObject *parent,int port)
{
    connect(this,SIGNAL(readyRead()),this,SLOT(dataReceived()));
//    connect(this,SIGNAL(sendtoall(QString)),this,SLOT(dataReceived(QString)));
    connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
    isfirst=port;
}
Пример #12
0
    void
    RTMPSession::streamStatusChanged(StreamStatus_t status)
    {
        if(status & kStreamStatusConnected && m_state < kClientStateConnected) {
            setClientState(kClientStateConnected);
        }
        if(status & kStreamStatusReadBufferHasBytes) {
            dataReceived();
        }
        if(status & kStreamStatusWriteBufferHasSpace) {
            if(m_state < kClientStateHandshakeComplete) {
                handshake();
            } else {
                
#ifdef __APPLE__
                dispatch_semaphore_signal(m_networkWaitSemaphore);
#else 
                m_networkMutex.unlock();
                m_networkCond.notify_one();
#endif
            }
        }
        if(status & kStreamStatusEndStream) {
            setClientState(kClientStateNotConnected);
        }
        if(status & kStreamStatusErrorEncountered) {
            setClientState(kClientStateError);
        }
    }
Пример #13
0
void NetworkConnection::continueReceive()
{
	if (closed || sendError)	// Close if anything is wrong
	{
		close();
	}
	else
	{
		bufferInfo.buf = (char*)receiveBuffer;	// Set buffer data
		bufferInfo.len = BUFFER_SIZE;
	
										// 0 means send completed instantly
		if (WSARecv(connection, &bufferInfo, 1, &bytesReceived, 
			&flags, &receiveOverlapped, NULL) == 0) 
		{
			dataReceived();	// Wait for more data
		}
		else
		{
			if (WSAGetLastError() == WSA_IO_PENDING) // Data is pending
			{		// Send a wait handle to the WinAPI thread pool
				RegisterWaitForSingleObject(&newWaitHandle, 
					receiveOverlapped.hEvent, 
					DataReceivedCallback, 
					this, INFINITE, WT_EXECUTEONLYONCE);
			}
			else
			{
				close();
			}
		}
	}
}
Пример #14
0
void Widget::on_pushButton_2_clicked()
{
    QString ipAddress = "127.0.0.1";
    int port = 8010;

    if(!status)
    {
        tcpSocket = new QTcpSocket(this);
        connect(tcpSocket, SIGNAL(connected()),
        this, SLOT(tcpConnected()));
        connect(tcpSocket, SIGNAL(disconnected()),
        this, SLOT(tcpDisconnected()));
        connect(tcpSocket, SIGNAL(readyRead()),
        this, SLOT(dataReceived()));
        tcpSocket->connectToHost(ipAddress, port);
        status = true;
    }
    else
    {
        int length = 0;
        QString message = userName + tr(":Leave Chat Room");
        length = tcpSocket->write(message.toLatin1(), message.length());

        if(length != message.length())
        {
            return;
        }

        tcpSocket->disconnectFromHost();
        status = false;
    }
}
Пример #15
0
QString ClientThread::waitForName()
{
    // Wait for the connecting client to send its username
    QDataStream in(connection);
    in.setVersion(QDataStream::Qt_4_0);

    QString name;

    connection->waitForReadyRead(5000);

    quint16 blockSize = 0;
    while (connection->bytesAvailable() < (int)sizeof(quint16));

    in >> blockSize;

    while (connection->bytesAvailable() < blockSize);

    quint8 type;
    in >> type;
    in >> name;

    connect(connection, SIGNAL(readyRead()), this, SLOT(dataReceived()));

    username = name;

    qDebug() << name << "connected and sent username";

    return name;
}
Пример #16
0
 void
 RTMPSession::streamStatusChanged(StreamStatus_t status)
 {
     if(status & kStreamStatusConnected && m_state < kClientStateConnected) {
         setClientState(kClientStateConnected);
     }
     if(status & kStreamStatusReadBufferHasBytes) {
         dataReceived();
     }
     if(status & kStreamStatusWriteBufferHasSpace) {
         if(m_state < kClientStateHandshakeComplete) {
             handshake();
         } else if (!m_ending) {
             m_jobQueue.enqueue([this]() {
                 this->write(nullptr, 0);
             });
         }
     }
     if(status & kStreamStatusEndStream) {
         setClientState(kClientStateNotConnected);
     }
     if(status & kStreamStatusErrorEncountered) {
         setClientState(kClientStateError);
     }
 }
Пример #17
0
FSActionTaskModel::FSActionTaskModel(MaFreeBox *fbx, QObject *parent) :
    FSAbstractTaskModel(parent)
{
    mFbx = fbx;
    connect(mFbx->fileSystem(),SIGNAL(taskListReceived(QList<FileTask>)),
            this,SLOT(dataReceived(QList<FileTask>)));
}
Пример #18
0
SocketLineReader::SocketLineReader(QTcpSocket* socket, QObject* parent)
    : QObject(parent)
    , mSocket(socket)
{
    connect(mSocket, SIGNAL(readyRead()),
            this, SLOT(dataReceived()));
}
Пример #19
0
void CTcpServer::clientHasData(QObject *obj)
{
    qDebug() << "Received client data\n";

    QTcpSocket *socket = qobject_cast<QTcpSocket *>(obj);
    emit dataReceived(socket->readAll());

#if 0
    QDataStream in(socket);
    in.setVersion(QDataStream::Qt_4_4);

    while (true)
    {
        if (clientInfo[socket] == 0)
        {
            if (socket->bytesAvailable() < (int)sizeof(quint32))
                return;

            in >> clientInfo[socket];
        }

        if (socket->bytesAvailable() < clientInfo[socket])
            return;

        clientTcpReceived(in);
        clientInfo[socket] = 0;
    }
#endif
}
Пример #20
0
void LiveDanmuHandler::connectServer(int roomID)
{
    serverClient = new ServerClient();
    connect(serverClient, SIGNAL(actionPrepared(Intent)), this, SLOT(dispatchAction(Intent)));
    connect(serverClient, SIGNAL(dataReceived(QByteArray)), this, SLOT(parseDataToDanmu(QByteArray)));
    serverClient->doConnect(roomID);
}
Пример #21
0
bool Socket::readToBuffer()
{
	if(file < 0)
		throw InvalidState("Socket is closed.");

	char buffer[64*1024];
	ssize_t readIn = 0;

	do{
		readIn = 0;
		do {
			readBuffer.append(buffer, readIn);
			if(0 < readIn){
				totalReceived += readIn;
				dataReceived();
				if(file == -1) // closed by child class
					return true;
			}
			readIn = ::read(file, buffer, sizeof(buffer));
		} while(0 < readIn);
	} while(readIn < 0 && errno == EINTR);

	if(readIn < 0 && ( errno != EAGAIN /*&& errno != EWOULDBLOCK*/ ) )
		throw SocketError(errno, "Error while reading from socket.");

	return 0 <= readIn; // false if EAGAIN or EWOULDBLOCK happened
}
void SimulationConnectionController::SimulationDataReceived(QByteArray data)
{
    DATA_HEADER_SET header;

    if(data.length()> sizeof(DATA_HEADER_SET))
    {
        memcpy(&header,data.data(),sizeof(DATA_HEADER_SET));
        data.remove(0,sizeof(DATA_HEADER_SET));
        if(header.type == IMAGE_JPEG)
        {
            if(data.length() >= header.length)
            {
                _simulationViewImageRAW = data;

                QImage img;
                try {
                    img = QImage::fromData(_simulationViewImageRAW,"JPEG");//the second param is format name
                } catch (...) {
                    qDebug() << "SimulationDataReceived -> ImageFailed.";
                }
                emit imageReceived(img);
            }
        }
        else if(header.type == SIMULATION_OUTPUT)
        {
            emit dataReceived(data);
        }
    }
}
Пример #23
0
    bool DBClientCursor::initLazyFinish( bool& retry ) {

        bool recvd = _client->recv( *batch.m );

        // If we get a bad response, return false
        if ( ! recvd || batch.m->empty() ) {

            if( !recvd )
                log() << "DBClientCursor::init lazy say() failed" << endl;
            if( batch.m->empty() )
                log() << "DBClientCursor::init message from say() was empty" << endl;

            _client->checkResponse( NULL, -1, &retry, &_lazyHost );

            return false;

        }

        dataReceived( retry, _lazyHost );

        if (DBClientWithCommands::PostRunCommandHookFunc hook = _client->getPostRunCommandHook()) {
            if (NamespaceString(ns).isCommand()) {
                BSONObj cmdResponse = peekFirst();
                hook(cmdResponse, _lazyHost);
            }
        }

        return ! retry;
    }
Пример #24
0
int Konsole::Pty::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = K3Process::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: done((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 1: receivedData((*reinterpret_cast< const char*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
        case 2: bufferEmpty(); break;
        case 3: readRVBData(); break;
        case 4: setUtf8Mode((*reinterpret_cast< bool(*)>(_a[1]))); break;
        case 5: lockPty((*reinterpret_cast< bool(*)>(_a[1]))); break;
        case 6: sendData((*reinterpret_cast< const char*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
        case 7: sendData1((*reinterpret_cast< const char*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
        case 8: doSendJobs1(); break;
        case 9: donePty(); break;
        case 10: dataReceived((*reinterpret_cast< K3Process*(*)>(_a[1])),(*reinterpret_cast< char*(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
        case 11: doSendJobs(); break;
        case 12: writeReady(); break;
        default: ;
        }
        _id -= 13;
    }
    return _id;
}
Пример #25
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    _sensors.push_back(Sensor(SensorData('s', CUSTOM_SENSOR01, 0, 0), 25.5));
    _sensors.push_back(Sensor(SensorData('s', CUSTOM_SENSOR02, 0, 0), 27.5));
    _sensors.push_back(Sensor(SensorData('s', CUSTOM_SENSOR03, 0, 0), 28.5));

    for (Sensor sensor: _sensors) {
        ui->comboBox_SensorId->addItem(QString::number(sensor.sensorData.byte01),
                                       sensor.sensorData.byte01);
        _sensorIds.push_back(sensor.sensorData.byte01);
    }

    _tcpClient = new TcpClient(CUSTOM_IPV4ADDRESS,
                               CUSTOM_PORT,
                               _sensorIds,
                               CUSTOM_QUERYINTERVAL,
                               this);

    bool isOk;
    // TcpClient: Connections
    isOk = connect(_tcpClient, SIGNAL(dataReceived(quint8, qreal)),
                   this, SLOT(onDataReceived(quint8, qreal)));
    Q_ASSERT(isOk);
    Q_UNUSED(isOk);

    isOk = connect(_tcpClient, SIGNAL(dataReceived(SensorData)),
                   this, SLOT(onDataReceived(SensorData)));
    Q_ASSERT(isOk);
    Q_UNUSED(isOk);

    // GUI: Connections
    isOk = connect(ui->pushButton_TemperatureSet, SIGNAL(clicked()),
                   this, SLOT(setTemperatureDesired()));
    Q_ASSERT(isOk);
    Q_UNUSED(isOk);

    isOk = connect(ui->comboBox_SensorId, SIGNAL(currentIndexChanged(int)),
                   this, SLOT(on_comboBox_SensorId_currentIndexChanged(int)));
    Q_ASSERT(isOk);
    Q_UNUSED(isOk);

    _tcpClient->start();
}
Пример #26
0
// Receive IMs from other bots
void Robot::listenPort() const
{
	// Return if nothing to do
	if (my_socket == -1)
		return;

	// Get message from other bot
	int length;
	struct sockaddr_in si_other;
	socklen_t other_length = sizeof(struct sockaddr_in);

	length = recvfrom(
		my_socket,
		buffer,
		BUFFLEN,
		0,
		(struct sockaddr *) &si_other,
		&other_length);

	// Return if nothing (length = -1) or
	// empty message (length = 0) received
	if (length <= 0)
		return;

	// Security: check that the data comes from one of the other robots
	int num;
	for (num = 0; num < NUMCLIENTS; num++)
	{
		if (client[num])
		{
			if (si_client[num].sin_addr.s_addr == si_other.sin_addr.s_addr &&
                si_client[num].sin_port        == si_other.sin_port)
				break;
		}
	}
	if (num == NUMCLIENTS)
	{
		printf("Received data from an unknown source: \"%s\"\n", buffer);
		return;
	}

	// Security: ensure the buffer is NUL-terminated
	if (length >= BUFFLEN)
		length = BUFFLEN - 1;
	buffer[length] = '\0';

	// Analyze data received
	switch (*buffer)
	{
		case 'D':
			dataReceived(num, buffer + 1, length - 1);
			break;
		case 'C':
			commandReceived(num, buffer + 1, length - 1);
			break;
		default:
			printf("Received invalid data: \"%s\"\n", buffer);
	}
}
Пример #27
0
void TKN_NodeBox::receiveData(TKN_Data *data)
{
    dataQueueMutex.lock();
    dataQueue.enqueue(*data);
    dataQueueMutex.unlock();
    dataQueueSem.release();
    emit dataReceived(*data);
}
IoHandler::IoHandler(QObject *pParent)
{
    pMyParent = (QMainWindow *)pParent;

    comPort = new ComPort(this);

    RefreshComPort();

    connect(this, SIGNAL(dataReceived(/*int index*/)), pParent, SLOT(dataReceived(/*int index*/)));
    connect(this, SIGNAL(pingReceived()), pParent, SLOT(pingReceived()));
    connect(this, SIGNAL(noPingResponse()), pParent, SLOT(noPingResponse()));

    // Create instance to Node Database.
    pNodeDb = new NodeDb;

	pLog= NULL;
}
Пример #29
0
XmlDataSource::XmlDataSource(QObject *parent)
    : QObject(parent),
      m_receiver(new XmlReceiver(this)),
      m_refreshRate(-1),
      m_waiting(false)
{
    QObject::connect(m_receiver, SIGNAL(finished()), this, SLOT(dataReceived()));
}
Пример #30
0
void CTcpFetcher::fetch(int len){
    if (m_pTcpSocket){
        char data[len];
        m_pTcpSocket->read(data,len);
        qDebug() << " GOT SOME DATA " << data;
        emit dataReceived(QString(data));
    }
}