bool SerialDevice::atEnd() const
{
    if(!isOpen())
    {
        return false;
    }

    return !bytesAvailable();
}
Пример #2
0
void CG2Node::OnRead()
{
	if( !Network.m_pSection.tryLock(50) )
	{
		emit readyRead(); // it is a queued connection, lets requeue the missed signal
		return;
	}

    //qDebug() << "CG2Node::OnRead";
    if( m_nState == nsHandshaking )
    {
        if( peek(bytesAvailable()).indexOf("\r\n\r\n") != -1 )
        {
            if( m_bInitiated )
            {
                ParseOutgoingHandshake();
            }
            else
            {
                ParseIncomingHandshake();
            }
        }
    }
    else if ( m_nState == nsConnected )
    {

		G2Packet* pPacket = 0;
        try
        {
			while( (pPacket = G2Packet::ReadBuffer(GetInputBuffer())) )
            {
				m_tLastPacketIn = time(0);
				m_nPacketsIn++;

				OnPacket(pPacket);

				pPacket->Release();
            }
        }
		catch(...)
        {
			if( pPacket )
			{
				qDebug() << pPacket->ToHex() << "\n" << pPacket->ToASCII();
				pPacket->Release();
			}

            qDebug() << "Packet error - " << m_oAddress.toString().toAscii();
            m_nState = nsClosing;
            emit NodeStateChanged();
            deleteLater();
        }
    }

	Network.m_pSection.unlock();
}
Пример #3
0
void AGChatSocket::readMessage()
{
    QDataStream socketIn(this);
    socketIn.setVersion(QDataStream::Qt_5_0);
    while (1)
    {
        qDebug() <<this->bytesAvailable()<< "Signal2\n";
        quint16 messageLength= 0;
        if (bytesAvailable() < sizeof(quint16)) return;
        socketIn >> messageLength;

        if (bytesAvailable() < messageLength) return;
        QString temp;
        socketIn >> temp;
        qDebug() << id << ": message received: " << temp << endl;
        emit readFinished(id, temp);
    }

}
Пример #4
0
void QUsbHid::onHidData(void* p, int len)
{
    QMutexLocker lock(mutex);
    {
        // got data
        readBuffer.append((char*)p,len);
        if (bytesAvailable() > 0)
            emit readyRead();
    }
}
Пример #5
0
int Connection::dataLengthForCurrentDataType()
{
    if (bytesAvailable() <= 0 || readDataIntoBuffer() <= 0 || !buffer.endsWith(SeparatorToken))
             return 0;

    buffer.chop(1);
    int number = buffer.toInt();
    buffer.clear();
    return number;
}
Пример #6
0
void eCIClient::dataAvailable()
{
	if (!receivedCmd)
	{
		if ((unsigned int)bytesAvailable() < sizeof(ciplus_header)) return;
		if ((unsigned int)readBlock((char*)&header, sizeof(ciplus_header)) < sizeof(ciplus_header)) return;
		header.magic = ntohl(header.magic);
		header.cmd = ntohl(header.cmd);
		header.size = ntohl(header.size);
		if (header.magic != CIPLUSHELPER_MAGIC)
		{
			if (parent) parent->connectionLost();
			return;
		}
		receivedCmd = header.cmd;
		receivedCmdSize = header.size;
	}
	if (receivedCmdSize)
	{
		if ((unsigned int)bytesAvailable() < receivedCmdSize) return;
		if (receivedCmdSize) delete [] receivedData;
		receivedData = new unsigned char[receivedCmdSize];
		if ((unsigned int)readBlock((char*)receivedData, receivedCmdSize) < receivedCmdSize) return;

		ciplus_message *message = (ciplus_message *)receivedData;
		switch (header.cmd)
		{
		default:
			{
				unsigned char *data = &receivedData[sizeof(ciplus_message)];
				parent->getSlot(ntohl(message->slot))->send(data, ntohl(message->size));
			}
			break;
		case eCIClient::CIPLUSHELPER_STATE_CHANGED:
			{
				eDVBCISession::setAction(ntohl(message->session), receivedData[sizeof(ciplus_message)]);
			}
			break;
		}
		receivedCmdSize = 0;
		receivedCmd = 0;
	}
}
Пример #7
0
/*!
 *  \internal
 *  This slot handles a disconnect notice from a source I/O device to handle
 *  cases where the source size is unknown. The internal state is adjusted
 *  ensuring a reader will unblock in waitForAllContent(). If unread
 *  data is present, a readyRead() signal will be emitted.
 *  The readChannelFinished() signal is emitted regardless.
 */
