void RemoteInterfaceListener::run() {

	// Init socket
	stopRequested = false;
	QUdpSocket socket;
	if(!socket.bind(QHostAddress(server->ip), server->port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint)) {
		// Show error
		Debug::print("[RemoteInterfaceListener] could not bind");
		stopRequested = true;
	}

	// Enter processing loop...
	while (stopRequested == false) {

		// Process all pending datagrams
		while(socket.hasPendingDatagrams() && !stopRequested) {
			// Get the data from socket
			QByteArray data;
			data.resize(socket.pendingDatagramSize());
			QHostAddress sender;
			quint16 senderPort;
			socket.readDatagram(data.data(), data.size(), &sender, &senderPort);

			// Extract message and keep track of the pointer in the server
			RemoteInterfaceMessage *message = new RemoteInterfaceMessage(&data);
			message->sourceIp = sender.toString();
			message->sourcePort = senderPort;
			message->destinationIp = server->ip;
			message->destinationPort = server->port;
			server->messages->append(message);

			// Show reception and pass on for processing...
			Debug::print("[RemoteInterfaceListener] received %1 message from %2:%3", message->type, sender.toString(), senderPort);
			server->processMessage(message);
		}

		// Sleep wait
		QThread::msleep(core->intSetting("RemoteInterface_ListenerInterval"));

	}
}
Exemplo n.º 2
0
QString connection::Broadcast() {
    // Om ip adressen te ontdekken
    QNetworkAddressEntry inter;
    // sockets aanmaken en verbinden met enerzijds broadcast en anderzijds een luister poort
    QUdpSocket udpSocketSend;
    QUdpSocket udpSocketGet;
    udpSocketSend.connectToHost(inter.broadcast(), 40000);
    // udpSocketGet->bind(inter->ip(),667);
    // udpSocketGet->bind(QHostAddress::Any,667)
    if(udpSocketGet.bind(udpgetport,QUdpSocket::ShareAddress))
        Label->setText(Label->text() + "[INFO] Could properly bind udpSocketget to " + QString::number(udpgetport) + "\n");
    else Label->setText(Label->text() + "[INFO] Couldn't properly bind udpSocketget to " + QString::number(udpgetport) + "\n");
    // Pakket verzenden
    QByteArray send_datagram = "DISCOVER-STRATEGO-SERVER";
    // Optimalisatie voor in de loop
    QByteArray receive_datagram;

    quint16 serverPort;
    forever{
        udpSocketSend.writeDatagram(send_datagram, QHostAddress::Broadcast, 40000);
        if(udpSocketGet.waitForReadyRead(3000)){
            receive_datagram.resize(udpSocketGet.pendingDatagramSize());
            udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
            if(QString::fromUtf8(receive_datagram.data()) == "DISCOVERED-STRATEGO-SERVER")
            {
                receive_datagram.resize(udpSocketGet.pendingDatagramSize());
                udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
                Label->setText(Label->text() +"[INFO] PLAYER DATA: "+ receive_datagram.data() +"\n");
                speler = receive_datagram.toInt();
                if(speler==1)
                {
                    attacker=true;
                }
                else
                {
                    attacker=false;
                }
                receive_datagram.resize(udpSocketGet.pendingDatagramSize());
                udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
                Label->setText(Label->text() + "[INFO] GAME DATA: "+receive_datagram.data()+"\n");
                spel = receive_datagram.toInt();
                Label->setText(Label->text() + " SPEL:" + QString::number(spel) + "\n");
                Label->setText(Label->text() + "[INFO] Found STRATEGO-SERVER on " + server.toString().toUtf8().constData() + "\n");
                return server.toString();
            }
        }
        else
        {
            Label->setText(Label->text() + "[INFO] UDP Discover TimeOut!\n");
            static int timeout=0;
            timeout++;
            if(timeout==5)
            {
                Label->setText(Label->text() + "[ERROR] Server is not online. Please try again later!");
                return "";
            }
        }
    }
    return "";
}
Exemplo n.º 3
0
void Connection::slReceive() {
	QUdpSocket* sock = (QUdpSocket*) QObject::sender();
	const bool main = (sock->localPort() == sets.portMain) ? true : false;
	const bool aux = (sock->localPort() == sets.portAux) ? true : false;

	if (sock->hasPendingDatagrams()) {
		if (main) emit sgRxMain();
		if (aux) emit sgRxAux();
	}

	int size = 0;

	bool enabled = false;
	if (main) enabled = sets.main;
	if (aux) enabled = sets.aux;

	while (sock->hasPendingDatagrams() && run && enabled) {
		size = sock->pendingDatagramSize();
		convertor->setBufSize(size);
		sock->readDatagram(convertor->getBuf(), size);

		if (convertor->convert()) emit sgWr();
		else emit sgNoWr();

		if (main) timerRxMain->start();
		if (aux) timerRxAux->start();
	}
}
Exemplo n.º 4
0
void MainWindow::controlMessageReceived() {
    qDebug() << "message received";
    QUdpSocket* udpSocket = qobject_cast<QUdpSocket*>(sender());
    while (udpSocket->hasPendingDatagrams()) {
             QByteArray datagram;
             datagram.resize(udpSocket->pendingDatagramSize());
             QHostAddress sender;
             quint16 senderPort;

             udpSocket->readDatagram(datagram.data(), datagram.size(),
                                     &sender, &senderPort);
             if (datagram=="left") {
                 drone->moveLeft();
             } else if (datagram== "right") {
                 drone->moveRight();
             } else if (datagram=="stayx" && datagram=="stayy"){
                 drone->stay();
             } else if (datagram=="up") {
                 drone->higher();
             } else if (datagram=="down") {
                 drone->lower();
             } else {
                 qDebug() << "invalid command received";
             }
         }

}
Exemplo n.º 5
0
void TestClient::testSendKeyInputPacket(){
	Client* client = new Client(NULL);

	QUdpSocket* socket = new QUdpSocket();
	socket->bind(INCOMING_PORT);

	client->setDirection(1);
	client->setIsJumping(false);
	client->setIsLaunching(true);
	client->sendDatagram(KEY_INPUT_PACKET);

	QHostAddress *address = NULL;
	quint16 *port = NULL;
	QByteArray *datagram = new QByteArray(socket->pendingDatagramSize(), (char) 0);

	socket->readDatagram(datagram->data(), datagram->size(), address, port);

	QCOMPARE(datagram->at(0), KEY_INPUT_PACKET);
	QCOMPARE((int)datagram->at(1), -1);
	QCOMPARE((int)datagram->at(2), 1);
	QCOMPARE((bool)datagram->at(3), false);
	QCOMPARE((bool)datagram->at(4), true);

	delete socket;
}
Exemplo n.º 6
0
void OceanSocket::processIncomingWaves()
{
    QUdpSocket* socket = dynamic_cast<QUdpSocket*>(QObject::sender());
    while (socket->hasPendingDatagrams())
    {
        QByteArray wave;
        QHostAddress host;
        wave.resize(socket->pendingDatagramSize());
        socket->readDatagram(wave.data(), wave.size(), &host);
        for (int i = 0; i < boundAddresses.count(); i++) {
            if (host == boundAddresses.at(i))
                // skip processing since this is our own packet
                return;
        }
        if (wave.startsWith(NET_OCEAN_HEARTBEAT))
            emit shipHeartbeat(host, wave.mid(1).data());
        else if (wave.startsWith(NET_OCEAN_COURSE_CHANGE))
            emit shipChangedCourse(host, wave.mid(1).data());
        else if (wave.startsWith(NET_OCEAN_RETURN_TO_PORT))
            emit shipDocked(host, wave.mid(1).data());
        else if (wave.startsWith(NET_OCEAN_ADMIN_LOCK_REQ))
            emit adminLockRequested(host, wave.mid(1).data());
        else if (wave.startsWith(NET_OCEAN_ADMIN_LOCK_RESP))
            emit adminLockRequestReponse(host, (atoi(wave.mid(1,1).data()) == NET_OCEAN_ACKNOWLEDGE), wave.mid(2).data());
        else if (wave.startsWith(NET_OCEAN_MESSAGE))
            this->processMessage(host, wave.mid(1).data());
        else if (wave.startsWith(NET_OCEAN_SAIL))
            emit shipSailed(host, wave.mid(1).data());
    }
}
Exemplo n.º 7
0
void AudioReceiver::readPendingAudioRcvrData() {

    QUdpSocket *socket = qobject_cast<QUdpSocket *>(sender());

    while (socket->hasPendingDatagrams()) {

        m_datagram.resize(socket->pendingDatagramSize());

        if (socket->readDatagram(m_datagram.data(), m_datagram.size()) < 0) {

            AUDIO_RECEIVER << "read client" << m_client << "socket failed.";
            if (io->rcveIQ_toggle) {  // toggles the rcveIQ signal

                emit rcveIQEvent(this, 2);
                io->rcveIQ_toggle = false;
            }
        }
        else {

            io->au_queue.enqueue(m_datagram);

            if (!io->rcveIQ_toggle) {  // toggles the rcveIQ signal

                emit rcveIQEvent(this, 1);
                io->rcveIQ_toggle = true;
            }
        }
    }
}
Exemplo n.º 8
0
void SocketTestWindow::readyReadMessage()
{
    if(m_tcpEnable)
    {
        QByteArray data = m_socketClient->readAll();
        QString rd = data;
//        char logbuf[BUFSIZ] = {0};
//        sprintf(logbuf,"receive data from %s:%d  %s",)
//        QLogProvider::getLog()->log(logbuf);
        ui->m_teRecvData->setText(rd);

    }
    else
    {
        QUdpSocket* udpSocket = dynamic_cast<QUdpSocket*>(m_socketClient);
        while (udpSocket->hasPendingDatagrams()) {
                 QByteArray datagram;
                 datagram.resize(udpSocket->pendingDatagramSize());
                 udpSocket->readDatagram(datagram.data(), datagram.size(),
                                         &m_remoteHost, &m_remotePort);
                 char logbuf[BUFSIZ] = {0};
                 sprintf(logbuf,"receive datagram from %s:%d",m_remoteHost.toString().toStdString().c_str(),m_remotePort);
                 ui->m_teRecvData->setText(datagram);
                 QLogProvider::getLog()->log(logbuf);
        }
    }
}
Exemplo n.º 9
0
void StunClient::onStunReadyRead()
{
    QUdpSocket *sock = (QUdpSocket*)(sender());
    qDebug()<<""<<sock;

    u08bits rbuf[STUN_BUFFER_SIZE];

    while (sock->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(sock->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        sock->readDatagram(datagram.data(), datagram.size(),
                                &sender, &senderPort);

        {
            m_sending_udp = false;
            m_sending_timer->stop();
        }

        qDebug()<<"read: "<<sender<<senderPort<<datagram.length()<<datagram.toHex().left(20)<<"...";
        
        for (int i = 0; i < datagram.length(); i ++) {
            char c = datagram.at(i);
            fprintf(stderr, "%c", isprint(c) ? c : '.');
            if (i > 375) break;
        }
        fprintf(stderr, " ...]\n");

        this->processResponse(datagram, QString("%1:%2").arg(sender.toString()).arg(senderPort));
        // processTheDatagram(datagram);
    }
}
Exemplo n.º 10
0
void ICServer::processPendingDatagrams()
{
    QByteArray datagram;
    QUdpSocket *socket = isRunning ? udpSocket : testUdpSocket;

    do {
        QHostAddress *address = new QHostAddress;
        datagram.resize(socket->pendingDatagramSize());
        socket->readDatagram(datagram.data(), datagram.size(), address);

        ICMessageHandler *messageHandler = new ICMessageHandler(this);
        connect(messageHandler, SIGNAL(connectionOffer(QString)), this, SLOT(processSidCollision(QString)));
        connect(messageHandler, SIGNAL(serverDiscovery(QHostAddress,QString)), this, SLOT(processDiscovery(QHostAddress,QString)));
        connect(messageHandler, SIGNAL(questionRequest(QHostAddress)), this, SLOT(processRequest(QHostAddress)));
        connect(messageHandler, SIGNAL(answerReady(ICAnswer,QString)), this, SLOT(processAnswer(ICAnswer,QString)));

        ICMessageProcessor *processor = new ICMessageProcessor(messageHandler, *address, datagram);

        QThreadPool::globalInstance()->start(processor);

        qDebug()<< "[1] Received from " << *address << datagram;

        delete address;
    } while (socket->hasPendingDatagrams());
}
Exemplo n.º 11
0
void UdpRelay::onClientUdpSocketReadyRead()
{
    QUdpSocket *sock = qobject_cast<QUdpSocket *>(sender());
    if (!sock) {
        emit info("Fatal. A false object calling onClientUdpSocketReadyRead.");
        return;
    }

    if (sock->pendingDatagramSize() > RecvSize) {
        emit info("[UDP] Datagram is too large. Discarded.");
        return;
    }

    QByteArray data;
    data.resize(sock->pendingDatagramSize());
    QHostAddress r_addr;
    quint16 r_port;
    sock->readDatagram(data.data(), RecvSize, &r_addr, &r_port);

    QByteArray response;
    if (isLocal) {
        data = encryptor->decryptAll(data);
        Address destAddr;
        int header_length = 0;
        bool _auth;

        Common::parseHeader(data, destAddr, header_length, _auth);
        if (header_length == 0) {
            emit info("[UDP] Can't parse header. "
                      "Wrong encryption method or password?");
            return;
        }
        response = QByteArray(3, static_cast<char>(0)) + data;
    } else {
        data.prepend(Common::packAddress(r_addr, r_port));
        response = encryptor->encryptAll(data);
    }

    Address clientAddress = cache.key(sock);
    if (clientAddress.getPort() != 0) {
        listenSocket.writeDatagram(response,
                                   clientAddress.getFirstIP(),
                                   clientAddress.getPort());
    } else {
        emit debug("[UDP] Drop a packet from somewhere else we know.");
    }
}
Exemplo n.º 12
0
void tst_QUdpSocket::pendingDatagramSize()
{
    QUdpSocket server;
    QVERIFY2(server.bind(), server.errorString().toLatin1().constData());

    QHostAddress serverAddress = QHostAddress::LocalHost;
    if (!(server.localAddress() == QHostAddress::Any))
        serverAddress = server.localAddress();

    QUdpSocket client;
    QVERIFY(client.writeDatagram("this is", 7, serverAddress, server.localPort()) == 7);
    QVERIFY(client.writeDatagram(0, 0, serverAddress, server.localPort()) == 0);
    QVERIFY(client.writeDatagram("3 messages", 10, serverAddress, server.localPort()) == 10);

    char c = 0;
    QVERIFY(server.waitForReadyRead());
    if (server.hasPendingDatagrams()) {
#if defined Q_OS_HPUX && defined __ia64
        QEXPECT_FAIL("", "HP-UX 11i v2 can't determine the datagram size correctly.", Abort);
#endif
        QCOMPARE(server.pendingDatagramSize(), qint64(7));
        c = '\0';
        QCOMPARE(server.readDatagram(&c, 1), qint64(1));
        QCOMPARE(c, 't');
        c = '\0';
    } else {
        QSKIP("does not have the 1st datagram", SkipSingle);
    }

    if (server.hasPendingDatagrams()) {
        QCOMPARE(server.pendingDatagramSize(), qint64(0));
        QCOMPARE(server.readDatagram(&c, 1), qint64(0));
        QCOMPARE(c, '\0'); // untouched
        c = '\0';
    } else {
        QSKIP("does not have the 2nd datagram", SkipSingle);
    }

    if (server.hasPendingDatagrams()) {
        QCOMPARE(server.pendingDatagramSize(), qint64(10));
        QCOMPARE(server.readDatagram(&c, 1), qint64(1));
        QCOMPARE(c, '3');
    } else {
        QSKIP("does not have the 3rd datagram", SkipSingle);
    }
}
Exemplo n.º 13
0
void CNetwork::DataMayRead( )
{
    QByteArray byData;
    QUdpSocket* udpServer = qobject_cast< QUdpSocket* > ( sender( ) );

    while ( udpServer->hasPendingDatagrams( ) ) {
        byData.resize( udpServer->pendingDatagramSize( ) );
        udpServer->readDatagram( byData.data( ), byData.size( ) );
        ProcessData( byData );
    }
}
Exemplo n.º 14
0
void tst_QUdpSocket::broadcasting()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy) {
#ifdef TEST_QNETWORK_PROXY
        QFETCH_GLOBAL(int, proxyType);
        if (proxyType == QNetworkProxy::Socks5Proxy) {
            QSKIP("With socks5 Broadcast is not supported.", SkipAll);
        }
#endif
    }
