Exemple #1
0
    foreach (Sliver *sliver, slivers) {
        sliver->status = Sliver::STATUS_OFFLINE;
        sliverHash[sliver->name] = sliver;
        if (relayEnabled()) {
            installProgram(sliver);
            addSliverConnection(sliver);
        } else {
            if (sliver->IPv6.isEmpty()) {
                qDebug() << "No ip, getting address";
                getIpAddress(sliver);
                installProgram(sliver);
            } else {
                addSliverConnection(sliver);
                QTimer *timer = new QTimer(this);
                //if there's a specified IP address, give the connection some time before running the script setting things up.
                connect(timer, &QTimer::timeout, [timer, sliver, this]() {
                    qDebug() << "Checking connection status";
                    if (sliver->status == sliver->STATUS_OFFLINE) {
                        qDebug() << "Still offline, reinstalling";
                        installProgram(sliver);
                    }
                    timer->stop();
                    timer->deleteLater();
                });
                timer->start(3000);
            }
        }

        QTimer *timer = new QTimer(this);


        //Will try to connect as long as the sliver is not connected
        connect(timer, &QTimer::timeout, [timer, sliver, this]() {
            if (sliver->status != sliver->STATUS_CONNECTED) {
                qDebug() << "Retryign connection";
                addSliverConnection(sliver);
            } else {
                timer->stop();
                timer->deleteLater();
            }

            static int time = 0;
            time+=3;
            //if (time > 35) {
             //   shutDownNodeprogs(QList<Sliver*>() << sliver);
              //  installProgram(sliver);
               // time = 0;
           // }
        });
        timer->start(3000);
    }