void QxtWebContent::sourceDisconnect()
{
    if (qxt_d().bytesNeeded == 0) return;
    if(!qxt_d().ignoreRemaining){
	qxt_d().ignoreRemaining = true;
	qxt_d().bytesNeeded = 0;
	if(bytesAvailable() != 0)
	    QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection);
        QMetaObject::invokeMethod(this, "readChannelFinished", Qt::QueuedConnection);
    }
}
Пример #8
0
		qint64 CustomNetworkReply::readData (char *data, qint64 maxSize)
		{
			if (Offset_ >= Content_.size ())
				return -1;

			qint64 number = std::min (maxSize, bytesAvailable ());
			std::memcpy (data, Content_.constData () + Offset_, number);
			Offset_ += number;

			return number;
		}
Пример #9
0
void TcpSocket::dataReceived()
{
    while(this->bytesAvailable() > 0) //检查字节数
    {
        char buf[1024];
        int length = bytesAvailable();
        this->read(buf, length); //读取接收
        QString message = buf;
        emit updateClients(message, length); //发射信号
    }
}
Пример #10
0
void TcpSocket::dataReceived()
{
    while(bytesAvailable()>0)
    {
        QByteArray jsonData=readAll();
        jsonFromClient2Server.setJSONData(jsonData);
        jsonFromClient2Server.converJSON2Data();
       protocolFromClient2Server= jsonFromClient2Server.getProtocolFromClient2Server();
        emit updateClients(protocolFromClient2Server);
    }
}
Пример #11
0
 void TcpClient::onReadyRead()
 {
     auto socket = m_socket;
     if (socket != nullptr)
     {
         while(socket->bytesAvailable() > 0)
         {
             auto const size = socket->read(reinterpret_cast<char*>(m_buffer), RxBufferSize);
             read(m_buffer, m_buffer + size, size);
         }
     }
 }
