示例#1
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);
}
示例#2
0
bool spherebot::send(QString cmd)
{
    if(port->isOpen())
    {
        port->flush();
        lastSentLine.clear();
        lastSentLine.append(cmd);
        if(cmd.size() != 0)
        {
            if(cmd[cmd.size()-1] == '\n') cmd.chop(1);
        }
        cmd.append(" ");
        cmd.append(generateChecksumString(cmd));
        qDebug()<<"Sending: " + cmd;
        cmd.append("\n");
        port->write((const char*)cmd.toUtf8(),cmd.length());
    }
    else
    {
        qDebug()<<port->errorString()<<" port is not open";
        return false;
    }
    cmd.chop(1);
    emit dataSent(cmd);
    return true;
}
void MainWindow::entry_sending()    //substate of transmitting
{
    qDebug()<< "entry sending"<< endl;
    connect(this->bot,  SIGNAL(dataSent(QString)),this,         SLOT(interpretSentString(QString)));
    ui->controllBox->setEnabled(false);
    ui->sendFileButton->setText("Stop");
    bot->sendingFile = true;
    statusBar()->showMessage(tr("Sending File"));
}
/*
  Creates an ClientTCPRequest object where TCPSocket is the socket
  that will be used for data transfer
  */
ClientTCPRequest::ClientTCPRequest() : socket(new QTcpSocket(this)), data(new QString()), totalBytesSent(0), timer(NULL){
    QTimer * timeoutTimer = new QTimer();
    timeoutTimer->setInterval(8000);
    timeoutTimer->setSingleShot(true);
    timer = timeoutTimer;
    timer->start();
    connect(timer, SIGNAL(timeout()), this, SLOT(connectionTimedOut()));
    connect(getSocket(), SIGNAL(connected()), this, SLOT(readyToSend()));
    connect(getSocket(), SIGNAL(bytesWritten(qint64)), this, SLOT(dataSent(qint64)));
}
示例#5
0
void eConsoleAppContainer::readyWrite(int what)
{
	if (what&eSocketNotifier::Write && outbuf.size() )
	{
		queue_data &d = outbuf.front();
		int wr = ::write( fd[1], d.data+d.dataSent, d.len-d.dataSent );
		if (wr < 0)
			eDebug("eConsoleAppContainer write failed (%m)");
		else
			d.dataSent += wr;
		if (d.dataSent == d.len)
		{
			outbuf.pop();
			delete [] d.data;
			if ( filefd[0] == -1 )
			/* emit */ dataSent(0);
		}
	}
	if ( !outbuf.size() )
	{
		if ( filefd[0] > 0 )
		{
			char readbuf[32*1024];
			int rsize = read(filefd[0], readbuf, 32*1024);
			if ( rsize > 0 )
				write(readbuf, rsize);
			else
			{
				close(filefd[0]);
				filefd[0] = -1;
				::close(fd[1]);
				eDebug("readFromFile done - closing eConsoleAppContainer stdin pipe");
				fd[1]=-1;
				dataSent(0);
				out->stop();
			}
		}
		else
			out->stop();
	}
}
示例#6
0
qint64 LimitedNodeList::writeDatagram(const QByteArray& datagram,
                                      const SharedNodePointer& destinationNode,
                                      const HifiSockAddr& overridenSockAddr) {
    if (destinationNode) {
        PacketType packetType = packetTypeForPacket(datagram);

        if (NON_VERIFIED_PACKETS.contains(packetType)) {
            return writeUnverifiedDatagram(datagram, destinationNode, overridenSockAddr);
        }

        // if we don't have an overridden address, assume they want to send to the node's active socket
        const HifiSockAddr* destinationSockAddr = &overridenSockAddr;
        if (overridenSockAddr.isNull()) {
            if (destinationNode->getActiveSocket()) {
                // use the node's active socket as the destination socket
                destinationSockAddr = destinationNode->getActiveSocket();
            } else {
                // we don't have a socket to send to, return 0
                return 0;
            }
        }

        QByteArray datagramCopy = datagram;

        // if we're here and the connection secret is null, debug out - this could be a problem
        if (destinationNode->getConnectionSecret().isNull()) {
            qDebug() << "LimitedNodeList::writeDatagram called for verified datagram with null connection secret for"
                     << "destination node" << destinationNode->getUUID() << " - this is either not secure or will cause"
                     << "this packet to be unverifiable on the receiving side.";
        }

        // perform replacement of hash and optionally also sequence number in the header
        if (SEQUENCE_NUMBERED_PACKETS.contains(packetType)) {
            PacketSequenceNumber sequenceNumber = getNextSequenceNumberForPacket(destinationNode->getUUID(), packetType);
            replaceHashAndSequenceNumberInPacket(datagramCopy, destinationNode->getConnectionSecret(),
                                                 sequenceNumber, packetType);
        } else {
            replaceHashInPacket(datagramCopy, destinationNode->getConnectionSecret(), packetType);
        }

        emit dataSent(destinationNode->getType(), datagram.size());
        auto bytesWritten = writeDatagram(datagramCopy, *destinationSockAddr);
        // Keep track of per-destination-node bandwidth
        destinationNode->recordBytesSent(bytesWritten);
        return bytesWritten;
    }

    // didn't have a destinationNode to send to, return 0
    return 0;
}
示例#7
0
qint64 LimitedNodeList::writePacket(const NLPacket& packet, const Node& destinationNode) {
    if (!destinationNode.getActiveSocket()) {
        return 0;
    }
    
    // TODO Move to transport layer when ready
    if (SEQUENCE_NUMBERED_PACKETS.contains(packet.getType())) {
        PacketSequenceNumber sequenceNumber = getNextSequenceNumberForPacket(destinationNode.getUUID(), packet.getType());
        const_cast<NLPacket&>(packet).writeSequenceNumber(sequenceNumber);
    }

    emit dataSent(destinationNode.getType(), packet.getDataSize());
    
    return writePacket(packet, *destinationNode.getActiveSocket(), destinationNode.getConnectionSecret());
}
示例#8
0
qint64 LimitedNodeList::writePacket(const NLPacket& packet, const HifiSockAddr& destinationSockAddr,
                                    const QUuid& connectionSecret) {
    if (!NON_SOURCED_PACKETS.contains(packet.getType())) {
        const_cast<NLPacket&>(packet).writeSourceID(getSessionUUID());
    }
    
    if (!connectionSecret.isNull()
        && !NON_SOURCED_PACKETS.contains(packet.getType())
        && !NON_VERIFIED_PACKETS.contains(packet.getType())) {
        const_cast<NLPacket&>(packet).writeVerificationHash(packet.payloadHashWithConnectionUUID(connectionSecret));
    }

    emit dataSent(NodeType::Unassigned, packet.getDataSize());
    
    return writeDatagram(QByteArray::fromRawData(packet.getData(), packet.getDataSize()), destinationSockAddr);
}
void do_sleep(int proc, size_t numDoubles)
{
    stk::CommSparse comm(MPI_COMM_WORLD);

    if(proc==0)
        ::usleep(workTimeProc0*1e6);
    else
        calculate_sum(workTimeProcOthers*1e6);

    std::vector<double> dataSent(numDoubles,1);
    std::vector<std::vector<double> > dataRecvd(comm.parallel_size());
    stk::pack_and_communicate(comm, [&comm, &dataSent]() { send_data_to_other_procs(dataSent, comm); });
    stk::unpack_communications(comm,
                               [&comm, &dataRecvd](int procId)
                               {
                                    stk::unpack_vector_from_proc(comm, dataRecvd[procId], procId);
                               });
}
void spherebot::processAnswer(QString answer)
{
//    int linenumber = getOption(line,"N");
    //qDebug()<< "process answer: " << answer << endl;
    //qDebug()<< "buffer: " << toSendBuffer << endl;
    if(answer.contains("rs"))
    {
        resendLine();
    }
    else if (answer.contains("ok"))
    {
        //qDebug()<< "answer.contains(ok): "<< endl;
        lastLineTransmitted = true;
        timeout_timer->stop();

        if(toSendBuffer.size() > 0)
        {
            trySendBufferLine();
        }
        else if(sendingFile)
        {
            if( toSendBuffer.size() == 0 && lineCounter > lineMax)
            {
               emit fileTransmitted();
            }
            sendNext();
        }
        else
        {
            //everything sent
            retry_timer->stop();
        }
        emit dataSent(lastLine);
    }
    else if(answer.contains("Spherebot"))
    {
        //qDebug() << "received version" << endl;
        bot_connected = true;
    }
    else
    {
        //qDebug() << "answer did not contain rs or ok" << endl;
    }
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    resetPortList();

    //////////////////////////////////////////////////// for .svg display
    scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(scene);
    ////////////////////////////////////////////////////

    this->bot = new spherebot();
    Receiver = new rxThread(this->bot);

    penDownAngle = DEFAULTPENDOWN;
    penUpAngle = DEFAULTPENUP;

    layerIndex = 0;

    connect(bot->port,  SIGNAL(readyRead()), Receiver,      SLOT(receiveData()));
    connect(bot,        SIGNAL(dataSent(QString)),this,     SLOT(sendDataUI(QString)));
    connect(bot,        SIGNAL(progressChanged(int)),this,  SLOT(refreshSendProgress(int)));
    //connect(bot,        SIGNAL(fileTransmitted()),this,     SLOT(finishedTransmission()));
    connect(Receiver,   SIGNAL(lineReceived(QString)),this, SLOT(processReceivedData(QString)));
    connect(Receiver,   SIGNAL(lineReceived(QString)),this->bot,  SLOT(processAnswer(QString)));

    initUI();
    initSateMachine();

    if(LoadSettings())
    {
        FitInTimer.setInterval(10);
        FitInTimer.setSingleShot(true);
        connect(&FitInTimer,SIGNAL(timeout()),this,SLOT(fitgraphicsView()));
        FitInTimer.start();
    }

    setWindowTitle("Spherebot Controll");

    qDebug()<<"mainwindow initialised: ";
    connect(restartLayerMsgBox,SIGNAL(accepted()),this,SLOT(hey()));
}
示例#12
0
UBNetwork::UBNetwork(QObject *parent) : QObject(parent) {
    m_host = QHostAddress(QHostAddress::LocalHost);

    m_port = PHY_PORT;
    m_size = 0;

    m_socket = new QTcpSocket(this);

    connect(m_socket, SIGNAL(bytesWritten(qint64)), this, SLOT(dataSent(qint64)));
    connect(m_socket, SIGNAL(connected()), this, SLOT(phyConnected()));
    connect(m_socket, SIGNAL(disconnected()), this, SLOT(phyDisconnected()));
    connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(phyError(QAbstractSocket::SocketError)));
    connect(m_socket, SIGNAL(readyRead()), this, SLOT(dataAvailable()));

    m_timer = new QTimer(this);
    m_timer->setInterval(TRACK_RATE);

    connect(m_timer, SIGNAL(timeout()), this, SLOT(phyTracker()));

    m_timer->start();
}
int QBtSerialPortClient::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: disconnectedFromServer(); break;
        case 1: connectionResetByPeer(); break;
        case 2: connectedToServer(); break;
        case 3: dataSent(); break;
        case 4: dataReceived((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 5: error((*reinterpret_cast< QBtSerialPortClient::ErrorCode(*)>(_a[1]))); break;
        case 6: connect((*reinterpret_cast< const QBtDevice(*)>(_a[1])),(*reinterpret_cast< const QBtService(*)>(_a[2]))); break;
        case 7: disconnect(); break;
        case 8: sendData((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 9: sendData((*reinterpret_cast< const QByteArray(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 10;
    }
    return _id;
}
void MainWindow::leave_sending()    //substate of transmitting
{
    qDebug()<< "leave sending"<< endl;
    disconnect(this->bot,SIGNAL(dataSent(QString)),this,SLOT(interpretSentString(QString)));
    bot->sendingFile = false;
}