Esempio n. 1
0
void CAsyncSerialPort::readCompleted(const boost::system::error_code& error, std::size_t bytesTransferred)
{
   if (error)
   {
      // boost::asio::error::operation_aborted is fired when stop is required
      if (error == boost::asio::error::operation_aborted)
         return;     // Normal stop

      // Error ==> disconnecting
      YADOMS_LOG(error) << "Serial port read error : " << error.message();
      disconnect();
      notifyEventHandler(false);
      return;
   }

   // Read OK
   CByteBuffer buffer(bytesTransferred);
   memcpy(buffer.begin(), m_asyncReadBuffer.begin(), bytesTransferred);

   if (!!m_receiveBufferHandler)
      m_receiveBufferHandler->push(buffer);

   // Restart read
   startRead();
}
Esempio n. 2
0
void MyServer::handleNewConnection()
{
    pServerSocket = tcpServer.nextPendingConnection();
    connect(pServerSocket, SIGNAL(readyRead()), this, SLOT(startRead()));
    connect(pServerSocket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    pServerSocket->write("Hello!");
}
Esempio n. 3
0
void Connector::onTimeOut()
{
    qDebug("on Time Out");
    timer.stop();
    stopRead();
    startRead(1, 4);
}
Esempio n. 4
0
void CRemoteControl::acceptConnection()
{
  client = server.nextPendingConnection();

  connect(client, SIGNAL(readyRead()), this, SLOT(startRead()));
  connected = true;
}
		virtual void	start()
		{

			boost::system::error_code err;
			applySocketOpts(err);
			startRead();
		}
Esempio n. 6
0
void CAsyncSerialPort::tryConnect()
{
   if (isConnected())
   {
      YADOMS_LOG(warning) << "Already connected";
   }
   else
   {
      if (!connect())
      {
         // Fail to reconnect, retry after a certain delay
         m_connectRetryTimer.expires_from_now(m_connectRetryDelay);
         m_connectRetryTimer.async_wait(boost::bind(&CAsyncSerialPort::reconnectTimerHandler, this, boost::asio::placeholders::error));
         return;
      }

      // Connected
      notifyEventHandler(true);

      // Flush buffers if required
      if (m_flushAtConnect)
         flush();
   }

   // Start listening on the port
   startRead();
}
Esempio n. 7
0
    UdpRpcChannel::UdpRpcChannel(const string& serverAddr, const string& serverPort)
    : stop_( false ),
    serverAddr_(serverAddr),
    serverPort_(serverPort),
    io_service_initializer_( new IoServiceInitializer() ),
    socket_( io_service_initializer_->get_io_service() ) {
        
        udp::resolver resolver(io_service_initializer_->get_io_service() );
        udp::resolver::query query(serverAddr_, serverPort_);
        boost::system::error_code error;

        udp::resolver::iterator iter = resolver.resolve(query, error);

        if (error || iter == udp::resolver::iterator()) {
            GOOGLE_LOG(FATAL) << "fail to resolve address " << serverAddr_ << ":" << serverPort_;
        } else {
            remoteEndpoint_ = *iter;

            socket_.open(remoteEndpoint_.protocol(), error);
            if( error ) {
                GOOGLE_LOG( ERROR ) << "fail to open the UDP socket";
            } else {
                socket_.set_option(udp::socket::reuse_address(true), error);
                socket_.set_option(udp::socket::send_buffer_size( RpcMessage::MAX_UDP_SIZE ), error);
                socket_.set_option(udp::socket::receive_buffer_size( RpcMessage::MAX_UDP_SIZE ), error);
                startRead();
            }
        }
    }
Esempio n. 8
0
/**
 * @paragraph This method slot accepts new connections
 * @brief ServerPanel::acceptConnection()
 * @return void
 */
void ServerPanelService::acceptConnection() {
    // Reset the block size
    this->mBlockSize = 0;
    // Setup the client
    this->mClient = this->mServer.nextPendingConnection();
    // Setup the client readyRead() event handler
    connect(this->mClient, SIGNAL(readyRead()), this, SLOT(startRead()));
}
Esempio n. 9
0
void cetserver::acceptConnection()
{
    client = server.nextPendingConnection();


    connect(client, SIGNAL(readyRead()), this, SLOT(startRead()));

}
Esempio n. 10
0
void Client::init()
{
    connect(&client, SIGNAL(readyRead()), this, SLOT(startRead()));
    connect(&client, SIGNAL(disconnected()), this, SLOT(quit()));
    printf("connected to IP %s\n",client.peerAddress().toString().toLocal8Bit().data());
    editor->setPlainText("");
    QTextCursor cursor = editor->textCursor();
    cursor.setPosition(0,QTextCursor::MoveAnchor);
    editor->setTextCursor(cursor);
}
Esempio n. 11
0
void Server::acceptConnection()
{
    clientSocket = tcpServer->nextPendingConnection();
    emit throwNewConfig();
    connectionLabel->setText("Вы можете играть");
    okButton->setEnabled(true);
    connect(clientSocket, SIGNAL(readyRead()), this, SLOT(startRead()));
    connect(clientSocket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
    connect(clientSocket, SIGNAL(disconnected()), clientSocket, SLOT(deleteLater()));
}
Esempio n. 12
0
void Connection::handleRead(const boost::system::error_code & ec, size_t bt, const ConnectionPtr & ptr)
{
    MLOG_MESSAGE(Debug, "handleRead(" << ec << ')');

    if(!ec)
    {
        pos_ += bt;
        if(processRecords())
            startRead();
    }
}
Esempio n. 13
0
// this function finds the first free address and counts the number of files. If
// the flash is not blank then this function must be called before anything else
// is done.
// A file is considered to end when a "blank" entry is found, i.e. filled all with
// 0xff. When we find two consecutive blank entries we know that we've found the
// start of the free space.
void Datastore::scanFlash()
{
    byte entryBytes[DATASTORE_LOG_ENTRY_SIZE];
    uint32_t entryChecksum;
    boolean previousEntryBlank = false;
    _numberOfFiles = 0;
    startRead();
    while (_readPointer < DATASTORE_MAX_ADDRESS)
    {
        getNextEntry((LogEntry*)entryBytes);
        // we add the bytes of the LogEntry together. The only way we can get 0xff * DATASTORE_LOG_ENTRY_SIZE
        // is if all the bytes are 0xff i.e. this is a blank entry.
        entryChecksum = 0;
        for (int i = 0; i < DATASTORE_LOG_ENTRY_SIZE; i++) entryChecksum += entryBytes[i];
//    ((LogEntry*)entryBytes)->print();
//    Serial.println(entryChecksum);
        if (entryChecksum == ((uint32_t)0xff * (uint32_t)DATASTORE_LOG_ENTRY_SIZE))
        {
            // we've found a blank entry, so update the file counter
            _numberOfFiles++;
            // if the previous entry was also blank, then we've found the end
            // of the used portion of the flash
            if (previousEntryBlank)
            {
                // the readPointer is now pointing to the start of the entry after the _two_ blank entries, so
                // take it back one entry and set this as the first free address
                _firstFreeAddress = _readPointer - DATASTORE_LOG_ENTRY_SIZE;
                // there's no need for a blank entry at the start of the flash - deal with this as a special case
                if (_firstFreeAddress == DATASTORE_LOG_ENTRY_SIZE)
                {
                    _firstFreeAddress = 0;
                    _numberOfFiles = 0;
                }
                else
                {
                    // the file counter will be one bigger than it should be, because of the last blank entry, so fix it
                    _numberOfFiles -= 1;
                }
                return;
            }
            // set a flag that this is entry is blank, in case the next one also is, signifying the end of
            // the used portion
            previousEntryBlank = true;
        }
        else
        {
            // not a blank entry, so clear the blank entry flag
            previousEntryBlank = false;
        }
    }
    // if we've got to here it means the flash is full
    _firstFreeAddress = _readPointer;
}
Esempio n. 14
0
void ClientBase::processIncomingRequest(const string &data)
{
	m_requireProcessing = true;
	if(m_enableProcessing)
	{
		if(processInput(Variant(), data))
		{			
			startRead();
		}
		else m_delayedData = data;
	}
}
Esempio n. 15
0
bool printcurrent() {
  if (playing)
    return false;

  SdErrorCode e = startRead(currentfile);
  if(e != SD_SUCCESS)
  {
    // HOST.labelnum("pc: ", e, true);
    return false;
  }
  return true;
}
Esempio n. 16
0
bool autorun() {
  if (playing)
    return false;

  SdErrorCode e = startRead("sjfwauto.gcd");
  if(e != SD_SUCCESS)
  {
    return false;
  }

  return true;
}
TcpClient::TcpClient(QObject* parent): QObject(parent)
{
  //connect(&client, SIGNAL(connected()),
    //this, SLOT(startTransfer()));

    connect(&Socket_, SIGNAL(connected()),this, SLOT(setConnectionStateOn()));
    //connect(&client, SIGNAL(disconnected()),this, SLOT(setConnectionStateOff()));

    connect(&Socket_, SIGNAL(readyRead()),this, SLOT(startRead()));


  IsConnected_ = false;
}
Esempio n. 18
0
uint8_t GPS_MTK3339::Read(){
    #ifdef GPS_DEBUG_READ_VERBOSE
        GPS_DEBUG_READ_PRINTLN("READ GPS");
    #endif
    
    switch(_machineState){
        case GPS_MS_INIT:
        case GPS_MS_ERROR:
        case GPS_MS_READY:
            return startRead();
    }
    return continueRead();
}
Esempio n. 19
0
/**
 * @paragraph This method slot handles the reading and responding of the server
 * @brief ServerPanel::startRead()
 * @return void
 */
void ServerPanelService::startRead() {
    // Create the data stream
    QDataStream qdsServerPanel(this->mClient);
    // Check the block size
    if (this->mBlockSize == 0) {
        // Make sure we have a valid amount of daya
        if (this->mClient->bytesAvailable() < (int) sizeof(quint16)) {
            // We're done
            return;
        }
        // Read the data
        qdsServerPanel >> this->mBlockSize;
    }
    // See if we have read all of the data
    if (this->mClient->bytesAvailable() < this->mBlockSize) {
        // We're done
        return;
    }
    // Set a response placeholder
    QString sJson;
    // Read the stream
    qdsServerPanel >> sJson;
    // Check for data
    if (sJson.isEmpty()) {
        // Rerun the read
        QTimer::singleShot(0, this, SLOT(startRead()));
        // We're done
        return;
    }
    // Create an empty byte array
    QByteArray qbaOutput;
    // Handle the request
    QByteArray qbaClientResponse = ServerPanel::Instance()->HandleRequest(sJson);
    // Create a data stream
    QDataStream qdsResponse(&qbaOutput, QIODevice::WriteOnly);
    // Send a 0 response
    qdsResponse << (quint16) 0;
    // Send the JSON response
    qdsResponse << QString(qbaClientResponse);
    // Reset the response
    qdsResponse.device()->seek(0);
    // Send the block size
    qdsResponse << (quint16) (qbaOutput.size() - sizeof(quint16));
    // Write the response
    this->mClient->write(qbaOutput);
    // Disconnect
    this->mClient->waitForDisconnected();
}
Esempio n. 20
0
/*! \brief Accept a new client connection.
 *
 * This slot is called when a client opens a new connection.
 */
void RemoteControl::acceptConnection()
{
    rc_socket = rc_server.nextPendingConnection();

    // check if host is allowed
    QString address = rc_socket->peerAddress().toString();
    if (rc_allowed_hosts.indexOf(address) == -1)
    {
        qDebug() << "Connection attempt from" << address << "(not in allowed list)";
        rc_socket->close();
    }
    else
    {
        connect(rc_socket, SIGNAL(readyRead()), this, SLOT(startRead()));
    }
}
Esempio n. 21
0
Connector::Connector()
{
    //readOp = {0x09, 0xAC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x02};
    readOp[0] = 0x09;   // 数据总数
    readOp[1] = 0xAC;   // 读数据
    readOp[2] = 0xFF;   // 密码
    readOp[3] = 0xFF;
    readOp[4] = 0xFF;
    readOp[5] = 0xFF;
    readOp[6] = 0xFF;
    readOp[7] = 0xFF;
    readOp[8] = 0x01;   // 起始扇区
    readOp[9] = 0x02;   // 扇区数(最多5)
    //waitOp = {0x01, 0xAD};
    waitOp[0] = 0x01;   // 数据总数
    waitOp[1] = 0xAD;   // 关射频
    //writeOp = {0x09, 0xAB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x02};
    writeOp[0] = 0x09;  // 数据总数
    writeOp[1] = 0xAB;  // 写数据
    writeOp[2] = 0xFF;  // 密码
    writeOp[3] = 0xFF;
    writeOp[4] = 0xFF;
    writeOp[5] = 0xFF;
    writeOp[6] = 0xFF;
    writeOp[7] = 0xFF;
    writeOp[8] = 0x01;  // 起始扇区
    writeOp[9] = 0x02;  // 扇区数
    //后面跟数据,最长240byte
    //读取数据的返回头
    returnHead[0] = 0x5A;
    returnHead[1] = 0x59;
    returnHead[2] = 0x48;
    returnHead[3] = 0x02;

    setPortName("/dev/ttyO5");
    setBaudRate(QSerialPort::Baud9600);
    setDataBits(QSerialPort::Data8);
    setStopBits(QSerialPort::OneStop);
    setParity(QSerialPort::NoParity);
    open(QIODevice::ReadWrite);
    timer.setInterval(2000);
    connect(&timer, SIGNAL(timeout()), this, SLOT(onTimeOut()));
    connect(this, SIGNAL(readOK(QByteArray)), this, SLOT(onReadOK(QByteArray)));
    startRead(1, 4);
}
Esempio n. 22
0
bool NetMessageSocket::handleWrite()
{
	ssize_t rc = ::write(fd_, writeBuffer_.data() + writePos_, writeBuffer_.size() - writePos_);
	if (rc < 0) {
		perror("write");
		return false;
	}

	writePos_ += rc;

	if (writePos_ == writeBuffer_.size()) {
		writeBuffer_.clear();
		writePos_ = 0;
		startRead();
	}

	return true;
}
Esempio n. 23
0
 void TcpRpcChannel::serverConnected(const boost::system::error_code& ec, tcp::resolver::iterator iter) {
     if (ec) {
         if (iter == tcp::resolver::iterator()) {
             GOOGLE_LOG(ERROR) << "fail to connect to server " << serverAddr_ << ":" << serverPort_;
             connectTried_ = true;
             startConnect();
         } else {
             doConnect(++iter);
         }
     } else {
         //the connection to server is established
         GOOGLE_LOG(INFO) << "connect to server " << serverAddr_ << ":" << serverPort_ << " successfully";
         boost::system::error_code error;
         sock_.set_option(tcp::socket::reuse_address(true), error);
         startRead();
         connectTried_ = true;
     }
 }
Esempio n. 24
0
		/// Handle completion of a read operation. 
		void handleRead(const boost::system::error_code& error, std::size_t bytes_transferred)
		{

			if (!error){
				readBytes += bytes_transferred;
				readBuff.has_written(bytes_transferred);
				onReadMsg(readBuff, writeBuff);
				readBuff.discard_all();

				reading = false;

				if (writeBuff.readable_bytes()>0){
					//std::cout << "going to send " << writeBuff.readable_bytes() << std::endl;
					//std::cout << writeBuff.as_string() << std::endl;
					LOG_DEBUG << "going to send " << writeBuff.readable_bytes();
					{

						size_t out_put_size = 256;
						if (out_put_size > writeBuff.readable_bytes()){
							out_put_size = writeBuff.readable_bytes();
						}
						
						LOG_DEBUG << writeBuff.as_string(0,out_put_size);
					}
					startWrite();
				}
				else{
					startRead();
				}

			}
			else{
				if (error == boost::asio::error::misc_errors::eof){
					LOG_INFO << " Client disconnectd:" << remoteAddr.address() << "  " << remoteAddr.port();
				}
				else{
					LOG_ERR << remoteAddr.address() << "  " << remoteAddr.port()
						<< ",error =" << error.value()
						<< ",msg=" << error.message();
				}
			}
			reading = false;
		}
Esempio n. 25
0
void ZDLInterface::mclick(){
	writeConfig();
	ZDLConf *zconf = ZDLConfigurationManager::getActiveConfiguration();
	int stat;
	if(zconf->hasValue("zdl.save","dlgmode")){
		QString txt = zconf->getValue("zdl.save","dlgmode",&stat);
		if(txt == "closed"){
			btnEpr->setIcon(QPixmap(adown));
			zconf->setValue("zdl.save", "dlgmode", "open");
		}else{
			zconf->setValue("zdl.save", "dlgmode", "closed");
			btnEpr->setIcon(QPixmap(aup));
		}
	}else{
		btnEpr->setIcon(QPixmap(adown));
		zconf->setValue("zdl.save", "dlgmode", "open");
	}
	startRead();
}
Esempio n. 26
0
// }}}
// {{{ NetMessageSocket
NetMessageSocket::NetMessageSocket(ev::loop_ref loop, int fd, bool autoClose) :
	Logging("NetMessageSocket[fd:%d]", fd),
	loop_(loop),
	socketWatcher_(loop_),
	socketTimer_(loop),
	fd_(fd),
	autoClose_(autoClose),
	writeBuffer_(),
	writePos_(0),
	readBuffer_(),
	readPos_(0),
	reader_(&readBuffer_),
	receiveHook_()
{
	socketWatcher_.set<NetMessageSocket, &NetMessageSocket::io>(this);
	socketTimer_.set<NetMessageSocket, &NetMessageSocket::timeout>(this);

	startRead();
}
Esempio n. 27
0
    void TcpRpcChannel::dataReceived(const boost::system::error_code& ec,
            std::size_t bytes_transferred) {
        if (ec) {
            GOOGLE_LOG(ERROR) << "fail to receive data from server";
            startConnect();
            return;
        }

        GOOGLE_LOG(INFO) << "received " << bytes_transferred << " bytes from server";
        receivedMsg_.append(msgBuffer_, bytes_transferred);

        startRead();

        string msg;

        while (extractMessage(msg)) {
            responseReceived(msg);
        }

    }
Esempio n. 28
0
		/// Handle completion of a write operation.
		void handleWrite(const boost::system::error_code& error, std::size_t bytes_transferred)
		{

			if (!error){
				//
				//std::cout << "send done,bytes_transferred:" << writeBuff.readable_bytes() << bytes_transferred << std::endl;
				LOG_DEBUG << "send done,bytes_transferred:"  << bytes_transferred;
				BOOST_ASSERT(bytes_transferred == writeBuff.readable_bytes());
				writeBytes += bytes_transferred;
				writeBuff.discard_all();
				writing = false;
				startRead();
			}
			else{ 
				LOG_ERR << remoteAddr.address() << "  " << remoteAddr.port()
					<< ",error =" << error.value()
					<< ",msg=" << error.message();
			}
			writing = false;

		}
Esempio n. 29
0
resultsOut(){
  int i;

  // get the results

  for(i=0; i<getNum(); i++){
    startRead(i);

    name=getName(1);
    x=getDouble("x", 0);
    y=getDouble("y", 0);
    z=getDouble("z", 0);
    theta=getDouble("theta", 0);
    phi=getDouble("phi", 0);
    t=getDouble("t", 0);
    e=getDouble("e", 0);

    x*=1.e-2; y*=1.e-2; z*=1.e-2; theta=180-theta; phi=phi<180?phi+180:phi-180; e*=1.e-3;
    printf("%s %g %g %g %g %g %g %g\n", name, x, y, z, theta, phi, t, e);

    endRead();
  }
}
Esempio n. 30
0
/**
 * Is called whenever we receive the result of an asynchronous I/O operation.
 * Note: This function is running in the IOCP thread!
 */
void OutputChannel::completionPortNotified(DWORD numberOfBytes, DWORD errorCode)
{
    if (numberOfBytes)  {
        d->bufferedOutputModeSwitchMutex.lock();

        if (d->q->isBufferedOutputSet()) {
            outputBufferLock.lock();
            QByteArray data(intermediateOutputBuffer.data(), numberOfBytes);
            buffers.append(TimeStampedBuffer(runtime()->elapsed(), data));
            outputBufferLock.unlock();
        } else {
            fwrite_binary(stream, intermediateOutputBuffer.data(), numberOfBytes);
        }

        d->bufferedOutputModeSwitchMutex.unlock();
    }

    if (errorCode == ERROR_SUCCESS)
        if (startRead())
            return;

    QMetaObject::invokeMethod(d->q, "tryToRetrieveExitCode", Qt::QueuedConnection);
}