Пример #12
0
void AGSocket::readMessage()
{
    QDataStream socketIn(this);
    socketIn.setVersion(QDataStream::Qt_5_0);
    while (1)
    {
        qDebug() <<this->bytesAvailable()<< "Signal1\n";
        int messageLength= 0;
        if (bytesAvailable() < (int)sizeof(int)) return;
        socketIn >> messageLength;
        
        if (bytesAvailable() < (int)sizeof(int)*messageLength) return;
        std::vector<int> temp;
        for (int i = 0; i<messageLength; i++) {
            int tempMessage;
            socketIn >>tempMessage;
            temp.push_back(tempMessage);
        }
        emit readFinished(id, temp);
    }
}
Пример #13
0
bool DeviceMuxer::waitForReadyRead(channel_t channel, int msecs)
{
    QTime* timer = (msecs < 0) ? 0 : new QTime();
    if (timer)
        timer->start();

    _readyReadEmitted[channel] = false;
    // Wait until we have some more data to read
    while ( !_readyReadEmitted[channel] && bytesAvailable(channel) <= 0 &&
            (!timer || (timer->elapsed() < msecs)) )
    {
        // How much time left?
        int remaining = timer ? msecs - timer->elapsed() : -1;
        if (timer && remaining < 0)
            remaining = 0;
        QCoreApplication::processEvents(QEventLoop::AllEvents, remaining);
        QThread::yieldCurrentThread();
    }

    return _readyReadEmitted[channel] || bytesAvailable(channel) > 0;
}
Пример #14
0
/*!
Do some clean up, and be sure that all output has been read.
*/
void MyProcess::procFinished() {

#if !USE_TEMP_FILE
	if ( bytesAvailable() > 0 ) readStdOut();
#else
	timer.stop();

	if ( temp_file.bytesAvailable() > 0 ) readTmpFile();

	temp_file.close();
#endif
}
Пример #15
0
bool Connection::hasEnoughData()
{
    if (numBytesForCurrentDataType <= 0)
        numBytesForCurrentDataType = dataLengthForCurrentDataType();

    if (bytesAvailable() < numBytesForCurrentDataType || numBytesForCurrentDataType <= 0)
    {
        return false;
    }

    return true;
}
void TrkDevice::tryTrkRead()
{
#ifdef Q_OS_WIN
    const DWORD BUFFERSIZE = 1024;
    char buffer[BUFFERSIZE];
    DWORD charsRead;
    DWORD totalCharsRead = 0;

    while (TryReadFile(d->hdevice, buffer, BUFFERSIZE, &charsRead, NULL)) {
        totalCharsRead += charsRead;
        d->trkReadBuffer.append(buffer, charsRead);
        if (isValidTrkResult(d->trkReadBuffer, d->serialFrame))
            break;
    }
    if (verbose() && totalCharsRead)
        logMessage("Read" + d->trkReadBuffer.toHex());
    if (!totalCharsRead)
        return;
    const ushort len = trk::isValidTrkResult(d->trkReadBuffer, d->serialFrame);
    if (!len) {
        const QString msg = QString::fromLatin1("Partial message: %1").arg(stringFromArray(d->trkReadBuffer));
        emitError(msg);
        return;
    }
#else
    const int size = bytesAvailable(d->file.handle());
    if (!size)
        return;
    const QByteArray data = d->file.read(size);
    if (verbose())
        logMessage("READ " + data.toHex());
    d->trkReadBuffer.append(data);
    const ushort len = trk::isValidTrkResult(d->trkReadBuffer, d->serialFrame);
    if (!len) {
        if (d->trkReadBuffer.size() > 10) {
            const QString msg = QString::fromLatin1("Unable to extract message from '%1' '%2'").
                             arg(QLatin1String(d->trkReadBuffer.toHex())).arg(QString::fromAscii(d->trkReadBuffer));
            emitError(msg);
        }
        return;
    }
#endif // Q_OS_WIN
    trk::TrkResult r;
    QByteArray rawData;
    while (extractResult(&d->trkReadBuffer, d->serialFrame, &r, &rawData)) {
        if (verbose())
            logMessage("Read TrkResult " + r.data.toHex());
        emit messageReceived(r);
        if (!rawData.isEmpty())
            emit rawDataReceived(rawData);
    }
}
Пример #17
0
void Connection::processReadyRead()
{
    if (state == WaitingForGreeting) {
        if (!readProtocolHeader())
            return;
        if (currentDataType != Greeting) {
            abort();
            return;
        }
        state = ReadingGreeting;
    }

    if (state == ReadingGreeting) {
        if (!hasEnoughData())
            return;

        buffer = read(numBytesForCurrentDataType);
        if (buffer.size() != numBytesForCurrentDataType) {
            abort();
            return;
        }

        username = QString(buffer) + '@' + peerAddress().toString() + ':'
                   + QString::number(peerPort());
        currentDataType = Undefined;
        numBytesForCurrentDataType = 0;
        buffer.clear();

        if (!isValid()) {
            abort();
            return;
        }

        if (!isGreetingMessageSent)
            sendGreetingMessage();

        pingTimer.start();
        pongTime.start();
        state = ReadyForUse;
        emit readyForUse();
    }

    do {
        if (currentDataType == Undefined) {
            if (!readProtocolHeader())
                return;
        }
        if (!hasEnoughData())
            return;
        processData();
    } while (bytesAvailable() > 0);
}
void Socket::clearInputBuffer() {

  if (!connected_) {
    throw VLRException("Not connected.");
  }

  int64_t val = bytesAvailable();
  if (val > 0) {
    uint8_t* buffer = new uint8_t[val];
    ssize_t dummy = read(socket_, buffer, val);
    delete[] buffer;
  }
}
Пример #19
0
long FQTermLocalSocket::writeBlock( const QByteArray &data )
{
  int count = shell_process_->write(data);

  //char c;
//  shell_process_->getChar(&c);
//  shell_process_->ungetChar(c);
  if (bytesAvailable())
  {
    emit readyRead();
  }
  return count;
}
Пример #20
0
void ClientSocket::readMessage()
 {
    QDataStream in(this);
    quint16 nextBlockSize;
    QString message;

        in.setVersion(QDataStream::Qt_4_7);
        while(1)
        {
        if(bytesAvailable() < (int)sizeof(quint16)) return;
        in >> nextBlockSize;

        if(bytesAvailable() < nextBlockSize) return;

        //如果没有得到全部的数据,则返回,继续接收数据

        in >> message;

        emit getMessage(id,message);
        }
        //将接收到的数据存放到变量中
 }