#ifdef Q_OS_AIX
    QSKIP("Broadcast does not work on darko", SkipAll);
#endif
    const char *message[] = {"Yo mista", "", "Yo", "Wassap"};

    for (int i = 0; i < 4; ++i) {
        QUdpSocket serverSocket;
        QVERIFY2(serverSocket.bind(QHostAddress::Any, 5000), serverSocket.errorString().toLatin1().constData());

        QCOMPARE(serverSocket.state(), QUdpSocket::BoundState);

        connect(&serverSocket, SIGNAL(readyRead()), SLOT(empty_readyReadSlot()));

        QUdpSocket broadcastSocket;

        for (int j = 0; j < 100; ++j) {
            broadcastSocket.writeDatagram(message[i], strlen(message[i]),
                                          QHostAddress::Broadcast, 5000);
            QTestEventLoop::instance().enterLoop(15);
            if (QTestEventLoop::instance().timeout()) {
#if defined(Q_OS_FREEBSD)
                QEXPECT_FAIL("",
                             "Broadcasting to 255.255.255.255 does not work on FreeBSD",
                             Abort);
                QVERIFY(false); // seems that QFAIL() doesn't respect the QEXPECT_FAIL() :/
#endif
                QFAIL("Network operation timed out");
            }
            QVERIFY(serverSocket.hasPendingDatagrams());

            do {
                QByteArray arr;
                arr.resize(serverSocket.pendingDatagramSize() + 1);
                QHostAddress host;
                quint16 port;
                QCOMPARE((int) serverSocket.readDatagram(arr.data(), arr.size() - 1, &host, &port),
                         (int) strlen(message[i]));
                arr.resize(strlen(message[i]));
                QCOMPARE(arr, QByteArray(message[i]));
            } while (serverSocket.hasPendingDatagrams());
        }
    }
}
Exemplo n.º 15
0
void ServerSktUdp::newData()
{
	QUdpSocket* s = qobject_cast<QUdpSocket*>(sender());
	if (!s) return;

	qint64 bufLen = s->pendingDatagramSize();
	char* buf = TK::createBuffer(bufLen, MAXBUFFER);
	if (!buf) return;

	QHostAddress addr; quint16 port(0);

	qint64 readLen = 0;
	qint64 ioLen = s->readDatagram(buf, bufLen, &addr, &port);

	//while (ioLen > 0)
	//{
		readLen += ioLen;
	//	ioLen = s->readDatagram(buf+readLen, bufLen-readLen, &addr, &port);
	//}

	if (ioLen >= 0)
	{
		Conn* conn = (Conn*)getCookie(TK::ipstr(addr, port, false));
		if (!conn)
		{
			conn = new Conn;
			if (conn)
			{
				conn->key  = TK::ipstr(addr, port, false);
				conn->addr = addr;
				conn->port = port;
				setCookie(conn->key, conn);
			}
		}

		if (conn)
		{
			recordRecv(readLen);

			conn->stamp = QDateTime::currentDateTime();
			dump(buf, readLen, false, conn->key);
		}
	}

	TK::releaseBuffer(buf);
}
Exemplo n.º 16
0
void ServerPool::newUdpDatagram(void)
{
    QUdpSocket *socket = dynamic_cast<QUdpSocket*>(sender());

    while (socket->state() == QAbstractSocket::BoundState &&
           socket->hasPendingDatagrams())
    {
        QByteArray buffer;
        buffer.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        socket->readDatagram(buffer.data(), buffer.size(),
                             &sender, &senderPort);
        emit newDatagram(buffer, sender, senderPort);
    }
}
Exemplo n.º 17
0
void tst_QUdpSocket::writeToNonExistingPeer()
{
    QSKIP("Connected-mode UDP sockets and their behaviour are erratic", SkipAll);
    QFETCH(QHostAddress, peerAddress);
    quint16 peerPort = 34534;
    qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");

    QUdpSocket sConnected;
    QSignalSpy sConnectedReadyReadSpy(&sConnected, SIGNAL(readyRead()));
    QSignalSpy sConnectedErrorSpy(&sConnected, SIGNAL(error(QAbstractSocket::SocketError)));
    sConnected.connectToHost(peerAddress, peerPort, QIODevice::ReadWrite);

    // the first write succeeds...
    QCOMPARE(sConnected.write("", 1), qint64(1));

    // the second one should fail!
    QTest::qSleep(1000);                   // do not process events
    QCOMPARE(sConnected.write("", 1), qint64(-1));
    QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));

    // the third one will succeed...
    QCOMPARE(sConnected.write("", 1), qint64(1));
    QTestEventLoop::instance().enterLoop(1);
    QCOMPARE(sConnectedReadyReadSpy.count(), 0);
    QCOMPARE(sConnectedErrorSpy.count(), 1);
    QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));

    // we should now get a read error
    QCOMPARE(sConnected.write("", 1), qint64(1));
    QTest::qSleep(1000);                   // do not process events
    char buf[2];
    QVERIFY(!sConnected.hasPendingDatagrams());
    QCOMPARE(sConnected.bytesAvailable(), Q_INT64_C(0));
    QCOMPARE(sConnected.pendingDatagramSize(), Q_INT64_C(-1));
    QCOMPARE(sConnected.readDatagram(buf, 2), Q_INT64_C(-1));
    QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));

    QCOMPARE(sConnected.write("", 1), qint64(1));
    QTest::qSleep(1000);                   // do not process events
    QCOMPARE(sConnected.read(buf, 2), Q_INT64_C(0));
    QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));

    // we should still be connected
    QCOMPARE(int(sConnected.state()), int(QUdpSocket::ConnectedState));
}
Exemplo n.º 18
0
bool CQMedia::loadURL(const QString& url)
{
    QString tmp = url;
    tmp.remove(0,6);
    QString ip = tmp.split(QChar(':'))[0];
    int port = tmp.split(QChar(':'))[1].toInt();
    QUdpSocket udp;
    udp.bind(port,QUdpSocket::ShareAddress);
    udp.joinMulticastGroup(QHostAddress(ip));
    QEventLoop q;
    QTimer::singleShot(1000,&q,SLOT(quit()));

    connect(&udp,SIGNAL(readyRead()),&q,SLOT(quit()));
    q.exec();
    if(udp.pendingDatagramSize() == -1)
    {
        //qDebug("has no avalid datapkg...");
        QTimer::singleShot(3500,this,SLOT(_emitTimeout()));
        return false;
    }
    qDebug("has avalid datapkg...");
    udp.leaveMulticastGroup(QHostAddress(ip));
    udp.close();

    this->url = url;
//    SdpsrcParser sdpSrc(url);
//    if(!sdpSrc.isValid())
//    {
//        qDebug()<<"SdpsrcParser invalid!!";
//        return false;
//    }
//    sdpSrc.printf();
    GstElement *udpsrc =  gst_bin_get_by_name(GST_BIN(pipeline),"udpsrc");
    GstCaps *caps = gst_caps_new_simple("application/x-rtp",NULL);
    //QString uri = "udp://"+sdpSrc.broadcastIP+":"+QString::number(sdpSrc.v_port);
//    QString uri = "udp://"+sdpSrc.broadcastIP+":"+QString::number(sdpSrc.v_port);
   // QString uri = "udp://239.255.42.42:1234";
    QString uri = url;

    g_object_set(G_OBJECT(udpsrc),"uri",uri.toUtf8().data(),"caps",caps,NULL);
    gst_object_unref(udpsrc);
    return true;

}
Exemplo n.º 19
0
void tst_QUdpSocket::writeDatagram()
{
    QUdpSocket server;
    QVERIFY2(server.bind(), server.errorString().toLatin1().constData());

    QHostAddress serverAddress = QHostAddress::LocalHost;
    if (!(server.localAddress() == QHostAddress::Any))
        serverAddress = server.localAddress();

    QUdpSocket client;

    qRegisterMetaType<qint64>("qint64");
    qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");

    for(int i=0;; i++) {
        QSignalSpy errorspy(&client, SIGNAL(error(QAbstractSocket::SocketError)));
        QSignalSpy bytesspy(&client, SIGNAL(bytesWritten(qint64)));

        qint64 written = client.writeDatagram(QByteArray(i * 1024, 'w'), serverAddress,
                                              server.localPort());

        if (written != i * 1024) {
#if defined (Q_OS_HPUX)
            QSKIP("HP-UX 11.11 on hai (PA-RISC 64) truncates too long datagrams.", SkipSingle);
#endif
            QCOMPARE(bytesspy.count(), 0);
            QCOMPARE(errorspy.count(), 1);
            QCOMPARE(*static_cast<const int *>(errorspy.at(0).at(0).constData()),
                     int(QUdpSocket::DatagramTooLargeError));
            QCOMPARE(client.error(), QUdpSocket::DatagramTooLargeError);
            break;
        }
        QVERIFY(bytesspy.count() == 1);
        QCOMPARE(*static_cast<const qint64 *>(bytesspy.at(0).at(0).constData()),
                 qint64(i * 1024));
        QCOMPARE(errorspy.count(), 0);
        if (!server.waitForReadyRead(5000))
            QSKIP(QString("UDP packet lost at size %1, unable to complete the test.").arg(i * 1024).toLatin1().data(), SkipSingle);
        QCOMPARE(server.pendingDatagramSize(), qint64(i * 1024));
        QCOMPARE(server.readDatagram(0, 0), qint64(0));
    }
}
Exemplo n.º 20
0
void TestClient::testSendHelloPacket(){

	Client* client = new Client(NULL);

	QUdpSocket* socket = new QUdpSocket();
	socket->bind(INCOMING_PORT);

	client->sendDatagram(HELLO_PACKET);

	QHostAddress *address = NULL;
	quint16 *port = NULL;
	QByteArray *datagram = new QByteArray(socket->pendingDatagramSize(), (char) 0);

	socket->readDatagram(datagram->data(), datagram->size(), address, port);

	QCOMPARE(datagram->at(0), HELLO_PACKET);

	delete socket;

}
Exemplo n.º 21
0
  void ExitTunnel::UdpReadFromProxy()
  {
    if(!_running) {
      qDebug("SOCKS UDP read but not running");
      return;
    }

    QUdpSocket* socket = qobject_cast<QUdpSocket*>(sender());
    if(!socket) {
      qWarning("SOCKS Illegal call to UDP ReadFromClient()");
      return;
    }

    if(!CheckSession()) {
      qDebug("SOCKS read but no session");
      return;
    }

    // Restart the timeout timer
    _timers[socket]->start();
 
    QHostAddress peer;
    quint16 peer_port;
    QByteArray datagram;

    while(socket->hasPendingDatagrams()) {
      datagram.resize(socket->pendingDatagramSize());
      quint64 bytes = socket->readDatagram(datagram.data(), datagram.size(), &peer, &peer_port);
      qDebug() << "SOCKS UDP read bytes:" << bytes;

      if(bytes != static_cast<quint64>(datagram.size())) {
        qWarning() << "SOCKS UDP invalid dgram read. Got:" << bytes << "Expected:" << datagram.size();
        continue;
      }

      SendReply(UdpResponsePacket(_table.IdForConnection(socket), 
            SocksHostAddress(peer, peer_port), datagram).ToByteArray());
    }

    qDebug() << "MEM active" << _table.Count();
  }