Exemple #2
0
void Sound::slotNotificationDisplayed(Snore::Notification notification)
{
    if (notification.hints().value("silent").toBool()) {
        return;
    }
    m_player->setVolume(settingsValue(QLatin1String("Volume")).toInt());

    QString sound = notification.hints().value("sound").toString();
    if (sound.isEmpty()) {
        sound = settingsValue(QLatin1String("Sound")).toString();
    }
    snoreDebug(SNORE_DEBUG) << "SoundFile:" << sound;
    if (!sound.isEmpty()) {
        m_player->setMedia(QUrl::fromLocalFile(sound));
        snoreDebug(SNORE_DEBUG) << "SoundFile:" << m_player->media().canonicalUrl();
        m_player->play();
        QTimer *timeout = new QTimer(this);
        timeout->setSingleShot(true);
        timeout->setInterval(notification.timeout() * 1000);
        connect(timeout, &QTimer::timeout, [this, timeout] {
            m_player->stop();
            timeout->deleteLater();
        });
    }
}
Exemple #3
0
void UpdaterPrivate::StopUpdateCheck(int delay, bool async) {
    if (main_process == nullptr || main_process->state() == QProcess::NotRunning) {
        return;
    }

    if (delay > 0) {
        main_process->terminate();
        if (async) {
            QTimer* timer = new QTimer(this);
            timer->setSingleShot(true);

            connect(timer, &QTimer::timeout, [=]() {
                StopUpdateCheck(0, false);
                timer->deleteLater();
            });

            timer->start(delay);
        } else {
            if (!main_process->waitForFinished(delay)) {
                main_process->kill();
                main_process->waitForFinished(100);
            }
        }
    } else {
        main_process->kill();
        main_process->waitForFinished(100);
    }
}
Exemple #4
0
void Controller::doLater(int msec, QObject *receiver, lambda func)  {
    QTimer *timer = new QTimer(receiver);
    QObject::connect(timer, &QTimer::timeout, receiver,
                     [timer, func](){ func(); timer->deleteLater(); });
    timer->setInterval(msec);
    timer->start();
}
Exemple #5
0
void UbuntuPlugin::activator()
{
    QTimer *timer = (QTimer*)sender();
    QWidget *w = sender()->property("widget").value<QWidget*>();

    /*w->activateWindow();
    w->raise();*/
    X11Util::forceActivateWindow(w->winId());
    timer->deleteLater();
}
Exemple #6
0
int main(int argc, char** argv) {
    auto glversion = gl::getAvailableVersion();
    auto major = GL_GET_MAJOR_VERSION(glversion);
    auto minor = GL_GET_MINOR_VERSION(glversion);

    if (glversion < GL_MAKE_VERSION(4, 1)) {
        MessageBoxA(nullptr, "Interface requires OpenGL 4.1 or higher", "Unsupported", MB_OK);
        return 0;
    }
    QGuiApplication app(argc, argv);

    bool quitting = false;
    // FIXME need to handle window closing message so that we can stop the timer
    GLWindow* window = new GLWindow();
    window->create();
    window->show();
    window->setSurfaceType(QSurface::OpenGLSurface);
    window->setFormat(getDefaultOpenGLSurfaceFormat());
    bool contextCreated = false;
    QTimer* timer = new QTimer();
    QObject::connect(timer, &QTimer::timeout, [&] {
        if (quitting) {
            return;
        }
        if (!contextCreated) {
            window->createContext();
            contextCreated = true;
        }
        if (!window->makeCurrent()) {
            throw std::runtime_error("Failed");
        }
        glClearColor(1.0f, 0.0f, 1.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        window->swapBuffers();
        window->doneCurrent();
    });
    // FIXME need to handle window closing message so that we can stop the timer
    QObject::connect(&app, &QCoreApplication::aboutToQuit, [&] {
        quitting = true;
        QObject::disconnect(timer, &QTimer::timeout, nullptr, nullptr);
        timer->stop();
        timer->deleteLater();
    });

    timer->setInterval(15);
    timer->setSingleShot(false);
    timer->start();
    app.exec();
    return 0;
}
void ScriptEngine::timer()
{
    QTimer *t = (QTimer*) sender();
    if (timerEvents[t].isFunction()) {
        timerEvents[t].call();
    } else if (timerEvents[t].isString()) {
        eval(timerEvents[t].toString());
    } else {
        warn("ScriptEngine::timer", "this is a bug, report it. code is not string or function");
        return;
    }

    if (t->isSingleShot()) {
        timerEvents.remove(t);
        t->deleteLater();
    }
}
void NetworkManager::init()
{
    QTimer *dbusCheckTimer = new QTimer;
    dbusCheckTimer->setInterval(100);
    dbusCheckTimer->setSingleShot(false);

    auto checkFunc = [=] {
        if (!m_networkInter->isValid())
            return;

        QTimer::singleShot(100, this, &NetworkManager::reloadDevices);
        QTimer::singleShot(150, this, &NetworkManager::reloadActiveConnections);
        dbusCheckTimer->deleteLater();
    };

    connect(dbusCheckTimer, &QTimer::timeout, checkFunc);
    dbusCheckTimer->start();
}
Exemple #9
0
void Configuration::sendRequest(const QUrl &url)
{
	d->req.setUrl(url);
	QNetworkReply *reply = d->net->get(d->req);
	d->requestcache << reply;
	QTimer *timer = new QTimer(this);
	timer->setSingleShot(true);
	connect(timer, &QTimer::timeout, [=]{
		timer->deleteLater();
		if(!d->requestcache.contains(reply))
			return;
		d->requestcache.removeAll(reply);
		reply->deleteLater();
		qDebug() << "Request timed out";
		Q_EMIT finished(false, tr("Request timed out"));
	});
	timer->start(30*1000);
}
int ScriptEngine::unsetAllTimers()
{
    int i = 0;
    QHashIterator <QTimer*, QScriptValue> it (timerEvents);
    while (it.hasNext()) {
        it.next();
        QTimer *timer = it.key();

        timer->stop();
        timer->blockSignals(true);

        timerEvents.remove(timer);
        timer->deleteLater();
        i++;
    }

    return i;
}
bool ScriptEngine::unsetTimer(int timerId)
{
    QHashIterator <QTimer*, QScriptValue> it (timerEvents);
    while (it.hasNext()) {
        it.next();
        QTimer *timer = it.key();

        if (timer->timerId() == timerId) {
            timer->stop();
            timer->blockSignals(true);

            timerEvents.remove(timer);
            timer->deleteLater();
            return true; // Timer found.
        }
    }
    warn ("unsetTimer(timerId)", "no timer with that id");
    return false; // No timer found.
}
void SchedulerServiceThread::executeCommand(){

    Parser::QBoolParser::resetInstance();
    Parser::QMathParser *parser = new Parser::QMathParser(this);
    Parser::QScriptBlock *block = new Parser::QScriptBlock(parser);

    QString s = sender()->objectName();
    s = s.split("\n").last();

    if(sender()->objectName().startsWith("timer\n")){
        s = s.split("\n").last();

        //Code nehmen und ausführen
        block->exec(QString::fromUtf8(QByteArray::fromHex(this->_instructions->value(s)->scriptCode.toUtf8())));
        this->_instructions->value(s)->count++;

        //Speichern
        this->saveToFile();
        parser->deleteLater();
        return;
    }

    //Allgemeine Daten holen
    SchedulerServiceThread::Task *task = this->_instructions->value(s);
    QTimer *timer = qobject_cast<QTimer *>(sender());

    //Block ausführen & Done
    block->exec(QString::fromUtf8(QByteArray::fromHex(task->scriptCode.toUtf8())));
    task->done = true;

    //Timer löschen
    timer->stop();
    timer->deleteLater();
    parser->deleteLater();

    //Speichern
    this->saveToFile();
}
void
ModuleManager::loadModules( Phase phase )
{
    //FIXME: When we depend on Qt 5.4 this ugly hack should be replaced with
    //       QTimer::singleShot.
    QTimer* timer = new QTimer();
    timer->setSingleShot( true );
    connect( timer, &QTimer::timeout,
             this, [ this, timer, phase ]()
    {
        foreach ( const QString& moduleName, Settings::instance()->modules( phase ) )
        {
            if ( !m_availableModules.contains( moduleName ) )
            {
                cDebug() << "Module" << moduleName << "not found in module search paths."
                         << "\nCalamares will now quit.";
                qApp->exit( 1 );
                return;
            }
            if ( m_availableModules.value( moduleName )->isLoaded() )
            {
                cDebug() << "Module" << moduleName << "already loaded.";
                continue;
            }

            doLoad( moduleName );
        }
        emit modulesLoaded( phase );
        // Loading sequence:
        // 1) deps are already fine. check if we have all the modules needed by the roster
        // 2) ask ModuleManager to load them from the list provided by Settings
        // 3) MM must load them asyncly but one at a time, by calling Module::loadSelf
        // 4) Module must have subclasses that reimplement loadSelf for various module types

        timer->deleteLater();
    });
void MessageBoxType4::initPost(const QJsonObject &post) {
    QPalette pal;
    pal.setColor(QPalette::Background, Qt::white);

    QFont nameFont;
    nameFont.setBold(true);

    QString offsetStyleSheet = "margin-left: " + QString::number(MessageBoxType4::commentOffset) + ";";

    userName = new QLabel(this);
    userName->setFont(nameFont);
    userName->setStyleSheet(offsetStyleSheet + "color: gray;");

    memberText = new QLabel(this);
    memberText->setAutoFillBackground(true);
    memberText->setPalette(pal);

    commentText = new QLabel(this);
    commentText->setAutoFillBackground(true);
    //commentText->setPalette(pal);
    commentText->setStyleSheet(offsetStyleSheet + "background-color: white;"
                                                  "color: gray");

    if(parentWidget() != NULL) {
        memberText->setFixedWidth(parentWidget()->width() - 40);
        commentText->setFixedWidth(parentWidget()->width() - 40 - MessageBoxType4::commentOffset);
    }

    QJsonArray postBody = post["body"].toArray();

    QString text = "";
    QString comment = "";
    for(int i = 0; i < postBody.count(); i++) {
        QJsonObject obj = postBody[i].toObject();
        int bodyType = obj["bodyType"].toInt();
        if(bodyType == 1)
            text += obj["text"].toString();
        else if(bodyType == 4) {
            QJsonObject commentJson = obj["comment"] .toObject();

            userName->setText(commentJson["sendUserName"].toString());
            commentText->setText(commentJson["text"].toString());
            commentText->setWordWrap(true);
            commentText->setMinimumHeight(commentText->sizeHint().height());
        }

    }
    memberText->setText(text);
    memberText->setWordWrap(true);
    memberText->setMinimumHeight(memberText->sizeHint().height());

    layout->addWidget(memberText, 1, 0);
    layout->addWidget(userName, 2, 0);
    layout->addWidget(commentText, 3, 0);

    setFixedHeight(sizeHint().height());

    QTimer *timer = new QTimer;
    QObject::connect(timer, &QTimer::timeout, [=] {
        timer->stop();
        timer->deleteLater();
        emit boxFinished(this);
    });
    timer->start(100);


}
Exemple #15
0
void Reader_RFM008B::readData()
{
    if(m_serial->canReadLine()){
        if(!allLines){

//            Logger::instance()->writeRecord(Logger::severity_level::debug, m_module, Q_FUNC_INFO, QString("Reading Data..."));

            QByteArray buffer = m_serial->readAll();
            QRegExp regex;
            regex.setPattern("(L(\\d{2})?W)\\s([0-9a-fA-F]{4})\\s([0-9a-fA-F]{16})");

            QString data(buffer);
            data.remove(QRegExp("[\\n\\t\\r]"));

            //        if(m_outReceived.device()){
            //            m_outReceived << data;
            //            m_outReceived.flush();
            //        }


            int pos = regex.indexIn(data);
            if(pos != -1){
                // The first string in the list is the entire matched string.
                // Each subsequent list element contains a string that matched a
                // (capturing) subexpression of the regexp.
                QStringList matches = regex.capturedTexts();

                // crear RFIDData
                QRegularExpression regexCode;
                regexCode.setPattern("([0-9a-fA-F]{4})(\\s)([0-9a-fA-F]{16})");
                QRegularExpressionMatch match = regexCode.match(matches.at(0));

                if(m_outCaptured.device()){
                    m_outCaptured << matches.at(0);
                    m_outCaptured.flush();
                }

                if(match.hasMatch()) {
                    Rfiddata *data = new Rfiddata(this);

                    // Id collector from configuration file
                    data->setIdpontocoleta(idCollector);

                    // This module can read from only one antena, so the idAntena is static.
                    int idAntena = 1;
                    data->setIdantena(idAntena);

                    qlonglong applicationcode = match.captured(1).toLongLong();
                    qlonglong identificationcode = match.captured(3).toLongLong();

                    /*
                 * Filter by time. If more than one transponder was read in a time interval only one of them will be persisted.
                 * A QMap is used to verify if each new data that had arrived was already read in this interval.
                 */
                    if(!m_map.contains(identificationcode)){

                        QTimer *timer = new QTimer;
                        timer->setSingleShot(true);
                        timer->setInterval(1000);
                        connect(timer, &QTimer::timeout,
                                [=, this]()
                        {
                            this->m_map.remove(identificationcode);
                            timer->deleteLater();
                        });
                        m_map.insert(identificationcode, timer);
                        timer->start();

                        data->setApplicationcode(applicationcode);
                        data->setIdentificationcode(identificationcode);
                        data->setDatetime(QDateTime::currentDateTime());
                        data->setSync(Rfiddata::KNotSynced);

                        QList<Rfiddata*> list;
                        list.append(data);
                        try {
                            PersistenceInterface *persister = qobject_cast<PersistenceInterface *>(RFIDMonitor::instance()->defaultService(ServiceType::KPersister));
                            Q_ASSERT(persister);
                            SynchronizationInterface *synchronizer = qobject_cast<SynchronizationInterface*>(RFIDMonitor::instance()->defaultService(ServiceType::KSynchronizer));
                            Q_ASSERT(synchronizer);

#ifdef CPP_11_ASYNC
                            /*C++11 std::async Version*/
                            std::function<void(const QList<Rfiddata *>&)> persistence = std::bind(&PersistenceInterface::insertObjectList, persister, std::placeholders::_1);
                            std::async(std::launch::async, persistence, list);
                            std::function<void()> synchronize = std::bind(&SynchronizationInterface::readyRead, synchronizer);
                            std::async(std::launch::async, synchronize);
#else
                            /*Qt Concurrent Version*/
                            QtConcurrent::run(persister, &PersistenceInterface::insertObjectList, list);
                            QtConcurrent::run(synchronizer, &SynchronizationInterface::readyRead);
#endif
                        } catch (std::exception &e) {
                            Logger::instance()->writeRecord(Logger::severity_level::fatal, m_module, Q_FUNC_INFO, e.what());
                        }
                    }
                }
            }
        }else{

            //            Logger::instance()->writeRecord(Logger::severity_level::debug, m_module, Q_FUNC_INFO, QString("FULL READ..."));

            QByteArray buffer = m_serial->readLine();
            QString data(buffer);
            data.remove(QRegExp("[\\n\\t\\r]"));

            // Remove lines only with LI. Not used anywhere.
            if(data == "LI")
                return;

            json::NodeJSMessage answer;
            answer.setType("READER-RESPONSE");

            QJsonObject dataObj;
            dataObj.insert("sender", QString("app"));
            dataObj.insert("response", data);
            dataObj.insert("reader", QString("1"));

            answer.setDateTime(QDateTime::currentDateTime());
            answer.setJsonData(dataObj);
            QJsonObject jsonAnswer;
            answer.write(jsonAnswer);


            static CommunicationInterface *communitacion = 0;
            communitacion = qobject_cast<CommunicationInterface *>(RFIDMonitor::instance()->defaultService(ServiceType::KCommunicator));

#ifdef CPP_11_ASYNC
            /*C++11 std::async Version*/
            std::function<void (QByteArray)> sendMessage = std::bind(&CommunicationInterface::sendMessage, communitacion, std::placeholders::_1);
            std::async(std::launch::async, sendMessage, QJsonDocument(jsonAnswer).toJson());
#else
            /*Qt Concurrent Version*/
            QtConcurrent::run(communitacion, &CommunicationInterface::sendMessage, QJsonDocument(jsonAnswer).toJson());
#endif
        }
    }
}
Exemple #16
0
Common::Common( int &argc, char **argv, const QString &app, const QString &icon )
	: BaseApplication( argc, argv )
{
	setApplicationName( app );
	setApplicationVersion( QString( "%1.%2.%3.%4" )
		.arg( MAJOR_VER ).arg( MINOR_VER ).arg( RELEASE_VER ).arg( BUILD_VER ) );
	setOrganizationDomain( "ria.ee" );
	setOrganizationName( ORG );
	setWindowIcon( QIcon( icon ) );
	if( QFile::exists( QString("%1/%2.log").arg( QDir::tempPath(), app ) ) )
		qInstallMessageHandler(msgHandler);

#ifdef BREAKPAD
	new QBreakPad(this);
#ifdef TESTING
	if( arguments().contains( "-crash" ) )
	{
		QBreakPad *crash;
		delete crash;
	}
#endif
#endif

	Q_INIT_RESOURCE(common_images);
	Q_INIT_RESOURCE(common_tr);
#if defined(Q_OS_WIN)
	setLibraryPaths( QStringList() << applicationDirPath() );
#elif defined(Q_OS_MAC)
	setLibraryPaths( QStringList() << applicationDirPath() + "/../PlugIns" );
#endif
	setStyleSheet(
		"QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 0; }\n" );
	QPalette p = palette();
	p.setBrush( QPalette::Link, QBrush( "#509B00" ) );
	p.setBrush( QPalette::LinkVisited, QBrush( "#509B00" ) );
	setPalette( p );

	qRegisterMetaType<TokenData>("TokenData");

	QNetworkProxyFactory::setUseSystemConfiguration(true);

#if defined(Q_OS_WIN)
	AllowSetForegroundWindow( ASFW_ANY );
#elif defined(Q_OS_MAC)
#ifdef BREAKPAD
	if(arguments().contains("-crashreport", Qt::CaseInsensitive))
		return;
#endif
	if(!QSettings().value("plugins").isNull())
		return;

	QTimer *timer = new QTimer(this);
	timer->setSingleShot(true);
	connect(timer, &QTimer::timeout, this, [=]{
		timer->deleteLater();
		QMessageBox *b = new QMessageBox(QMessageBox::Information, tr("Browser plugins"),
			tr("If you are using e-services for authentication and signing documents in addition to "
				"Mobile-ID an ID-card or only ID-card, you should install the browser integration packages.<br />"
				"<a href='http://installer.id.ee'>http://installer.id.ee</a>"),
			0, activeWindow());
		QAbstractButton *install = b->addButton(tr("Install"), QMessageBox::AcceptRole);
		b->addButton(tr("Remind later"), QMessageBox::AcceptRole);
		QAbstractButton *ignore = b->addButton(tr("Ignore forever"), QMessageBox::AcceptRole);
		b->exec();
		if(b->clickedButton() == install)
			QDesktopServices::openUrl(QUrl("http://installer.id.ee"));
		else if(b->clickedButton() == ignore)
			QSettings().setValue("plugins", "ignore");
	});
	timer->start(1000);
#endif
}
/*
 * This function works pretty much like routTcpMessage only that this one interpretes message from RFIDMonitor and don't verify packages size.
 * it only tries to interpret data just arrived.
 */
void RFIDMonitorDaemon::routeIpcMessage()
{
    QByteArray message = ipcConnection->readAll();
    json::NodeJSMessage nodeMessage;

    nodeMessage.read(QJsonDocument::fromJson(message).object());
    QString messageType(nodeMessage.type());

    if(messageType == "SYN"){

        m_restoreTimer.stop();
        ipcSendMessage(buildMessage(QJsonObject(), "ACK-SYN").toJson());
        qApp->processEvents();

        /* When the deskApp change some configuration the RFIDMonitor is restarted.
         * But, the RFIDMonitor starts with flag connection=false. And if the server is connected the RFIDMonitor don't know that yet.
         * To solve this, after 1 seconds a SYNC message is sent to RFIDMonitor to set true to connection flag.
         */
        if(isConnected)
        {
            QTimer *timer = new QTimer();
            timer->setSingleShot(true);
            timer->setInterval(1000);
            connect(timer, &QTimer::timeout, [=](){
                ipcSendMessage(buildMessage(QJsonObject(), "SYNC").toJson());
                timer->deleteLater();
            });
            timer->start();
        }

        m_configManager->restartNetwork();

    }else if (messageType == "READER-RESPONSE") {
        QJsonObject command(nodeMessage.jsonData());
        /*
         * When a 'reader response' message is received is because someone sent a 'reader command' message. So it needs to know who did it.
         * To perform this it uses a field called 'sender' that carry the name of who sent the 'command message'.
         * And based on that, it will respond to the server connection or to the deskApp connection.
         *
         * see reoutTcpMessage (messageType == "READER-COMMAND")
         */
        if(command.value("sender").toString() == "server")
            tcpSendMessage(m_tcpSocket, message);
        else
            tcpSendMessage(m_tcpAppSocket, message);

    }else if (messageType == "DATA"){
        /*
         * A Data message means that the RFIDMonitor is trying to sync some data into the server. So, it just send this message to the server.
         */
//        qDebug() <<  "DATA Message Received from Monitor\n";
//        qDebug() <<  QString(QJsonDocument(nodeMessage.jsonData()).toJson());
        // Only a node.js server receives DATA messages.
        tcpSendMessage(m_tcpSocket, message);

    }else if (messageType == "STOPPED"){
        qDebug() << "STOPPED";
        m_process.kill();
//        qDebug() << "Process Killed, PID: " << m_process.pid();
    }
    else if (messageType == "ACK-UNKNOWN") {
        QJsonDocument unknown(nodeMessage.jsonData());
        QJsonObject dataObj(unknown.object().value("unknownmessage").toObject());
        qDebug() <<  "The Monitor don't understand the message type: "
                        << dataObj.value("type").toString();
    }
    else{
        /* When receives a message that can't be interpreted like any type is an unknown message.
         * In this case an ACK-UNKNOWN message is built and sent to the connection that received this message
         */
        qDebug() <<  "UNKNOWN MESSAGE";

        QJsonObject unknownObj;
        unknownObj.insert("unknownmessage", QJsonDocument::fromJson(message).object());
        unknownObj.insert("errorinfo", QString("Unknown message received"));

        ipcSendMessage(buildMessage(unknownObj, "ACK-UNKNOWN").toJson());
    }
}
/*
 * The routeTcpMessage() receives messages from any TCP connection. The Daemon can be connected with server and deskApp at the same time, but it will know which connection received data.
 * Any message arrive by TCP must to have two parts. The first part defines the data size of the coming package (second part) and must to be an 8 bytes String (always 8 bytes).
 *
 * The algoritm works like this:
 * When some data arrive it verifies (using the hasPackage variable) if is the first part or the second one of the complete message;
 * If hasPackage is true then is especting the second part of the message, otherwise the dada just arrived is the size information.
 *
 * The information of size correspond to the size of the message package. So, when more data arrive it verifies if the size is greater than or equals to the expected size.
 * If true the message is all here and can go on, otherwise the message is coming and it will wait for more data.
 *
 * When all the message arrives it will interpret and route it (by message type) to the right way.
 *
 */
void RFIDMonitorDaemon::routeTcpMessage()
{
    QTcpSocket *connection = (QTcpSocket *) QObject::sender();

    static bool hasPackage = false;
    static quint64 packageSize = 0;

    if( ! hasPackage){

        if((quint64)connection->bytesAvailable() < sizeof(quint64))
            return;

        //    	m_tcpSocket->read((char *)&packageSize, sizeof(quint64));
        QString packageSizeStr(connection->read(sizeof(quint64)));
        packageSize = packageSizeStr.toULongLong();

        qDebug() <<  QString("Message = %1 - Size of coming package: %2").arg(packageSizeStr).arg(QString::number(packageSize));
        hasPackage = true;
    }

    if((quint64)connection->bytesAvailable() >=  packageSize){
        QByteArray data(connection->read(packageSize));

        json::NodeJSMessage nodeMessage;

        nodeMessage.read(QJsonDocument::fromJson(data).object());
        QString messageType(nodeMessage.type());

        qDebug() << QString("New Message Received: %1").arg(QString(data));


        if(messageType == "SYN-ALIVE"){

            tcpSendMessage(connection, buildMessage(m_configManager->identification(), "ACK-ALIVE").toJson());
            qDebug() << QString("New Message Received: %1").arg(messageType);
        }
        else if (messageType == "ACK-SYN") {

            QJsonObject obj(nodeMessage.jsonData());
            if(!obj.isEmpty()){
                m_configManager->setIdentification(obj);
            }

            bool statusDateTime = m_configManager->setDateTime(nodeMessage.dateTime());
            QJsonObject response = m_configManager->identification();
            response["success"] = QJsonValue(statusDateTime);

            tcpSendMessage(connection, buildMessage(response, "ACK").toJson());

            // Informe RFIDMonitor that server is now connected. Wait 2 seconds;
            if(connection->objectName() == "server"){
                isConnected = true;
                QTimer *timer = new QTimer();
                timer->setSingleShot(true);
                timer->setInterval(2000);
                connect(timer, &QTimer::timeout, [=](){
                    ipcSendMessage(buildMessage(QJsonObject(), "SYNC").toJson());
                    timer->deleteLater();
                });
                timer->start();
            }
        }else if (messageType == "GET-CONFIG") {
            tcpSendMessage(connection, buildMessage(m_configManager->currentConfig(), "CONFIG").toJson());

        }else if (messageType == "READER-COMMAND") {

            QJsonObject command(nodeMessage.jsonData());
            /*
             * When a 'reader command' message is received is because someone is sending a command to the reader. So it needs to send also who is doing this.
             * To perform this it uses a field called 'sender' that carry the name of who is sending the 'command message'.
             * And based on that, it will respond to the server connection or to the deskApp connection
             *
             * see reoutIcpMessage (messageType == "READER-RESPONSE")
             */
            if(connection->objectName() == "server")
                command.insert("sender", QString("server"));
            else
                command.insert("sender", QString("app"));

            ipcSendMessage(buildMessage(command, "READER-COMMAND").toJson());

        }else if (messageType == "NEW-CONFIG") {

            QJsonObject newConfig(nodeMessage.jsonData());
            bool ackConf;
            if(m_configManager->newConfig(newConfig))
            {
                // Send a message to stop the RFIDMonitor
                emit restartMonitor();
                ackConf = true;
            }else{
                ackConf = false;
            }
            QJsonObject dataObj;
            dataObj.insert("success", QJsonValue(ackConf));
            tcpSendMessage(connection, buildMessage(dataObj, "ACK-NEW-CONFIG").toJson());

            if(m_tcpAppSocket->isOpen())
                m_tcpAppSocket->close();

        }else if (messageType == "DATETIME") {

            QJsonObject dataObj;
            dataObj["success"] =  QJsonValue(m_configManager->setDateTime(nodeMessage.dateTime()));
            tcpSendMessage(connection, buildMessage(dataObj, "ACK").toJson());

        }else if (messageType == "ACK-DATA") {
            // A ACK-DATA message means that the server is trying to inform the RFIDMonitor that some data is now synced. So, it just send this message to the RFIDMonitor.
            ipcSendMessage(data);

        }else if (messageType == "GET-NET-CONFIG") {
            // Only return the network configuration.
            tcpSendMessage(connection, buildMessage(m_configManager->netConfig(), "NET-CONFIG").toJson());

        }else if (messageType == "NEW-NET") {

            QJsonObject network = nodeMessage.jsonData();
            // Receive a new configuration for the network (ssid and password).
            QJsonObject dataObj;
            dataObj.insert("success", QJsonValue(m_configManager->setNetConfig(network)));

            // returns a message ACK-NET to inform the sender that the new configuration was set
            tcpSendMessage(connection, buildMessage(dataObj, "ACK-NET").toJson());

            // Try to restar the network service to already use the new configuration
            bool resetNet = m_configManager->restartNetwork();
            qDebug() <<  QString(resetNet? "Network restarted" : "Networkt Don't restarted");

        }else if (messageType == "ACK-UNKNOWN") {
            QJsonDocument unknown(nodeMessage.jsonData());
            QJsonObject oldMessage(unknown.object().value("unknownmessage").toObject());
            qDebug() <<  "The server don't understand the message type: " << oldMessage.value("type").toString();
            qDebug() <<  "ERROR message: " << unknown.object().value("errorinfo").toString();

        }else if (messageType == "FULL-READ"){
            ipcSendMessage(data);

        }else{
            /* When receives a message that can't be interpreted like any type is an unknown message.
             * In this case an ACK-UNKNOWN message is built and sent to the connection that received this message
             */
            qDebug() <<  "UNKNOWN MESSAGE";
            QJsonObject unknownObj;
            unknownObj.insert("unknownmessage", QJsonValue(QJsonDocument::fromJson(data).object()));
            unknownObj.insert("errorinfo", QString("Unknown message received"));
            tcpSendMessage(connection, buildMessage(unknownObj, "ACK-UNKNOWN").toJson());
        }

        /* when all the process is done, reset the expecting message size to zero and the haspackage to false.
         * Then when more data arrive it must to be the size information again.
         */
        packageSize = 0;
        hasPackage = false;
    }
}
Exemple #19
0
void Tunneld::promiseChannelCleanup(ToxTunChannel *chan)
{
    qDebug()<<chan<<sender();
    QObject *snderobj = (QObject*)sender();
    QTimer *repeat_timer = NULL;

    qDebug()<<snderobj->objectName()<<snderobj->metaObject()->className();
    if (chan == NULL) {
        repeat_timer = (QTimer*)snderobj;
        assert(repeat_timer != NULL);
        int conid = repeat_timer->property("conid").toInt();
        if (!m_conid_chans.contains(conid)) {
            qDebug()<<"maybe too late repeat check self sock close timer event";
            repeat_timer->deleteLater();
            return;
        }
        chan = m_conid_chans[conid];
        assert(chan != NULL);
    } else {
        // snderobj is ENetPoll or QTcpSocket
    }
    QTcpSocket *sock = chan->m_sock;
    ENetPeer *enpeer = chan->m_enpeer;

    //////////
    QHash<QString, bool> promise_results;

    promise_results["sock_closed"] = chan->sock_closed;
    // promise_results["enet_closed"] = chan->enet_closed;
    promise_results["peer_sock_closed"] = chan->peer_sock_closed;

    bool promise_result = true;
    for (auto it = promise_results.begin(); it != promise_results.end(); it ++) {
        QString key = it.key();
        bool val = it.value();
        promise_result = promise_result && val;
    }

    if (true) {
        // 检测对方最近的回包情况
        if (!promise_result && repeat_timer == NULL
            && promise_results["peer_sock_closed"] && !promise_results["sock_closed"]) {
            qDebug()<<"here";
            if (chan->last_recv_peer_pkt_time == QDateTime()) {
                qDebug()<<"maybe can close socket right now, because recv nothing forever";
            }
            
            QTimer *t = new QTimer();
            t->setInterval(500);
            t->setSingleShot(true);
            t->setProperty("conid", QVariant(chan->m_conid));
            // // QObject::connect(t, &QTimer::timeout, this, &Tunneld::promiseChannelCleanup, Qt::QueuedConnection);
            QObject::connect(t, SIGNAL(timeout()), this, SLOT(promiseChannelCleanup()), Qt::QueuedConnection);
            qDebug()<<"start repeat check sock close timer:";
            t->start();
        }
        if (!promise_result && repeat_timer != NULL
            && promise_results["peer_sock_closed"] && !promise_results["sock_closed"]) {
            //
            QDateTime now_time = QDateTime::currentDateTime();
            uint32_t last_recv_to_now_time = chan->last_recv_peer_pkt_time.msecsTo(now_time);
            qDebug()<<"here:"<<last_recv_to_now_time<<enpeer->lastReceiveTime;
            if (last_recv_to_now_time > 7000) {
                qDebug()<<"last recv to now, force close self socket:"<<last_recv_to_now_time
                        <<enpeer->incomingPeerID<<enpeer->outgoingPeerID;
                // 不能直接关闭,要在当前函数执行完后,即下一次事件的时候开始执行。
                QTimer::singleShot(1, sock, &QTcpSocket::close);
                // QTimer *t = new QTimer();
                // t->setSingleShot(true);
                // QObject::connect(t, &QTimer::timeout, sock, &QTcpSocket::close, Qt::QueuedConnection);
                // t->start(1);
                
                repeat_timer->deleteLater();
            } else {
                repeat_timer->start();
            }
        }
    }
    
    if (!promise_result) {
        qDebug()<<"promise nooooot satisfied:"<<promise_results<<chan->m_conid;
        return;
    }
    
    chan->promise_close_time = QDateTime::currentDateTime();
    qDebug()<<"promise satisfied."<<chan->m_conid;

    ///// do cleanup
    bool force_closed = chan->force_closed;
    
    // enpeer->toxchan = NULL;  // cleanup
    peerRemoveChan(enpeer, chan);
    
    this->m_sock_chans.remove(sock);
    // this->m_enpeer_chans.remove(enpeer);
    this->m_conid_chans.remove(chan->m_conid);

    delete chan;
    sock->disconnect();
    sock->deleteLater();
    if (repeat_timer != NULL) repeat_timer->deleteLater();
    qDebug()<<"curr chan size:"<<this->m_sock_chans.count()<<this->m_conid_chans.count();

    if (force_closed) {
        return;
    }

    // 延时关闭enet_peer
    QTimer *t = new QTimer();
    auto later_close_timeout = [enpeer, t]() {
        qDebug()<<enpeer<<enpeer->state;
        if (enpeer->state != ENET_PEER_STATE_CONNECTED) {
            qDebug()<<"warning, peer currently not connected:"<<enpeer->incomingPeerID;
        }

        if (! (enet_list_empty (& enpeer -> outgoingReliableCommands) &&
               enet_list_empty (& enpeer -> outgoingUnreliableCommands) && 
               enet_list_empty (& enpeer -> sentReliableCommands))) {
            qDebug()<<"warning, maybe has unsent packet:"<<enpeer->incomingPeerID;
        }

        qDebug()<<"last recv time:"<<enpeer->incomingPeerID
        <<enetx_time_diff(enpeer->lastReceiveTime, enet_time_get());

        qDebug()<<"restore peer timeout, ping interval";
        enet_peer_timeout(enpeer, ENET_PEER_TIMEOUT_LIMIT*2,
                          ENET_PEER_TIMEOUT_MINIMUM*2, ENET_PEER_TIMEOUT_MAXIMUM*2);
        enet_peer_ping_interval(enpeer, ENET_PEER_PING_INTERVAL*2);

        // enet_peer_disconnect_now(enpeer, qrand());
        enet_peer_disconnect_later(enpeer, qrand());
        t->deleteLater();
    };

    qDebug()<<"last recv time:"<<enpeer->incomingPeerID
            <<enetx_time_diff(enpeer->lastReceiveTime, enet_time_get());
    // QTimer::singleShot(5678, later_close_timeout);
    t->setInterval(5678);
    t->setSingleShot(true);
    QObject::connect(t, &QTimer::timeout, later_close_timeout);
    t->start();
}