void QHttpSocketEngine::setReadNotificationEnabled(bool enable)
{
    Q_D(QHttpSocketEngine);
    if (d->readNotificationEnabled == enable)
        return;

    d->readNotificationEnabled = enable;
    if (enable) {
        // Enabling read notification can trigger a notification.
        if (bytesAvailable())
            slotSocketReadNotification();
    }
}
Пример #22
0
int SocketClient::read(char *buf, int size)
{
    size = std::min(bytesAvailable(), size);
    if (size) {
        memcpy(buf, mReadBuffer.data() + mReadBufferPos, size);
        mReadBufferPos += size;
        if (mReadBuffer.size() == mReadBufferPos) {
            mReadBuffer.clear();
            mReadBufferPos = 0;
        }
    }
    return size;
}
Пример #23
0
void Connection::processReadyRead()
{
    QDataStream stream(this);
    do {
        QString request;
        stream >> request;
        if (request == "REQUEST_CONNECT") {
            onRequestConnect();
        } else if (request == "MESSAGE") {
            onMessageRecivied();
        } else {
        }
    } while (bytesAvailable() > 0);
}
Пример #24
0
void Slave::receiveMessage()
{
	while( bytesAvailable() > 0 )
	{
		Ipc::Msg m;
		if( m.receive( this ).isValid() )
		{
			if( m.cmd() != Ipc::Commands::Ping )
			{
				qDebug() << "Slave" << m_slaveId << "received message" << m.cmd();
			}

			bool handled = false;
			if( handleMessage( m ) )
			{
				handled = true;
			}

			if( m.cmd() == Ipc::Commands::Quit )
			{
				handled = true;
				QCoreApplication::quit();
			}
			else if( m.cmd() == Ipc::Commands::Identify )
			{
				Ipc::Msg( Ipc::Commands::Identify ).
					addArg( Ipc::Arguments::Id, m_slaveId ).
						send( this );
				handled = true;
			}
			else if( m.cmd() == Ipc::Commands::Ping )
			{
				m_lastPingResponse = QTime::currentTime();
				handled = true;
			}

			if( !handled )
			{
				Ipc::Msg( Ipc::Commands::UnknownCommand ).
						addArg( Ipc::Arguments::Command, m.cmd() ).send( this );
			}
		}
		else
		{
			LogStream( Logger::LogLevelError )
								<< "Slave" << m_slaveId
								<< "received invalid message from master";
		}
	}
}
Пример #25
0
	Uint32 BufferedSocket::readBuffered(Uint32 max_bytes_to_read,bt::TimeStamp now)
	{	
		Uint32 br = 0;
		bool no_limit = (max_bytes_to_read == 0);
		
		if (bytesAvailable() == 0)
		{
			close();
			return 0;
		}
			
		while ((br < max_bytes_to_read || no_limit)  && bytesAvailable() > 0)
		{
			Uint32 tr = bytesAvailable();
			if (tr > OUTPUT_BUFFER_SIZE)
				tr = OUTPUT_BUFFER_SIZE;
			if (!no_limit && tr + br > max_bytes_to_read)
				tr = max_bytes_to_read - br;
			
			int ret = Socket::recv(input_buffer,tr);
			if (ret != 0)
			{
				mutex.lock();
				down_speed->onData(ret,now);
				mutex.unlock();
				if (rdr)
					rdr->onDataReady(input_buffer,ret);
				br += ret;
			}
			else
			{
				// connection closed, so just return the number of bytes read
				return br;
			}
		}
		return br;
	}