Exemplo n.º 22
0
void TestClient::testSendLevelIDPacket(){

	Client* client = new Client(NULL);

	QUdpSocket* socket = new QUdpSocket();
	socket->bind(INCOMING_PORT);

	client->setLevelID(1);
	client->sendDatagram(LEVEL_ID_PACKET);

	QHostAddress *address = NULL;
	quint16 *port = NULL;
	QByteArray *datagram = new QByteArray(socket->pendingDatagramSize(), (char) 0);

	socket->readDatagram(datagram->data(), datagram->size(), address, port);

	QCOMPARE(datagram->at(0), LEVEL_ID_PACKET);
	QCOMPARE((int)datagram->at(1), -1);
	QCOMPARE((int)datagram->at(2), 1);

	delete socket;

}
Exemplo n.º 23
0
int Discoverer::findHPSDRDevices() {

	int devicesFound = 0;

	m_findDatagram.resize(63);
    m_findDatagram[0] = (char)0xEF;
    m_findDatagram[1] = (char)0xFE;
    m_findDatagram[2] = (char)0x02;
	for (int i = 3; i < 63; i++)
		m_findDatagram[i] = (char)0x00;

	QUdpSocket socket;

	CHECKED_CONNECT(
		&socket,
		SIGNAL(error(QAbstractSocket::SocketError)),
		this,
		SLOT(displayDiscoverySocketError(QAbstractSocket::SocketError)));

	io->networkIOMutex.lock();
	DISCOVERER_DEBUG << "using " << qPrintable(QHostAddress(set->getHPSDRDeviceLocalAddr()).toString()) << " for discovery.";
	io->networkIOMutex.unlock();

	// clear comboBox entries in the network dialogue
	set->clearNetworkIOComboBoxEntry();

#if defined(Q_OS_WIN32)

	if (socket.bind(
				QHostAddress(set->getHPSDRDeviceLocalAddr()), 0,
				QUdpSocket::ReuseAddressHint | QUdpSocket::ShareAddress))
				//QUdpSocket::ReuseAddressHint))
	{
		set->setMetisPort(this, socket.localPort());
		io->networkIOMutex.lock();
		DISCOVERER_DEBUG << "discovery_socket bound successfully to port " << socket.localPort();
		io->networkIOMutex.unlock();
	}
	else {

		io->networkIOMutex.lock();
		DISCOVERER_DEBUG << "discovery_socket bind failed.";
		io->networkIOMutex.unlock();

		socket.close();
		return 0;
	}
#elif defined(Q_OS_LINUX)

	if (socket.bind(
				QHostAddress(set->getHPSDRDeviceLocalAddr()),
				QUdpSocket::DefaultForPlatform))
	{
		CHECKED_CONNECT(
			&socket, 
			SIGNAL(error(QAbstractSocket::SocketError)), 
			this, 
			SLOT(displayDiscoverySocketError(QAbstractSocket::SocketError)));

		set->setMetisPort(this, socket.localPort());
		io->networkIOMutex.lock();
		DISCOVERER_DEBUG << "discovery_socket bound successfully to port " << socket.localPort();
		io->networkIOMutex.unlock();
	}
	else {
		
		io->networkIOMutex.lock();
		DISCOVERER_DEBUG << "discovery_socket bind failed.";
		io->networkIOMutex.unlock();

		socket.close();
		return 0;
	}
#endif

	if (socket.writeDatagram(m_findDatagram, QHostAddress::Broadcast, DEVICE_PORT) == 63) {

		io->networkIOMutex.lock();
		DISCOVERER_DEBUG << "discovery data sent.";
		io->networkIOMutex.unlock();
	}
	else {

		io->networkIOMutex.lock();
		DISCOVERER_DEBUG << "discovery data not sent.";
		io->networkIOMutex.unlock();
	}


	// wait a little
	//SleeperThread::msleep(30);
	SleeperThread::msleep(500);

	while (socket.hasPendingDatagrams()) {

		TNetworkDevicecard mc;
		quint16 port;
				
		m_deviceDatagram.resize(socket.pendingDatagramSize());
		socket.readDatagram(m_deviceDatagram.data(), m_deviceDatagram.size(), &mc.ip_address, &port);

		if (m_deviceDatagram[0] == (char)0xEF && m_deviceDatagram[1] == (char)0xFE) {
			
			if (m_deviceDatagram[2] == (char)0x02) {
				
				sprintf(mc.mac_address, "%02X:%02X:%02X:%02X:%02X:%02X",
					m_deviceDatagram[3] & 0xFF, m_deviceDatagram[4] & 0xFF, m_deviceDatagram[5] & 0xFF,
					m_deviceDatagram[6] & 0xFF, m_deviceDatagram[7] & 0xFF, m_deviceDatagram[8] & 0xFF);
				
				io->networkIOMutex.lock();
				DISCOVERER_DEBUG << "Device found at " << qPrintable(mc.ip_address.toString()) << ":" << port << "; Mac addr: [" << mc.mac_address << "]";
				DISCOVERER_DEBUG << "Device code version: " << qPrintable(QString::number(m_deviceDatagram.at(9), 16));
				io->networkIOMutex.unlock();

				int no = m_deviceDatagram.at(10);
				QString str;
				if (no == 0)
					str = "Metis";
				else if (no == 1)
					str = "Hermes";
				else if (no == 2)
					str = "Griffin";
				else if (no == 4)
					str = "Angelia";

				mc.boardID = no;
				mc.boardName = str;
				io->networkIOMutex.lock();
				DISCOVERER_DEBUG << "Device board ID: " <<  no;
				DISCOVERER_DEBUG << "Device is: " << qPrintable(str);
				io->networkIOMutex.unlock();

				m_deviceCards.append(mc);

				str += " (";
				str += mc.ip_address.toString();
				str += ")";
				
				set->addNetworkIOComboBoxEntry(str);
				devicesFound++;
			}
			else if (m_deviceDatagram[2] == (char)0x03) {

				io->networkIOMutex.lock();
				DISCOVERER_DEBUG << "Device already sending data!";
				io->networkIOMutex.unlock();
			}
		}
		
	}
	set->setMetisCardList(m_deviceCards);

	if (devicesFound == 1) {

		set->setCurrentHPSDRDevice(m_deviceCards.at(0));
		io->networkIOMutex.lock();
		DISCOVERER_DEBUG << "Device selected: " << qPrintable(m_deviceCards.at(0).ip_address.toString());
		io->networkIOMutex.unlock();
	}

	socket.close();
	return devicesFound;
}
Exemplo n.º 24
0
int main(int argc, char *argv[])
{
    int debugMode = DEBUGMODE;


    if(debugMode)
    {

    } else {
        qInstallMessageHandler(myMessageOutputDisable);

    }

    QDEBUG() << "number of arguments:" << argc;
    QStringList args;
    QDEBUGVAR(RAND_MAX);
    if(argc > 1) {
        QCoreApplication a(argc, argv);
        args = a.arguments();

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();



        QDEBUG() << "Running command line mode.";

        Packet sendPacket;
        sendPacket.init();
        QString outBuilder;

        QTextStream o(&outBuilder);


        QTextStream out(stdout);

        QDate vDate = QDate::fromString(QString(__DATE__).simplified(), "MMM d yyyy");
        QCoreApplication::setApplicationName("Packet Sender");
        QCoreApplication::setApplicationVersion("version " + vDate.toString("yyyy-MM-dd"));

        QCommandLineParser parser;
        parser.setApplicationDescription("Packet Sender is a Network TCP and UDP Test Utility by Dan Nagle\nSee http://PacketSender.com/ for more information.");
        parser.addHelpOption();
        parser.addVersionOption();

        // A boolean option with a single name (-p)
        QCommandLineOption quietOption(QStringList() << "q" << "quiet", "Quiet mode. Only output received data.");
        parser.addOption(quietOption);


        QCommandLineOption hexOption(QStringList() << "x" << "hex", "Parse data as hex (default).");
        parser.addOption(hexOption);

        QCommandLineOption asciiOption(QStringList() << "a" << "ascii", "Parse data as mixed-ascii (like the GUI).");
        parser.addOption(asciiOption);

        QCommandLineOption pureAsciiOption(QStringList() << "A" << "ASCII", "Parse data as pure ascii (no \\xx translation).");
        parser.addOption(pureAsciiOption);

        // An option with a value
        QCommandLineOption waitOption(QStringList() << "w" << "wait",
                "Wait up to <milliseconds> for a response after sending. Zero means do not wait (Default).",
                "milliseconds");
        parser.addOption(waitOption);

        // An option with a value
        QCommandLineOption fileOption(QStringList() << "f" << "file",
                "Send contents of specified path. Max 1024 for UDP, 10 MiB for TCP.",
                "path");
        parser.addOption(fileOption);


        // An option with a value
        QCommandLineOption bindPortOption(QStringList() << "b" << "bind",
                "Bind port. Default is 0 (dynamic).",
                "port");
        parser.addOption(bindPortOption);


        QCommandLineOption tcpOption(QStringList() << "t" << "tcp", "Send TCP (default).");
        parser.addOption(tcpOption);

        // A boolean option with multiple names (-f, --force)
        QCommandLineOption udpOption(QStringList() << "u" << "udp", "Send UDP.");
        parser.addOption(udpOption);

        // An option with a value
        QCommandLineOption nameOption(QStringList() << "n" << "name",
                                      "Send previously saved packet named <name>. Other options overrides saved packet parameters.",
                                      "name");
        parser.addOption(nameOption);


        parser.addPositionalArgument("address", "Destination address. Optional for saved packet.");
        parser.addPositionalArgument("port", "Destination port. Optional for saved packet.");
        parser.addPositionalArgument("data", "Data to send. Optional for saved packet.");


        // Process the actual command line arguments given by the user
        parser.process(a);

        const QStringList args = parser.positionalArguments();

        bool quiet = parser.isSet(quietOption);
        bool hex = parser.isSet(hexOption);
        bool mixedascii = parser.isSet(asciiOption);
        bool ascii = parser.isSet(pureAsciiOption);
        unsigned int wait = parser.value(waitOption).toUInt();
        unsigned int bind = parser.value(bindPortOption).toUInt();
        bool tcp = parser.isSet(tcpOption);
        bool udp = parser.isSet(udpOption);
        bool ipv6  = false;

        QString name = parser.value(nameOption);

        QString filePath = parser.value(fileOption);


        QString address = "";
        unsigned int port = 0;

        int argssize = args.size();
        QString data, dataString;
        data.clear();
        dataString.clear();
        if(argssize >= 1) {
            address = args[0];
        }
        if(argssize >= 2) {
            port = args[1].toUInt();
        }
        if(argssize >= 3) {
            data = (args[2]);
        }

        //check for invalid options..

        if(argssize > 3) {
            OUTIF() << "Warning: Extra parameters detected. Try surrounding your data with quotes.";
        }

        if(hex && mixedascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            mixedascii = false;
        }

        if(hex && ascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            ascii = false;
        }

        if(mixedascii && ascii) {
            OUTIF() << "Warning: both mixed ascii and pure ascii set. Defaulting to pure ascii.";
            mixedascii = false;
        }

        if(tcp && udp) {
            OUTIF() << "Warning: both TCP and UDP set. Defaulting to TCP.";
            udp = false;
        }

        if(!filePath.isEmpty() && !QFile::exists(filePath)) {
            OUTIF() << "Error: specified path "<< filePath <<" does not exist.";
            filePath.clear();
            OUTPUT();
            return -1;
        }

        //bind is now default 0

        if(!bind && parser.isSet(bindPortOption)) {
            OUTIF() << "Warning: Binding to port zero is dynamic.";
        }


        if(!port && name.isEmpty()) {
            OUTIF() << "Warning: Sending to port zero.";
        }

        //set default choices
        if(!hex && !ascii && !mixedascii) {
            hex = true;
        }

        if(!tcp && !udp) {
            tcp = true;
        }

        //Create the packet to send.
        if(!name.isEmpty()) {
            sendPacket = Packet::fetchFromDB(name);
            if(sendPacket.name.isEmpty()) {
                OUTIF() << "Error: Saved packet \""<< name <<"\" not found.";
                OUTPUT();
                return -1;
            } else {
                if(data.isEmpty()) {
                    data  = sendPacket.hexString;
                    hex = true;
                    ascii = false;
                    mixedascii = false;
                }
                if(!port) {
                    port  = sendPacket.port;
                }
                if(address.isEmpty()) {
                    address  = sendPacket.toIP;
                }
                if(!parser.isSet(tcpOption) && !parser.isSet(udpOption)) {

                    if(sendPacket.tcpOrUdp.toUpper() == "TCP") {
                        tcp=true;
                        udp = false;
                    } else {
                        tcp=false;
                        udp = true;
                    }

                }

            }

        }

        if(!parser.isSet(bindPortOption)) {
            bind = 0;
        }

        if(!filePath.isEmpty() && QFile::exists(filePath)) {
            QFile dataFile(filePath);
            if(dataFile.open(QFile::ReadOnly)) {

                if(tcp) {
                    QByteArray dataArray = dataFile.read(1024*1024*10);;
                    dataString = Packet::byteArrayToHex(dataArray);
                } else {

                    QByteArray dataArray = dataFile.read(1024);
                    dataString = Packet::byteArrayToHex(dataArray);
                }

                //data format is raw.
                ascii = 0;
                hex = 0;
                mixedascii = 0;

            }
        }



        QDEBUGVAR(argssize);
        QDEBUGVAR(quiet);
        QDEBUGVAR(hex);
        QDEBUGVAR(mixedascii);
        QDEBUGVAR(ascii);
        QDEBUGVAR(address);
        QDEBUGVAR(port);
        QDEBUGVAR(wait);
        QDEBUGVAR(bind);
        QDEBUGVAR(tcp);
        QDEBUGVAR(udp);
        QDEBUGVAR(name);
        QDEBUGVAR(data);
        QDEBUGVAR(filePath);

        //NOW LETS DO THIS!

        if(ascii) { //pure ascii
            dataString = Packet::byteArrayToHex(data.toLatin1());
        }

        if(hex) { //hex
            dataString = Packet::byteArrayToHex(Packet::HEXtoByteArray(data));
        }
        if(mixedascii) { //mixed ascii
            dataString = Packet::ASCIITohex(data);
        }

        if(dataString.isEmpty()) {
            OUTIF() << "Warning: No data to send. Is your formatting correct?";
        }

        QHostAddress addy;
        if(!addy.setAddress(address)) {
            QHostInfo info = QHostInfo::fromName(address);
            if (info.error() != QHostInfo::NoError)
            {
                OUTIF() << "Error: Could not resolve address:" + address;
                OUTPUT();
                return -1;
            } else {
                addy = info.addresses().at(0);
                address = addy.toString();
            }
        }

        QHostAddress theAddress(address);
        if (QAbstractSocket::IPv6Protocol == theAddress.protocol())
        {
           QDEBUG() << "Valid IPv6 address.";
           ipv6 = true;
        }


        QByteArray sendData = sendPacket.HEXtoByteArray(dataString);
        QByteArray recvData;
        recvData.clear();
        int bytesWriten = 0;
        int bytesRead = 0;


        if(tcp) {
            QTcpSocket sock;


            if(ipv6) {
                sock.bind(QHostAddress::AnyIPv6, bind);
            } else {
                sock.bind(QHostAddress::AnyIPv4, bind);
            }
            sock.connectToHost(addy, port);
            sock.waitForConnected(1000);
            if(sock.state() == QAbstractSocket::ConnectedState)
            {
                OUTIF() << "TCP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;
                bytesWriten = sock.write(sendData);
                sock.waitForBytesWritten(1000);
                //OUTIF() << "Sent:" << Packet::byteArrayToHex(sendData);
                if(wait) {
                    sock.waitForReadyRead(wait);
                    recvData = sock.readAll();
                    bytesRead = recvData.size();
                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
                sock.disconnectFromHost();
                sock.waitForDisconnected(1000);
                sock.close();

                OUTPUT();
                return bytesWriten;


            } else {
                OUTIF() << "Error: Failed to connect to " << address;

                OUTPUT();
                return -1;
            }


        } else {
            QUdpSocket sock;
            if(ipv6) {
                if(!sock.bind(QHostAddress::AnyIPv6, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            } else {
                if(!sock.bind(QHostAddress::AnyIPv4, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            }
            OUTIF() << "UDP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;

            bytesWriten = sock.writeDatagram(sendData, addy, port);
            //OUTIF() << "Wrote " << bytesWriten << " bytes";
            sock.waitForBytesWritten(1000);

            if(wait) {
                sock.waitForReadyRead(wait);

                if(sock.hasPendingDatagrams()) {
                    QHostAddress sender;
                    quint16 senderPort;
                    recvData.resize(sock.pendingDatagramSize());

                    sock.readDatagram(recvData.data(), recvData.size(),
                                            &sender, &senderPort);

                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
            }

            sock.close();

            OUTPUT();
            return bytesWriten;

        }





        OUTPUT();



    } else {
        QApplication a(argc, argv);

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();

        QFile file(":/packetsender.css");
        if(file.open(QFile::ReadOnly)) {
           QString StyleSheet = QLatin1String(file.readAll());
         //  qDebug() << "stylesheet: " << StyleSheet;
           a.setStyleSheet(StyleSheet);
        }

        MainWindow w;


        w.show();

        return a.exec();

    }



    return 0;

}
Exemplo n.º 25
0
void MainWindow::processData()
{
	int cnt = 0;
	while (m_udp.hasPendingDatagrams())
	{
		QByteArray datagram;
		datagram.resize(m_udp.pendingDatagramSize());
		QHostAddress sender;
		quint16 senderPort;

		m_udp.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

		quint32 size = *(quint32*)datagram.data();
		QByteArray data = qUncompress(datagram);

		char *udpData = (char*)data.data();

		switch (udpData[0])
		{
		case TYPE_SENSORS:
			processSensorsData((TUdpDataSENSORS*)udpData);
			break;
		case TYPE_PLAYER:
		{
			TUdpDataPLAYER *d = (TUdpDataPLAYER*)udpData;

			for (int i = 0; i < 8; i++)
			{
				float x = d->frustumPoints[i][0];
				float y = d->frustumPoints[i][1];
				float z = d->frustumPoints[i][2];
				m_pdaData.frustum[i] = QVector3D(x, y, z);
			}

			QByteArray b(udpData + sizeof(TUdpDataPLAYER), data.size());
			QDataStream ds(b);
			ds.setByteOrder(QDataStream::LittleEndian);
			ds.setFloatingPointPrecision(QDataStream::SinglePrecision);

			m_pdaData.playerPoints.clear();

			for (int i = 0; i < d->playerSize; i++)
			{
				int16_t latU, lonU;
				ds >> latU >> lonU;
				m_pdaData.playerPoints.append(latlonUtoVector(latU, lonU));
			}

			ui->lbInfo->setText(QString("Points: %1\nLives: %2").arg(d->points).arg(d->lives));
			ui->lbInfo_2->setText(QString("Time left: %1:%2").arg(d->timeLeft / 60).arg((int)(d->timeLeft % 60), 2, 10, QChar('0')));

			break;
		}
		case TYPE_STAB:
			m_pdaData.sphereEnabled = udpData[1];
			break;
		case TYPE_ENEMY:
		{
			TUdpDataENEMY *d = (TUdpDataENEMY*)udpData;
			QByteArray b(udpData + sizeof(TUdpDataENEMY), data.size());
			QDataStream ds(b);
			ds.setByteOrder(QDataStream::LittleEndian);
			ds.setFloatingPointPrecision(QDataStream::SinglePrecision);

			while (m_pdaData.enemies.size() < d->idx + 1)
			{
				m_pdaData.enemies.append(Enemy());
			}

			m_pdaData.enemies[d->idx].points.clear();
			for (int i = 0; i < d->enemiesSize; i++)
			{
				int16_t latU, lonU;
				ds >> latU >> lonU;
				m_pdaData.enemies[d->idx].points.push_back(latlonUtoVector(latU, lonU));
			}
			break;
		}
		case TYPE_FOOD:
		{
			TUdpDataFOOD *d = (TUdpDataFOOD*)udpData;
			QByteArray b(udpData + sizeof(TUdpDataFOOD), data.size());
			QDataStream ds(b);
			ds.setByteOrder(QDataStream::LittleEndian);
			ds.setFloatingPointPrecision(QDataStream::SinglePrecision);

			m_pdaData.foodPoints.clear();

			for (int i = 0; i < d->foodSize; i++)
			{
				int16_t latU, lonU;
				ds >> latU >> lonU;
				m_pdaData.foodPoints.append(latlonUtoVector(latU, lonU));
			}

			break;
		}
		}
		cnt++;
	}
}
Exemplo n.º 26
0
void MultiPointCom::run()
{
    mutex.lock();

    QTime timeout = lastConnectTime.addSecs(30);

    if (timeout < QTime::currentTime()) {
        qDebug() << "Device connected timeout" << disconnectCount++;
        lastConnectTime = QTime::currentTime();
#ifdef __arm__
        ioctl(device, SI4432_IOC_RESET, 1);
#endif
    }

#ifdef __arm__
    si4432_ioc_transfer tr;
    char txBuf[64], rxBuf[64];
    memcpy(txBuf, request.data(), request.size());
    memset(&tr, 0, sizeof(si4432_ioc_transfer));
    tr.tx_buf = (__u64)txBuf;
    tr.rx_buf = (__u64)rxBuf;
    tr.len = request.size();
    int len = ioctl(device, SI4432_IOC_MESSAGE(1), &tr);
    if (len > 0) {
        response.clear();
        response.append(rxBuf, len);
        quint8 addr = response.at(0);
        if (addr == address) {
            lastConnectTime = QTime::currentTime();
            disconnect = 0;
            emit deviceConnected();
            emit responseReceived(response.at(1), QByteArray(response.data() + 2, len - 2));
        }
    } else {
        disconnect++;
        if (disconnect > 3) {
            disconnect = 0;
            emit deviceDisconnected();
        }
    }
#else
    QUdpSocket *udp = new QUdpSocket();
    udp->writeDatagram(request, QHostAddress::LocalHost, 19999);

    if (udp->waitForReadyRead(100) && (udp->pendingDatagramSize() > 0)) {
        response.resize(udp->pendingDatagramSize());
        udp->readDatagram(response.data(), response.size());
        quint8 addr = response.at(0);
        if (addr == address) {
            lastConnectTime = QTime::currentTime();
            disconnect = 0;
            emit deviceConnected();
            emit responseReceived(response.at(1), response.mid(2));
        }
    } else {
        disconnect++;
        if (disconnect > 3) {
            disconnect = 0;
            emit deviceDisconnected();
        }
    }
    delete udp;
#endif

    mutex.unlock();
}
Exemplo n.º 27
0
int main(int argc, char *argv[])
{
        QCoreApplication a(argc, argv);

        //help output
        if(a.arguments().contains("help"))
        {
            MSG("### OSCGrabber HELP ###");
            MSG(" ");
            MSG("The following Arguments are available:");
            MSG("   osc-server-address (address to send osc messages to) [default: 127.0.0.1]");
            MSG("   osc-send-port      (port to send osc messages to) [default: 7000]");
            MSG("   osc-listen-port    (port on wich OSCGrabber is listening for incomming osc messages) [default: 9001]");
            MSG("   udp-send-address   (address to send udp converted messages to) [default: 127.0.0.1]");
            MSG("   udp-send-port      (port to send udp converted messages to) [default: 7799]");
            MSG("   udp-listen-port    (port on wich OSCGrabber is listening for incomming udp messages) [default: 7788]");
            MSG(" ");
            MSG("examaple calls:");
            MSG("   OSCGrabber osc-listen-port 7000 osc-server-address 1.2.3.4");
            MSG(" ");
            MSG("Type 'help' for this message.");
            a.exit();
            return a.exec();
        }

        //read command line arguments
        int oscListenPort = 9001;
        if(a.arguments().contains("osc-listen-port"))
            oscListenPort = a.arguments().at(a.arguments().indexOf(QRegExp("osc-listen-port"))+1).toInt();

        QString oscServerAddress = "127.0.0.1";
        if(a.arguments().contains("osc-server-address"))
            oscServerAddress = a.arguments().at(a.arguments().indexOf(QRegExp("osc-server-address"))+1);

        int oscSendPort = 9000;
        if(a.arguments().contains("osc-send-port"))
            oscSendPort = a.arguments().at(a.arguments().indexOf(QRegExp("osc-send-port"))+1).toInt();

        int udpSendPort = 7799;
        if(a.arguments().contains("udp-send-port"))
            udpSendPort = a.arguments().at(a.arguments().indexOf(QRegExp("udp-send-port"))+1).toInt();

        QString udpSendAddress = "127.0.0.1";
        if(a.arguments().contains("udp-send-address"))
            udpSendAddress = a.arguments().at(a.arguments().indexOf(QRegExp("udp-send-address"))+1);

        int udpListenPort = 7788;
        if(a.arguments().contains("udp-listen-port"))
            udpListenPort = a.arguments().at(a.arguments().indexOf(QRegExp("udp-listen-port"))+1).toInt();


        //start creating the services
        MSG("### [Creating] UDP service at Port "<<udpListenPort);
        MSG("### Sending to "<<udpSendAddress.toStdString());
        QUdpSocket *listenSocket = new QUdpSocket(&a);
        listenSocket->bind(QHostAddress::AnyIPv4, udpListenPort);

        if(!listenSocket->isValid())
        {
            MSG("Couldn't creat udp service at port "<<udpSendPort<<" . Port already occupied?");
            a.exit();
            return 0; //a.exec();
        }

        MSG("### [Launching] OSC Bridge to address "<<oscServerAddress.toStdString()<<" "<<oscListenPort)
        lo::ServerThread * server = new lo::ServerThread(oscListenPort);
        server->start();

        if (!server->is_valid()) { //this check isn't working. why?
            MSG("Couldn't creat osc service listening to port "<<oscListenPort<<" . Port already occupied?");
            a.exit();
            return 0; //a.exec();
        }
        MSG("### --> Listening to Port: "<<oscListenPort);

        lo::string_type address(oscServerAddress.toStdString());
        lo::Address * oscSender = new lo::Address(address, oscSendPort);

//        lo::Address * oscSender = new lo::Address("localhost", oscSendPort);
        MSG("### --> Writing on Port: "<<oscSendPort);


        //####################################################################################
        //####################################################################################
        //  OSC to UDP
        //####################################################################################
        //####################################################################################

        QUdpSocket *senderSocket = new QUdpSocket(&a);

        server->add_method(NULL, NULL, [=](const char *path, const lo::Message& msg)
        {
//            msg.print();
            QString type = QString::fromStdString(msg.types());
            QString data(path);
            data.append("%");
            data.append(type);
            data.append("%");

            for (int i = 0; i < msg.argc(); i++) {
                if(type.at(i) == 'i')
                {
                    data.append(QString::number(msg.argv()[i]->i)+"%");
//                    std::cout<<std::bitset<32>()<<std::endl;
                }
                else if(type.at(i) == 'f')
                    data.append(QString::number(msg.argv()[i]->f)+"%");
                else if(type.at(i) == 's')
                    data.append(QString::fromStdString(&msg.argv()[i]->S)+"%");
            }

            if(-1 == senderSocket->writeDatagram(data.toUtf8(), QHostAddress(udpSendAddress), udpSendPort))
            {
                //qDebug()<<"ERROR: "<<senderSocket->errorString()<<" "<<senderSocket->error();
            }
            else
            {
                //qDebug()<<"From live: "<<data;
                //qDebug()<<"NO ERROR?: "<<senderSocket->errorString()<<" "<<senderSocket->error()<<" valid? "<<senderSocket->isValid();
            }
        });

        //####################################################################################
        //####################################################################################
        //  UDP to OSC
        //####################################################################################
        //####################################################################################

        QObject::connect(listenSocket, &QUdpSocket::readyRead, [=]()
        {
            QByteArray datagram;
            datagram.resize(listenSocket->pendingDatagramSize());
            QHostAddress sender;
            quint16 senderPort;

            listenSocket->readDatagram(datagram.data(), datagram.size(),
                                            &sender, &senderPort);

            //qDebug()<<"Message from: "<<sender<<" "<<senderPort<<" "<<QString::fromUtf8(datagram);

            QStringList splittedData = QString::fromUtf8(datagram).split("%");

            if(splittedData.length() > 1)
            {

                lo::string_type path(splittedData.takeFirst().toStdString());
                QString dataTypes = splittedData.takeFirst();
                lo::Message message;

                for(int i = 0; i<dataTypes.length(); i++)
                {
                    //qDebug()<<"type: "<<dataTypes.at(i);
                    if(dataTypes.at(i) == 'i')
                        message.add(splittedData.at(i).toInt());
                    else if(dataTypes.at(i) == 'f')
                        message.add(splittedData.at(i).toFloat());
                    else if(dataTypes.at(i) == 's')
                    {
                        lo::string_type str(splittedData.at(i).toStdString());
                        message.add(str);
                    }
                }
                //qDebug()<<"Stringlist: "<<splittedData;
                /*qDebug()<<"To live: "<<*/
                oscSender->send(path, message);//<<QString::fromStdString(message.types())<<path._s;

            }
            else
            {
                lo::string_type path(splittedData.takeFirst().toStdString());
                /*qDebug()<<"To live: "<<*/
                oscSender->send(path);
            }

        });

        //clean up services
        QObject::connect(&a, &QCoreApplication::destroyed, [=](){
            server->stop();
            delete server;
        });

        return a.exec();
}
Exemplo n.º 28
0
int main(int argc, char *argv[])
{
	int framePeriod = 1000000 / 60;
	
	QString logFile;
	
	// Determine log file name
	if (argc == 2)
	{
		logFile = argv[1];
	}
	
	if (logFile.isNull())
	{
		if (!QDir("logs").exists())
		{
			printf("No logs directory and no log file specified\n");
			return 1;
		}
		
		logFile = QString("logs/") + QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss.log");
	}
	
	// Create vision socket
	QUdpSocket visionSocket;
	if (!visionSocket.bind(SharedVisionPort, QUdpSocket::ShareAddress))
	{
		printf("Can't bind to shared vision port");
		return 1;
	}
	multicast_add(&visionSocket, SharedVisionAddress);
	
	// Create referee socket
	QUdpSocket refereeSocket;
	if (!refereeSocket.bind(LegacyRefereePort, QUdpSocket::ShareAddress))
	{
		printf("Can't bind to referee port");
		return 1;
	}
	multicast_add(&refereeSocket, RefereeAddress);
	
	// Create log file
	int fd = creat(logFile.toAscii(), 0666);
	if (fd < 0)
	{
		printf("Can't create %s: %m\n", (const char *)logFile.toAscii());
		return 1;
	}
	
	printf("Writing to %s\n", (const char *)logFile.toAscii());
	
	// Main loop
	LogFrame logFrame;
	bool first = true;
	while (true)
	{
		uint64_t startTime = timestamp();
		
		logFrame.Clear();
		logFrame.set_command_time(startTime);
		
		// Check for user input (to exit)
		struct pollfd pfd;
		pfd.fd = 0;
		pfd.events = POLLIN;
		if (poll(&pfd, 1, 0) > 0)
		{
			// Enter pressed
			break;
		}
		
		// Read vision data
		while (visionSocket.hasPendingDatagrams())
		{
			string buf;
			unsigned int n = visionSocket.pendingDatagramSize();
			buf.resize(n);
			visionSocket.readDatagram(&buf[0], n);
			
			SSL_WrapperPacket *packet = logFrame.add_raw_vision();
			if (!packet->ParseFromString(buf))
			{
				printf("Bad vision packet of %d bytes\n", n);
				continue;
			}
		}
		
		// Read referee data
		while (refereeSocket.hasPendingDatagrams())
		{
			unsigned int n = refereeSocket.pendingDatagramSize();
			string str(6, 0);
			refereeSocket.readDatagram(&str[0], str.size());
			
			// Check the size after receiving to discard bad packets
			if (n != str.size())
			{
				printf("Bad referee packet of %d bytes\n", n);
				continue;
			}
			
			logFrame.add_raw_referee(str);
		}
		
		if (first)
		{
			first = false;
			
			LogConfig *logConfig = logFrame.mutable_log_config();
			logConfig->set_generator("simple_logger");
			logConfig->set_git_version_hash(git_version_hash);
			logConfig->set_git_version_dirty(git_version_dirty);
		}
		
		uint32_t size = logFrame.ByteSize();
		if (write(fd, &size, sizeof(size)) != sizeof(size))
		{
			printf("Failed to write size: %m\n");
			break;
		} else if (!logFrame.SerializeToFileDescriptor(fd))
		{
			printf("Failed to write frame: %m\n");
			break;
		}
		
		uint64_t endTime = timestamp();
		int lastFrameTime = endTime - startTime;
		if (lastFrameTime < framePeriod)
		{
			usleep(framePeriod - lastFrameTime);
		} else {
			printf("Processor took too long: %d us\n", lastFrameTime);
		}
	}
	
	// Discard input on stdin
	tcflush(0, TCIFLUSH);
	
	printf("Done.\n");
	
	return 0;
}
Exemplo n.º 29
0
void Discover::readDatagrams ()
{
	QUdpSocket* socket = qobject_cast<QUdpSocket*>(QObject::sender());
	if (socket)
	while (socket->hasPendingDatagrams())
	{
		// Read it to a buffer
		QByteArray datagram;
		datagram.resize(socket->pendingDatagramSize());
		QHostAddress sender;
		quint16 senderPort;
		socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

		// Check the prefix
		bool respond = false;
		bool removeThem = false;
		if (datagram.startsWith("DSDA")) respond = false; // Announcement, do not respond
		else if (datagram.startsWith("DSDR")) respond = true; // Request, do respond
		else if (datagram.startsWith("DSDD")) removeThem = true; // This is a departure, remove records following
		else
		{
			// This datagram isn't written for Discover, pass it on
			QList<Record> matchingRecords;
			for (Record record : foundRecords.keys())
			{
				if (record.has("Address") and record["Address"]==sender.toString())
				if (record.has("Port") and record["Port"]==QString::number(senderPort))
					matchingRecords.append(record);
			}
			emit gotDatagram(datagram, sender, senderPort, matchingRecords);
			continue;
		}
		datagram.remove(0, 4);

		// Determine the scope of the sender
		// See if it's this machine
		QString scope("Global");
		if (sender.isLoopback())
		{
			scope = "Loopback";
		}
		else if (sender.protocol() == QAbstractSocket::IPv4Protocol)
		{
			if (addressIsLocal(sender)) scope = "Local";
		}

		// Process the records locally
		acceptRecords(Record::listFromBytes(datagram), removeThem, scope, sender.toString(), QString::number(senderPort));

		// Normal: Respond to only Local requests with only owned Records
		if (respond and not mServerMode and (scope=="Local" or scope=="Loopback"))
		{
			globalSocket->writeDatagram(QByteArray("DSDA")+makeDatagram(ownedRecords, true), sender, senderPort);
		}
		// Server: Respond to only global requests with owned and found Records
		else if (respond and mServerMode and scope=="Global")
		{
			globalSocket->writeDatagram(QByteArray("DSDA")+makeDatagram(ownedRecords + foundRecords.keys(), false), sender, senderPort);
		}
	}
}
Exemplo n.º 30
0
/**
 * @brief SingleApplication::SingleApplication
 *  Constructor. Checks and fires up LocalServer or closes the program
 *  if another instance already exists
 * @param argc
 * @param argv
 */
SingleApplication::SingleApplication(QStringList &args)
{
  _shouldContinue = false; // By default this is not the main process

  socket = new QUdpSocket();
  QUdpSocket acceptor;
  acceptor.bind(QHostAddress::LocalHost, 58488, QUdpSocket::ReuseAddressHint|QUdpSocket::ShareAddress);

  // Attempt to connect to the LocalServer
  socket->connectToHost(QHostAddress::LocalHost, 58487);
  QString isServerRuns;
  if(socket->waitForConnected(100))
  {
      socket->write(QString("CMD:Is editor running?").toUtf8());
      socket->flush();
      if(acceptor.waitForReadyRead(100))
      {
          //QByteArray dataGram;//Yes, I'm runs!
          QByteArray datagram;
          datagram.resize(acceptor.pendingDatagramSize());
          QHostAddress sender;
          quint16 senderPort;
          acceptor.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
          if(QString::fromUtf8(datagram)=="Yes, I'm runs!")
          {
              isServerRuns="Yes!";
          }
      }
  }

  if(args.contains("--force-run", Qt::CaseInsensitive))
  {
      isServerRuns.clear();
      args.removeAll("--force-run");
  }
  _arguments = args;

  if(!isServerRuns.isEmpty())
  {
    QString str = QString("CMD:showUp");
    QByteArray bytes;
    for(int i=1; i<_arguments.size(); i++)
    {
       str.append(QString("\n%1").arg(_arguments[i]));
    }
    bytes = str.toUtf8();
    socket->write(bytes);
    socket->flush();
    QThread::msleep(100);
    socket->close();
  }
  else
  {
    // The attempt was insuccessful, so we continue the program
    _shouldContinue = true;
    server = new LocalServer();
    server->start();
    QObject::connect(server, SIGNAL(showUp()), this, SLOT(slotShowUp()));
    QObject::connect(server, SIGNAL(dataReceived(QString)), this, SLOT(slotOpenFile(QString)));
    QObject::connect(server, SIGNAL(acceptedCommand(QString)), this, SLOT(slotAcceptedCommand(QString)));
    QObject::connect(this, SIGNAL(stopServer()), server, SLOT(stopServer()));
  }
}