Пример #26
0
/*
==============
<SLOTS>
==============
*/
void Qthreadcomport::newDataInPortSlot(int count)
{
	if ((bytesAvailable() == 0) || (!(isOpen()))) return; 
	const int size = 4096;
	char data[size];
    int readcount = readData(data, count);
	QTime timedb;
	timedb = timedb.currentTime();
	qDebug()<<"readData"<<"time= "<<"\t\t\t"<<timedb.second()<<" "<<timedb.msec();
	data[readcount] = '\0';
	
	unsigned char *dataPtr;
	dataPtr = (unsigned char *)&data;
	emit newDataInPortSignal(timedb, dataPtr,readcount);
}
Пример #27
0
bool Socket::CircularBuffer::peekBytes(void *dst, size_t n) {
	if (bytesAvailable() < n) {
		return false;
	}
	char_ptr ptr = (char_ptr)dst;
	if (tail + n <= buffer_size) {
		memcpy(ptr, buffer + tail, n);
	} else {
		size_t first_n = buffer_size - tail;
		size_t second_n = n - first_n;
		memcpy(ptr, buffer + tail, first_n);
		memcpy(ptr + first_n, buffer, second_n);
	}
	return true;
}
Пример #28
0
void AGChatSocket::setup()
{
    QDataStream socketIn(this);
    socketIn.setVersion(QDataStream::Qt_5_0);
    while (1)
    {
        qDebug() <<this->bytesAvailable()<< "Signal1\n";
        if (bytesAvailable() < (int)sizeof(int)) continue;
        socketIn >> id;
        qDebug() <<id<< " ID received\n";
        disconnect(this,SIGNAL(readyRead()),this,SLOT(setup()));
        connect(this,SIGNAL(readyRead()),this,SLOT(readMessage()));
        return;
    }
}
Пример #29
0
bool BinaryBuffer::waitForReadyRead(int msecs)
{
    Q_D(BinaryBuffer);
    if(bytesAvailable() > 0) return true;
    else
    {
        QMutexLocker lock(&d->_mutex);
        if(msecs == -1)
        {
            bool res = d->_dataAvailableCondition.wait(&d->_mutex);
            return res;
        }
        else return d->_dataAvailableCondition.wait(&d->_mutex, msecs);
    }
}
Пример #30
0
bool DkConnection::hasEnoughData() {
	if (mNumBytesForCurrentDataType <= 0) {
		mNumBytesForCurrentDataType = dataLengthForCurrentDataType();
	}
	
	//qDebug() << "numBytesForCurrentDataType:" << numBytesForCurrentDataType;
	//qDebug() << "bytesAvailable:" << bytesAvailable();
	//qDebug() << "buffer size:" << buffer.size();
	
	if (bytesAvailable() < mNumBytesForCurrentDataType || mNumBytesForCurrentDataType <= 0) {
		return false;
	}

	return true;
}