//--------------------------------------------------------------------------------------------
void MArduinoConnector::InitPort()
{
qsrand(1234578);

//  QSerialPort* pSerialPort = new QSerialPort(this);
//  QString sp;
  PStringMessage->clear();

  QString portName;//("COM4");
  foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
    if(info.description() == NameDevice) {
      portName = info.portName();
      *PStringMessage = info.description() + ":\n"
                      + QObject::tr("     Port: ") + info.portName() + "\n"
                      + QObject::tr("     Location: ") + info.systemLocation() + "\n"
//                      + QObject::tr("Description: ") + info.description() + "\n"
                      + QObject::tr("     Manufacturer: ") + info.manufacturer() + "\n"
                      + QObject::tr("     Vendor Identifier: ") + (info.hasVendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : QString()) + "\n"
                      + QObject::tr("     Product Identifier: ") + (info.hasProductIdentifier() ? QString::number(info.productIdentifier(), 16) : QString()) + "\n"
                      + QObject::tr("     Busy: ") + (info.isBusy() ? QObject::tr("Yes") : QObject::tr("No")) + "\n";
//QMessageBox msgBox;  msgBox.setText(sp);  msgBox.exec();
//  *PStringMessage = sp;
//      emit SignalMessage(PStringMessage);
      break;
    }
  }

  if(portName.isEmpty()) {
    *PStringMessage = NameDevice;  *PStringMessage += " is not connected.";
  }
  else {
    PPort = new QSerialPort(this);

//  connect(PPort, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(SlotPortError(QSerialPort::SerialPortError)));

    PPort->setPortName(portName);
    if(PPort->open(QIODevice::ReadWrite)) { // | QIODevice::Text)) { // | QIODevice::Unbuffered)) { //QIODevice::WriteOnly))  {
      PPort->setBaudRate(QSerialPort::Baud38400);//38400);
      PPort->setDataBits(QSerialPort::Data8);
      PPort->setParity(QSerialPort::NoParity);
      PPort->setStopBits(QSerialPort::OneStop);
      PPort->setFlowControl(QSerialPort::NoFlowControl); // QSerialPort::SoftwareControl

      PPort->setReadBufferSize(64);
//    PPort->clear(QSerialPort::AllDirections);

//    QMessageBox msgBox;  msgBox.setText("Port \""+portName+"\" is open");  msgBox.exec();
      *PStringMessage += "\nPort \""+portName+"\" is open.\n";

      connect(PPort, SIGNAL(readyRead()), SLOT(SlotReadyRead()));
    }
    else {
//    QMessageBox msg;  msg.setText("Port \""+portName+"\" is not open");  msg.exec();
      *PStringMessage += "\nPort \""+portName+"\" is not open.\n";

      delete PPort;  PPort = NULL;
    }
  }

  emit SignalMessage(PStringMessage);
}
Example #2
0
void InspectorServerRequestHandlerQt::tcpReadyRead()
{
    WebKit::QHttpRequestHeader header;
    bool isWebSocket = false;
    if (!m_tcpConnection)
        return;

    if (!m_endOfHeaders) {
        while (m_tcpConnection->bytesAvailable() && !m_endOfHeaders) {
            QByteArray line = m_tcpConnection->readLine();
            m_data.append(line);
            if (line == "\r\n")
                m_endOfHeaders = true;
        }
        if (m_endOfHeaders) {
            header = WebKit::QHttpRequestHeader(QString::fromLatin1(m_data));
            if (header.isValid()) {
                m_path = header.path();
                m_contentType = header.contentType().toLatin1();
                m_contentLength = header.contentLength();
                if (header.hasKey(QLatin1String("Upgrade")) && (header.value(QLatin1String("Upgrade")) == QLatin1String("WebSocket")))
                    isWebSocket = true;

                m_data.clear();
            }
        }
    }

    if (m_endOfHeaders) {
        QStringList pathAndQuery = m_path.split(QLatin1Char('?'));
        m_path = pathAndQuery[0];
        QStringList words = m_path.split(QLatin1Char('/'));

        if (isWebSocket) {
            // switch to websocket-style WebSocketService messaging
            if (m_tcpConnection) {
                m_tcpConnection->disconnect(SIGNAL(readyRead()));
                connect(m_tcpConnection, SIGNAL(readyRead()), SLOT(webSocketReadyRead()), Qt::QueuedConnection);

                QByteArray key3 = m_tcpConnection->read(8);

                quint32 number1 = parseWebSocketChallengeNumber(header.value(QLatin1String("Sec-WebSocket-Key1")));
                quint32 number2 = parseWebSocketChallengeNumber(header.value(QLatin1String("Sec-WebSocket-Key2")));

                char responseData[16];
                generateWebSocketChallengeResponse(number1, number2, (unsigned char*)key3.data(), (unsigned char*)responseData);
                QByteArray response(responseData, sizeof(responseData));

                WebKit::QHttpResponseHeader responseHeader(101, QLatin1String("WebSocket Protocol Handshake"), 1, 1);
                responseHeader.setValue(QLatin1String("Upgrade"), header.value(QLatin1String("Upgrade")));
                responseHeader.setValue(QLatin1String("Connection"), header.value(QLatin1String("Connection")));
                responseHeader.setValue(QLatin1String("Sec-WebSocket-Origin"), header.value(QLatin1String("Origin")));
                responseHeader.setValue(QLatin1String("Sec-WebSocket-Location"), (QLatin1String("ws://") + header.value(QLatin1String("Host")) + m_path));
                responseHeader.setContentLength(response.size());
                m_tcpConnection->write(responseHeader.toString().toLatin1());
                m_tcpConnection->write(response);
                m_tcpConnection->flush();

                if ((words.size() == 4)
                    && (words[1] == QString::fromLatin1("devtools"))
                    && (words[2] == QString::fromLatin1("page"))) {
                    int pageNum = words[3].toInt();

                    m_inspectorClient = m_server->inspectorClientForPage(pageNum);
                    // Attach remoteFrontendChannel to inspector, also transferring ownership.
                    if (m_inspectorClient)
                        m_inspectorClient->attachAndReplaceRemoteFrontend(this);
                }

            }

            return;
        }
        if (m_contentLength && (m_tcpConnection->bytesAvailable() < m_contentLength))
            return;

        QByteArray content = m_tcpConnection->read(m_contentLength);
        m_endOfHeaders = false;

        QByteArray response;
        int code = 200;
        QString text = QString::fromLatin1("OK");

        // If no path is specified, generate an index page.
        if (m_path.isEmpty() || (m_path == QString(QLatin1Char('/')))) {
            QString indexHtml = QLatin1String("<html><head><title>Remote Web Inspector</title></head><body><ul>\n");
            for (QMap<int, InspectorClientQt* >::const_iterator it = m_server->m_inspectorClients.begin();
                 it != m_server->m_inspectorClients.end(); 
                 ++it) {
                indexHtml.append(QString::fromLatin1("<li><a href=\"/webkit/inspector/inspector.html?page=%1\">%2</li>\n")
                                 .arg(it.key())
                                 .arg(it.value()->m_inspectedWebPage->mainFrame()->url().toString()));
            }
            indexHtml.append(QLatin1String("</ul></body></html>"));
            response = indexHtml.toLatin1();
        } else {
            QString path = QString::fromLatin1(":%1").arg(m_path);
            QFile file(path);
            // It seems that there should be an enum or define for these status codes somewhere in Qt or WebKit,
            // but grep fails to turn one up.
            // QNetwork uses the numeric values directly.
            if (file.exists()) {
                file.open(QIODevice::ReadOnly);
                response = file.readAll();
            } else {
                code = 404;
                text = QString::fromLatin1("Not OK");
            }
        }

        WebKit::QHttpResponseHeader responseHeader(code, text, 1, 0);
        responseHeader.setContentLength(response.size());
        if (!m_contentType.isEmpty())
            responseHeader.setContentType(QString::fromLatin1(m_contentType));

        QByteArray asciiHeader = responseHeader.toString().toLatin1();
        m_tcpConnection->write(asciiHeader);

        m_tcpConnection->write(response);
        m_tcpConnection->flush();
        m_tcpConnection->close();

        return;
    }
}
MaiaXmlRpcServerConnection::MaiaXmlRpcServerConnection(QTcpSocket *connection, QObject* parent) : QObject(parent) {
	header = NULL;
	clientConnection = connection;
	connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readFromSocket()));
    connect(clientConnection, SIGNAL(disconnected()), this, SLOT(deleteLater()));
}
Example #4
0
/// Reads the config file (server.ini) and start the server accordingly
void Widget::startServer()
{
    ui->retranslateUi(this);

    logStatusMessage(tr("Private server v0.5.3-alpha2"));
#ifdef __APPLE__
    // this fixes the directory in OSX so we can use the relative CONFIGFILEPATH and etc properly
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef resourcesURL = CFBundleCopyBundleURL(mainBundle);
    char path[PATH_MAX];
    if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
    {
        // error!
    }
    CFRelease(resourcesURL);
    // the path we get is to the .app folder, so we go up after we chdir
    chdir(path);
    chdir("..");
#endif
    lastNetviewId=0;
    lastId=1;

    /// Read config
    logStatusMessage(tr("Reading config file ..."));
    QSettings config(CONFIGFILEPATH, QSettings::IniFormat);
    loginPort = config.value("loginPort", 1031).toInt();
    gamePort = config.value("gamePort", 1039).toInt();
    maxConnected = config.value("maxConnected",128).toInt();
    maxRegistered = config.value("maxRegistered",2048).toInt();
    pingTimeout = config.value("pingTimeout", 15).toInt();
    pingCheckInterval = config.value("pingCheckInterval", 5000).toInt();
    logInfos = config.value("logInfosMessages", true).toBool();
    saltPassword = config.value("saltPassword", "Change Me").toString();
    enableSessKeyValidation = config.value("enableSessKeyValidation", true).toBool();
    enableLoginServer = config.value("enableLoginServer", true).toBool();
    enableGameServer = config.value("enableGameServer", true).toBool();
    enableMultiplayer = config.value("enableMultiplayer", true).toBool();
    syncInterval = config.value("syncInterval",DEFAULT_SYNC_INTERVAL).toInt();
    remoteLoginIP = config.value("remoteLoginIP", "127.0.0.1").toString();
    remoteLoginPort = config.value("remoteLoginPort", 1031).toInt();
    remoteLoginTimeout = config.value("remoteLoginTimeout", 5000).toInt();
    useRemoteLogin = config.value("useRemoteLogin", false).toBool();
    enableGetlog = config.value("enableGetlog", true).toBool();

    /// Init servers
    tcpClientsList.clear();
#if defined _WIN32 || defined WIN32
    startTimestamp = GetTickCount();
#elif __APPLE__
    timeval time;
    gettimeofday(&time, NULL);
    startTimestamp = (time.tv_sec * 1000) + (time.tv_usec / 1000);
#else
    struct timespec tp;
    clock_gettime(CLOCK_MONOTONIC, &tp);
    startTimestamp = tp.tv_sec*1000 + tp.tv_nsec/1000/1000;
#endif

    /// Read vortex DB
    if (enableGameServer)
    {
        bool corrupted=false;
        QDir vortexDir("data/vortex/");
        QStringList files = vortexDir.entryList(QDir::Files);
        int nVortex=0;
        for (int i=0; i<files.size(); i++) // For each vortex file
        {
            // Each file is a scene
            Scene scene(files[i].split('.')[0]);

            QFile file("data/vortex/"+files[i]);
            if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                logStatusMessage(tr("Error reading vortex DB"));
                return;
            }
            QByteArray data = file.readAll();
            data.replace('\r', "");
            QList<QByteArray> lines = data.split('\n');

            // Each line is a vortex
            for (int j=0; j<lines.size(); j++)
            {
                if (lines[j].size() == 0) // Skip empty lines
                    continue;
                nVortex++;
                Vortex vortex;
                bool ok1, ok2, ok3, ok4;
                QList<QByteArray> elems = lines[j].split(' ');
                if (elems.size() < 5)
                {
                    logStatusMessage(tr("Vortex DB is corrupted. Incorrect line (%1 elems), file %2")
                                        .arg(elems.size()).arg(files[i]));
                    corrupted=true;
                    break;
                }
                vortex.id = elems[0].toInt(&ok1, 16);
                vortex.destName = elems[1];
                for (int j=2; j<elems.size() - 3;j++) // Concatenate the string between id and poss
                    vortex.destName += " "+elems[j];
                vortex.destPos.x = elems[elems.size()-3].toFloat(&ok2);
                vortex.destPos.y = elems[elems.size()-2].toFloat(&ok3);
                vortex.destPos.z = elems[elems.size()-1].toFloat(&ok4);
                if (!(ok1&&ok2&&ok3&&ok4))
                {
                    logStatusMessage(tr("Vortex DB is corrupted. Conversion failed, file %1").arg(files[i]));
                    corrupted=true;
                    break;
                }
                scene.vortexes << vortex;
                //win.logMessage("Add vortex "+QString().setNum(vortex.id)+" to "+vortex.destName+" "
                //               +QString().setNum(vortex.destPos.x)+" "
                //               +QString().setNum(vortex.destPos.y)+" "
                //               +QString().setNum(vortex.destPos.z));
            }
            scenes << scene;
        }

        if (corrupted)
        {
            stopServer();
            return;
        }

        logMessage(tr("Loaded %1 vortexes in %2 scenes").arg(nVortex).arg(scenes.size()));
    }

    /// Read/parse Items.xml
    if (enableGameServer)
    {
        QFile itemsFile("data/data/Items.xml");
        if (itemsFile.open(QIODevice::ReadOnly))
        {
            QByteArray data = itemsFile.readAll();
            wearablePositionsMap = parseItemsXml(data);
            win.logMessage(tr("Loaded %1 items").arg(wearablePositionsMap.size()));
        }
        else
        {
            win.logMessage(tr("Couln't open Items.xml"));
            stopServer();
            return;
        }
    }

    /// Read NPC/Quests DB
    if (enableGameServer)
    {
        try
        {
            unsigned nQuests = 0;
            QDir npcsDir("data/npcs/");
            QStringList files = npcsDir.entryList(QDir::Files);
            for (int i=0; i<files.size(); i++, nQuests++) // For each vortex file
            {
                try
                {
                    Quest quest("data/npcs/"+files[i], NULL);
                    quests << quest;
                    npcs << quest.npc;
                }
                catch (QString& error)
                {
                    win.logMessage(error);
                    win.stopServer();
                    throw error;
                }
            }
            logMessage(tr("Loaded %1 quests/npcs").arg(nQuests));
        }
        catch (QString& e)
        {
            enableGameServer = false;
        }
    }

    /// Read/parse mob zones
    if (enableGameServer)
    {
        try
        {
            QDir mobsDir(MOBSPATH);
            QStringList files = mobsDir.entryList(QDir::Files);
            for (int i=0; i<files.size(); i++) // For each mobzone file
            {
                QFile file(MOBSPATH+files[i]);
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    logStatusMessage(tr("Error reading mob zones"));
                    return;
                }
                QByteArray data = file.readAll();
                file.close();
                try {
                    parseMobzoneData(data); // Will fill our Mobzone and Mobs list
                }
                catch (QString& error)
                {
                    win.logMessage(error);
                    win.stopServer();
                    throw error;
                }
            }
            logMessage(tr("Loaded %1 mobs in %2 zones").arg(mobs.size()).arg(mobzones.size()));
        }
        catch (...) {}
    }

    if (enableLoginServer)
    {
//      logStatusMessage(tr("Loading players database ..."));
        tcpPlayers = Player::loadPlayers();
    }

    // TCP server
    if (enableLoginServer)
    {
        logStatusMessage(tr("Starting TCP login server on port %1...").arg(loginPort));
        if (!tcpServer->listen(QHostAddress::Any,loginPort))
        {
            logStatusMessage(tr("TCP: Unable to start server on port %1 : %2").arg(loginPort).arg(tcpServer->errorString()));
            stopServer();
            return;
        }

        // If we use a remote login server, try to open a connection preventively.
        if (useRemoteLogin)
            remoteLoginSock.connectToHost(remoteLoginIP, remoteLoginPort);
    }

    // UDP server
    if (enableGameServer)
    {
        logStatusMessage(tr("Starting UDP game server on port %1...").arg(gamePort));
        if (!udpSocket->bind(gamePort, QUdpSocket::ReuseAddressHint|QUdpSocket::ShareAddress))
        {
            logStatusMessage(tr("UDP: Unable to start server on port %1").arg(gamePort));
            stopServer();
            return;
        }
    }

    if (enableGameServer)
    {
        // Start ping timeout timer
        pingTimer->start(pingCheckInterval);
    }

    if (enableMultiplayer)
        sync.startSync();

    if (enableLoginServer || enableGameServer)
        logStatusMessage(tr("Server started"));

    connect(ui->sendButton, SIGNAL(clicked()), this, SLOT(sendCmdLine()));
    if (enableLoginServer)
        connect(tcpServer, SIGNAL(newConnection()), this, SLOT(tcpConnectClient()));
    if (enableGameServer)
    {
        connect(udpSocket, SIGNAL(readyRead()),this, SLOT(udpProcessPendingDatagrams()));
        connect(pingTimer, SIGNAL(timeout()), this, SLOT(checkPingTimeouts()));
    }
}
Example #5
0
		void client_contentReadyRead()
		{
			_content.append(_client->consumeContent());
			 emit readyRead();
			 //emit downloadProgress();
		}
Example #6
0
bool HttpClient::downloadFile( QString &urlIn, QString &destinationIn )
{
  // qDebug() << "HttpClient::downloadFile: url=" << urlIn << ", dest=" << destinationIn;

  if( downloadRunning == true )
    {
      qWarning( "HttpClient(%d): download is running!", __LINE__ );
      return false;
    }

  _url = urlIn;
  _destination = destinationIn;

  QUrl url( urlIn );
  QFileInfo fileInfo( destinationIn );

  if( urlIn.isEmpty() || ! url.isValid() || fileInfo.fileName().isEmpty() )
    {
      qWarning( "HttpClient(%d): Url or destination file are invalid!", __LINE__ );
      return false;
    }

  tmpFile = new QFile( destinationIn + "." +
                       QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss") );

  if( ! tmpFile->open( QIODevice::WriteOnly ) )
    {
      qWarning( "HttpClient(%d): Unable to open the file %s: %s",
                 __LINE__,
                 tmpFile->fileName ().toLatin1().data(),
                 tmpFile->errorString().toLatin1().data() );

      delete tmpFile;
      tmpFile = static_cast<QFile *> (0);
      return false;
    }

  // Check, if a proxy is defined in the configuration data. If true, we do use it.
  extern QSettings _settings;

  QString proxy = _settings.value( "/Internet/Proxy", "" ).toString();

  if( proxy.isEmpty() )
    {
      // Check the user's environment, if a proxy is defined there.
      char* proxyFromEnv = getenv("http_proxy");

      if( proxyFromEnv == 0 )
        {
          proxyFromEnv = getenv("HTTP_PROXY");
        }

      if( proxyFromEnv )
        {
          QString qProxy( proxyFromEnv );

          // remove an existing http prefix
          proxy = qProxy.remove("http://");
        }
    }

  if( ! proxy.isEmpty() )
    {
      QString hostName;
      quint16 port;

      if( parseProxy( proxy, hostName, port ) == true )
        {
          QNetworkProxy proxy;
          proxy.setType( QNetworkProxy::HttpProxy );
          proxy.setHostName( hostName );
          proxy.setPort( port );
          manager->setProxy( proxy );
        }
    }

  QNetworkRequest request;
  QString appl = QCoreApplication::applicationName() + "/" +
                 QCoreApplication::applicationVersion() +
                 " (Qt" + QT_VERSION_STR + "/X11)";

  request.setUrl( QUrl( _url, QUrl::TolerantMode ));
  request.setRawHeader( "User-Agent", appl.toLatin1() );

  reply = manager->get(request);

  if( ! reply )
    {
      qWarning( "HttpClient(%d): Reply object is invalid!", __LINE__ );
      return false;
    }

  reply->setReadBufferSize(0);

  connect( reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()) );

  connect( reply, SIGNAL(error(QNetworkReply::NetworkError)),
           this, SLOT(slotError(QNetworkReply::NetworkError)) );

  connect( reply, SIGNAL(finished()),
           this, SLOT(slotFinished()) );

  connect( reply, SIGNAL(downloadProgress(qint64, qint64)),
           this, SLOT(slotDownloadProgress( qint64, qint64 )) );

  downloadRunning = true;

  if ( _progressDialog != static_cast<QProgressDialog *> (0) )
    {
      _progressDialog->setWindowTitle( tr( "HTTP" ) );
      _progressDialog->setLabelText( tr( "Downloading %1" ).arg( fileInfo.fileName() ) );
      _progressDialog->show();
    }

  timer->start();
  return true;
}
THttpSocket::THttpSocket(QObject *parent)
    : QTcpSocket(parent), lengthToRead(-1), lastProcessed(QDateTime::currentDateTime())
{
    T_TRACEFUNC("");
    connect(this, SIGNAL(readyRead()), this, SLOT(readRequest()));
}
//! [0]
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
        this, SLOT(replyFinished(QNetworkReply*)));

manager->get(QNetworkRequest(QUrl("http://qt.nokia.com")));
//! [0]


//! [1]
QNetworkRequest request;
request.setUrl(QUrl("http://qt.nokia.com"));
request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");

QNetworkReply *reply = manager->get(request);
connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
        this, SLOT(slotError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
        this, SLOT(slotSslErrors(QList<QSslError>)));
//! [1]

//! [2]
QNetworkConfigurationManager manager;
networkAccessManager->setConfiguration(manager.defaultConfiguration());
//! [2]

//! [3]
networkAccessManager->setConfiguration(QNetworkConfiguration());
//! [3]
Example #9
0
QgsHelpContextSocket::QgsHelpContextSocket( int socket, QObject *parent ) :
    QTcpSocket( parent )
{
  connect( this, SIGNAL( readyRead() ), SLOT( readClient() ) );
  setSocketDescriptor( socket );
}
Example #10
0
void HttpPoll::http_result()
{
	// check for death :)
	QPointer<QObject> self = this;
	syncFinished();
	if(!self)
		return;

	// get id and packet
	QString id;
	QString cookie = d->http.getHeader("Set-Cookie");
	int n = cookie.indexOf("ID=");
	if(n == -1) {
		resetConnection();
		setError(ErrRead);
		return;
	}
	n += 3;
	int n2 = cookie.indexOf(';', n);
	if(n2 != -1)
		id = cookie.mid(n, n2-n);
	else
		id = cookie.mid(n);
	QByteArray block = d->http.body();

	// session error?
	if(id.right(2) == ":0") {
		if(id == "0:0" && d->state == 2) {
			resetConnection();
			connectionClosed();
			return;
		}
		else {
			resetConnection();
			setError(ErrRead);
			return;
		}
	}

	d->ident = id;
	bool justNowConnected = false;
	if(d->state == 1) {
		d->state = 2;
		justNowConnected = true;
	}

	// sync up again soon
	if(bytesToWrite() > 0 || !d->closing) {
		d->t->start(d->polltime * 1000);
  }

	// connecting
	if(justNowConnected) {
		connected();
	}
	else {
		if(!d->out.isEmpty()) {
			int x = d->out.size();
			d->out.resize(0);
			takeWrite(x);
			bytesWritten(x);
		}
	}

	if(!self)
		return;

	if(!block.isEmpty()) {
		appendRead(block);
		readyRead();
	}

	if(!self)
		return;

	if(bytesToWrite() > 0) {
		do_sync();
	}
	else {
		if(d->closing) {
			resetConnection();
			delayedCloseFinished();
			return;
		}
	}
}
Example #11
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    offcount = 0;
    datadisp = new DataDisplay(this);
//    this->setWindowFlags(Qt::WindowStaysOnTopHint);
//    this->setAttribute(Qt::WA_TranslucentBackground, true);

    setWindowTitle(tr("TMT Actuator Test Station Software"));
    ui->enccomboBox->addItem("10 seconds");
    ui->enccomboBox->addItem("25 seconds");
    ui->enccomboBox->addItem("50 seconds");
    ui->enccomboBox->addItem("100 seconds");

    ui->offcomboBox->addItem("1 mm");
    ui->offcomboBox->addItem("3 mm");
    ui->offcomboBox->addItem("6 mm");

    ui->vcmcomboBox->addItem("20 seconds");
    ui->vcmcomboBox->addItem("40 seconds");
    ui->vcmcomboBox->addItem("80 seconds");
    ui->vcmcomboBox->addItem("100 seconds");

    ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
//    ui->customPlot->setBackground(Qt::transparent);
    ui->customPlot->legend->setVisible(true);
    ui->customPlot->legend->setFont(QFont("Helvetica", 7));
    ui->customPlot->axisRect()->setBackground(Qt::darkGray);
    ui->customPlot->axisRect()->setupFullAxesBox();

    ui->customPlot->addGraph(); // blue line
    ui->customPlot->graph(0)->setName("Encoder Count vs. Time");
    ui->customPlot->graph(0)->setPen(QPen(Qt::blue));
    ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsLine);
    ui->customPlot->graph(0)->setAntialiasedFill(false);

    ui->customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    ui->customPlot->xAxis->setDateTimeFormat("hh:mm:ss");
    ui->customPlot->xAxis->setAutoTickStep(true);
    ui->customPlot->xAxis->setTickStep(1);

    ui->customPlot_1->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

    ui->customPlot_1->legend->setVisible(true);
    ui->customPlot_1->legend->setFont(QFont("Helvetica", 7));
    ui->customPlot_1->axisRect()->setBackground(Qt::darkGray);
    ui->customPlot_1->axisRect()->setupFullAxesBox();

    ui->customPlot_1->addGraph(); // blue line
    ui->customPlot_1->graph(0)->setName("Sensor Data vs. Time");
    ui->customPlot_1->graph(0)->setPen(QPen(Qt::green));
    ui->customPlot_1->graph(0)->setLineStyle(QCPGraph::lsLine);
    ui->customPlot_1->graph(0)->setAntialiasedFill(false);

    ui->customPlot_1->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    ui->customPlot_1->xAxis->setDateTimeFormat("hh:mm:ss");
    ui->customPlot_1->xAxis->setAutoTickStep(true);

    foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
    ui->portBox->addItem(info.portName);

    ui->portBox->setEditable(true);

    ui->baudRateBox->addItem("9600", BAUD9600);
    ui->baudRateBox->addItem("115200", BAUD115200);
    ui->baudRateBox->setCurrentIndex(2);

    ui->parityBox->addItem("NONE", PAR_NONE);
    ui->parityBox->addItem("ODD", PAR_ODD);
    ui->parityBox->addItem("EVEN", PAR_EVEN);

    ui->dataBitsBox->addItem("5", DATA_5);
    ui->dataBitsBox->addItem("6", DATA_6);
    ui->dataBitsBox->addItem("7", DATA_7);
    ui->dataBitsBox->addItem("8", DATA_8);
    ui->dataBitsBox->setCurrentIndex(3);

    ui->stopBitsBox->addItem("1", STOP_1);
    ui->stopBitsBox->addItem("2", STOP_2);

    ui->queryModeBox->addItem("POLLING", QextSerialPort::Polling);
    ui->queryModeBox->addItem("EVENT DRIVEN", QextSerialPort::EventDriven);

    timer = new QTimer(this);
    timer->setInterval(40);

    PortSettings settings = {BAUD115200, DATA_8, PAR_NONE, STOP_1, FLOW_OFF, 10};
    port = new QextSerialPort(ui->portBox->currentText(), settings, QextSerialPort::Polling);

    enumerator = new QextSerialEnumerator(this);
    enumerator->setUpNotifications();

    connect(ui->connect_Button, SIGNAL(clicked()), SLOT(run()));
    connect(ui->disconnect_Button, SIGNAL(clicked()), SLOT(disconnectClient()));
    connect(ui->stop_Button, SIGNAL(clicked()), SLOT(stopplot()));
    connect(ui->reset_window_Button, SIGNAL(clicked()), SLOT(resetfun()));
    connect(ui->enc_test_run_Button, SIGNAL(clicked()), SLOT(encoderfun()));
    connect(ui->enc_test_run_Button, SIGNAL(clicked()), SLOT(showdatadisp()));
    connect(ui->off_up_Button, SIGNAL(clicked()), SLOT(offloaderfun()));
    connect(ui->off_down_Button, SIGNAL(clicked()), SLOT(offloaderfun_1()));
    connect(ui->vcm_test_run_Button, SIGNAL(clicked()), SLOT(vcmfun()));
    connect(ui->vcm_test_run_Button, SIGNAL(clicked()), SLOT(showdatadisp()));
    connect(ui->reset_drive_board_Button, SIGNAL(clicked()), SLOT(resetdrivefun()));
    connect(ui->save_plot_Button, SIGNAL(clicked()), SLOT(saveplot_fun()));

    connect(ui->baudRateBox, SIGNAL(currentIndexChanged(int)), SLOT(onBaudRateChanged(int)));
    connect(ui->parityBox, SIGNAL(currentIndexChanged(int)), SLOT(onParityChanged(int)));
    connect(ui->dataBitsBox, SIGNAL(currentIndexChanged(int)), SLOT(onDataBitsChanged(int)));
    connect(ui->stopBitsBox, SIGNAL(currentIndexChanged(int)), SLOT(onStopBitsChanged(int)));
    connect(ui->portBox, SIGNAL(editTextChanged(QString)), SLOT(onPortNameChanged(QString)));

    connect(ui->openCloseButton, SIGNAL(clicked()), SLOT(onOpenCloseButtonClicked()));
    connect(ui->sendButton, SIGNAL(clicked()), SLOT(onSendButtonClicked()));
    connect(ui->aboutButton, SIGNAL(clicked()), SLOT(about_fun()));

    connect(timer, SIGNAL(timeout()), SLOT(onReadyRead()));
    connect(port, SIGNAL(readyRead()), SLOT(onReadyRead()));
    connect(enumerator, SIGNAL(deviceDiscovered(QextPortInfo)), SLOT(onPortAddedOrRemoved()));
    connect(enumerator, SIGNAL(deviceRemoved(QextPortInfo)), SLOT(onPortAddedOrRemoved()));
}
Example #12
0
//#include <QDebug>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    QTextCodec *utfcodec = QTextCodec::codecForName("UTF-8"); //qt4
    QTextCodec::setCodecForTr(utfcodec);
    QTextCodec::setCodecForCStrings(utfcodec);
    mySerialPort=new SerialPort(this);
    myTimer=new QTimer(this);
    connect(ui->toolButton, SIGNAL(clicked()), this, SLOT(refreshAvSerialPort()));
    connect(mySerialPort, SIGNAL(readyRead()), this , SLOT(readToPlainText()));
    //ui->groupBox->setHidden(ui->toolButton_3->isChecked());
    //ui->groupBox->hide();
    // fill data bits
    ui->comboBox_3->addItem(QLatin1String("8"), SerialPort::Data8);
    ui->comboBox_3->addItem(QLatin1String("7"), SerialPort::Data7);
    ui->comboBox_3->addItem(QLatin1String("6"), SerialPort::Data6);
    ui->comboBox_3->addItem(QLatin1String("5"), SerialPort::Data5);
    ui->comboBox_3->setCurrentIndex(0);

    // fill stop bits
    ui->comboBox_4->addItem(QLatin1String("2"), SerialPort::TwoStop);
#ifdef Q_OS_WIN
    ui->comboBox_4->addItem(QLatin1String("1.5"), SerialPort::OneAndHalfStop);
#endif
    ui->comboBox_4->addItem(QLatin1String("1"), SerialPort::OneStop);
    ui->comboBox_4->setCurrentIndex(ui->comboBox_4->count()-1);

    // fill parity
    ui->comboBox_5->addItem(QLatin1String("None"), SerialPort::NoParity);
    ui->comboBox_5->addItem(QLatin1String("Even"), SerialPort::EvenParity);
    ui->comboBox_5->addItem(QLatin1String("Odd"), SerialPort::OddParity);
    ui->comboBox_5->addItem(QLatin1String("Mark"), SerialPort::MarkParity);
    ui->comboBox_5->addItem(QLatin1String("Space"), SerialPort::SpaceParity);
    ui->comboBox_5->setCurrentIndex(0);

    // fill flow control
    ui->comboBox_6->addItem(QLatin1String("None"), SerialPort::NoFlowControl);
    ui->comboBox_6->addItem(QLatin1String("RTS/CTS"), SerialPort::HardwareControl);
    ui->comboBox_6->addItem(QLatin1String("XON/XOFF"), SerialPort::SoftwareControl);
    ui->comboBox_6->setCurrentIndex(0);
    refreshAvSerialPort();
    //currPortName="";
    loadSettings();
    if(complList.isEmpty())
        complList<<"ATID"<<"ATCH"<<"ATPL"<<"ATRE"<<"ATCN"<<"ATAC"<<"ATFR"<<"ATAD"<<"ATVR"<<"ATSH"<<"ATSL";

    myCompl=new QCompleter(complList, this);
    myCompl->setCaseSensitivity(Qt::CaseInsensitive);

    ui->lineEdit->setCompleter(myCompl);
    for(qint32 i=1; i<ui->comboBox_2->count(); i++) {
        if(ui->comboBox_2->itemText(i)==currPortName) {
            ui->comboBox_2->setCurrentIndex(i);
            break;
        }

    }
    dozvilNaOnovlPortiv=1;
    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeIndxToPushButton(int)));
    connect(ui->comboBox_3, SIGNAL(currentIndexChanged(int)), this, SLOT(changeIndxToPushButton(int)));
    connect(ui->comboBox_4, SIGNAL(currentIndexChanged(int)), this, SLOT(changeIndxToPushButton(int)));
    connect(ui->comboBox_5, SIGNAL(currentIndexChanged(int)), this, SLOT(changeIndxToPushButton(int)));
    connect(ui->comboBox_6, SIGNAL(currentIndexChanged(int)), this, SLOT(changeIndxToPushButton(int)));

    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(focusLineEdit(int)));
    connect(ui->comboBox_3, SIGNAL(currentIndexChanged(int)), this, SLOT(focusLineEdit(int)));
    connect(ui->comboBox_4, SIGNAL(currentIndexChanged(int)), this, SLOT(focusLineEdit(int)));
    connect(ui->comboBox_5, SIGNAL(currentIndexChanged(int)), this, SLOT(focusLineEdit(int)));
    connect(ui->comboBox_6, SIGNAL(currentIndexChanged(int)), this, SLOT(focusLineEdit(int)));
    connect(ui->comboBox_7, SIGNAL(currentIndexChanged(int)), this, SLOT(focusLineEdit(int)));
    connect(ui->comboBox_8, SIGNAL(currentIndexChanged(int)), this, SLOT(focusLineEdit(int)));
    connect(ui->cbTextSet, SIGNAL(currentIndexChanged(int)), this, SLOT(focusLineEdit(int)));
    connect(ui->toolButton_2,SIGNAL(clicked()), this , SLOT(focusLineEdit2()));
    connect(ui->toolButton_3,SIGNAL(clicked()), this , SLOT(focusLineEdit2()));
    connect(ui->toolButton_4,SIGNAL(clicked()), this , SLOT(focusLineEdit2()));

    connect(&checkPort, SIGNAL(portDisconnected()), this, SLOT(closeSerialPort()));

    //    onovlennyaTimer=new QTimer(this);
    //   connect(onovlennyaTimer, SIGNAL(timeout()), this, SLOT(onOnovlTimer()));
    //    onovlennyaTimer->start(1500);
}
Example #13
0
	void start(const QVariant &vrequest, Mode mode)
	{
		outSeq = 0;
		outCredits = 0;
		quiet = false;

		ZhttpRequestPacket request;
		if(!request.fromVariant(vrequest))
		{
			log_warning("failed to parse zurl request");

			QVariantHash vhash = vrequest.toHash();
			rid = vhash.value("id").toByteArray();
			assert(!rid.isEmpty()); // app layer ensures this
			toAddress = vhash.value("from").toByteArray();
			QByteArray type = vhash.value("type").toByteArray();
			if(!toAddress.isEmpty() && type != "error" && type != "cancel")
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			}
			else
			{
				cleanup();
				QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection);
			}

			return;
		}

		rid = request.id;
		toAddress = request.from;
		userData = request.userData;
		sentHeader = false;
		stuffToRead = false;
		bytesReceived = 0;

		ignorePolicies = request.ignorePolicies;

		if(request.uri.isEmpty())
		{
			log_warning("missing request uri");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		QString scheme = request.uri.scheme();
		if(scheme == "https" || scheme == "http")
		{
			transport = HttpTransport;
		}
		else if(scheme == "wss" || scheme == "ws")
		{
			transport = WebSocketTransport;
		}
		else
		{
			log_warning("unsupported scheme");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		if(transport == WebSocketTransport && mode != Worker::Stream)
		{
			log_warning("websocket must be used from stream interface");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		HttpHeaders headers = request.headers;

		if(transport == HttpTransport)
		{
			// streaming only allowed on streaming interface
			if(mode == Worker::Stream)
				outStream = request.stream;
			else
				outStream = false;

			if(request.method.isEmpty())
			{
				log_warning("missing request method");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			log_info("IN id=%s, %s %s", request.id.data(), qPrintable(request.method), request.uri.toEncoded().data());

			// inbound streaming must start with sequence number of 0
			if(mode == Worker::Stream && request.more && request.seq != 0)
			{
				log_warning("streamed input must start with seq 0");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			// fire and forget
			if(mode == Worker::Stream && toAddress.isEmpty())
				quiet = true;

			// can't use these two together
			if(mode == Worker::Single && request.more)
			{
				log_warning("cannot use streamed input on router interface");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			bodySent = false;

			inSeq = request.seq;

			if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost)))
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation"));
				return;
			}

			hreq = new HttpRequest(dns, this);
			connect(hreq, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &)));
			connect(hreq, SIGNAL(readyRead()), SLOT(req_readyRead()));
			connect(hreq, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int)));
			connect(hreq, SIGNAL(error()), SLOT(req_error()));
			maxResponseSize = request.maxSize;
			if(!request.connectHost.isEmpty())
				hreq->setConnectHost(request.connectHost);
			if(request.connectPort != -1)
				request.uri.setPort(request.connectPort);

			hreq->setIgnoreTlsErrors(request.ignoreTlsErrors);

			if(request.credits != -1)
				outCredits += request.credits;

			if(!headers.contains("Content-Length"))
			{
				if(request.more)
				{
					// ensure chunked encoding
					headers.removeAll("Transfer-Encoding");
					headers += HttpHeader("Transfer-Encoding", "chunked");
				}
				else
				{
					// ensure content-length
					if(!request.body.isEmpty() ||
						(request.method != "OPTIONS" &&
						request.method != "HEAD" &&
						request.method != "GET" &&
						request.method != "DELETE"))
					{
						headers += HttpHeader("Content-Length", QByteArray::number(request.body.size()));
					}
				}
			}
		}
		else // WebSocketTransport
		{
			log_info("IN id=%s, %s", request.id.data(), request.uri.toEncoded().data());

			// inbound streaming must start with sequence number of 0
			if(request.seq != 0)
			{
				log_warning("websocket input must start with seq 0");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			if(toAddress.isEmpty())
			{
				log_warning("websocket input must provide from address");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			inSeq = request.seq;

			if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost)))
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation"));
				return;
			}

			ws = new WebSocket(dns, this);
			connect(ws, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &)));
			connect(ws, SIGNAL(connected()), SLOT(ws_connected()));
			connect(ws, SIGNAL(readyRead()), SLOT(ws_readyRead()));
			connect(ws, SIGNAL(framesWritten(int)), SLOT(ws_framesWritten(int)));
			connect(ws, SIGNAL(peerClosing()), SLOT(ws_peerClosing()));
			connect(ws, SIGNAL(closed()), SLOT(ws_closed()));
			connect(ws, SIGNAL(error()), SLOT(ws_error()));

			if(!request.connectHost.isEmpty())
				ws->setConnectHost(request.connectHost);
			if(request.connectPort != -1)
				request.uri.setPort(request.connectPort);

			ws->setIgnoreTlsErrors(request.ignoreTlsErrors);
			ws->setMaxFrameSize(config->sessionBufferSize);

			if(request.credits != -1)
				outCredits += request.credits;
		}

		httpExpireTimer = new QTimer(this);
		connect(httpExpireTimer, SIGNAL(timeout()), SLOT(httpExpire_timeout()));
		httpExpireTimer->setSingleShot(true);
		httpExpireTimer->start(config->sessionTimeout * 1000);

		if(transport == WebSocketTransport || (transport == HttpTransport && mode == Worker::Stream))
		{
			expireTimer = new QTimer(this);
			connect(expireTimer, SIGNAL(timeout()), SLOT(expire_timeout()));
			expireTimer->setSingleShot(true);
			expireTimer->start(SESSION_EXPIRE);

			keepAliveTimer = new QTimer(this);
			connect(keepAliveTimer, SIGNAL(timeout()), SLOT(keepAlive_timeout()));
			keepAliveTimer->start(SESSION_EXPIRE / 2);
		}

		if(transport == HttpTransport)
		{
			hreq->start(request.method, request.uri, headers);

			if(!request.body.isEmpty())
				hreq->writeBody(request.body);

			if(!request.more)
			{
				bodySent = true;
				hreq->endBody();
			}
			else
			{
				// send cts
				ZhttpResponsePacket resp;
				resp.type = ZhttpResponsePacket::Credit;
				resp.credits = config->sessionBufferSize;
				writeResponse(resp);
			}
		}
		else // WebSocketTransport
		{
			ws->start(request.uri, headers);
		}
	}
Example #14
0
MythSocket::MythSocket(
    qt_socket_fd_t socket, MythSocketCBs *cb, bool use_shared_thread) :
    ReferenceCounter(QString("MythSocket(%1)").arg(socket)),
    m_tcpSocket(new QTcpSocket()),
    m_thread(NULL),
    m_socketDescriptor(-1),
    m_peerPort(-1),
    m_callback(cb),
    m_useSharedThread(use_shared_thread),
    m_disableReadyReadCallback(false),
    m_connected(false),
    m_dataAvailable(0),
    m_isValidated(false),
    m_isAnnounced(false)
{
    LOG(VB_SOCKET, LOG_INFO, LOC + QString("MythSocket(%1, 0x%2) ctor")
        .arg(socket).arg((intptr_t)(cb),0,16));

    // Use direct connections so m_tcpSocket can be used
    // in the handlers safely since they will be running
    // in the same thread as all other m_tcpSocket users.

    connect(m_tcpSocket,  SIGNAL(connected()),
            this, SLOT(ConnectHandler()),
            Qt::DirectConnection);
    connect(m_tcpSocket,  SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(ErrorHandler(QAbstractSocket::SocketError)),
            Qt::DirectConnection);
    connect(m_tcpSocket,  SIGNAL(aboutToClose()),
            this, SLOT(AboutToCloseHandler()));
    connect(m_tcpSocket,  SIGNAL(disconnected()),
            this, SLOT(DisconnectHandler()),
            Qt::DirectConnection);
    connect(m_tcpSocket,  SIGNAL(readyRead()),
            this, SLOT(ReadyReadHandler()),
            Qt::DirectConnection);

    connect(this, SIGNAL(CallReadyRead()),
            this, SLOT(CallReadyReadHandler()),
            Qt::QueuedConnection);

    if (socket != -1)
    {
        m_tcpSocket->setSocketDescriptor(
            socket, QAbstractSocket::ConnectedState,
            QAbstractSocket::ReadWrite);

        ConnectHandler(); // already called implicitly above?
    }

    if (!use_shared_thread)
    {
        m_thread = new MThread(QString("MythSocketThread(%1)").arg(socket));
        m_thread->start();
    }
    else
    {
        QMutexLocker locker(&s_thread_lock);
        if (!s_thread)
        {
            s_thread = new MThread("SharedMythSocketThread");
            s_thread->start();
        }
        m_thread = s_thread;
        s_thread_cnt++;
    }

    m_tcpSocket->moveToThread(m_thread->qthread());
    moveToThread(m_thread->qthread());
}
Example #15
0
MainWindow::MainWindow(Configuration *config, QWidget *parent)
    : QDialog(parent)
{
    QProcess::execute("mkdir -p cap");
    setWindowTitle("TTY Proxy Capture");
    setWindowIcon(QIcon(":/images/heart.svg"));

    createActions();
    createTrayIcon();
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
             this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));

    this->config = config;

    QStringList iplist = config->getHostAddress().split(".");

    QLabel *ipAddrLabel = new QLabel("Server IP:");
    ipAddr0 = new QSpinBox(this);
    ipAddr0->setRange(127, 254);
    ipAddr0->setValue(iplist[0].toInt());
    ipAddr1 = new QSpinBox(this);
    ipAddr1->setRange(0, 254);
    ipAddr1->setValue(iplist[1].toInt());
    ipAddr2 = new QSpinBox(this);
    ipAddr2->setRange(0, 254);
    ipAddr2->setValue(iplist[2].toInt());
    ipAddr3 = new QSpinBox(this);
    ipAddr3->setRange(220, 250);
    ipAddr3->setValue(iplist[3].toInt());

    QHBoxLayout *ipAddrLayout = new QHBoxLayout();
    ipAddrLayout->setSpacing(0);
    ipAddrLayout->addWidget(ipAddr0);
    ipAddrLayout->addWidget(ipAddr1);
    ipAddrLayout->addWidget(ipAddr2);
    ipAddrLayout->addWidget(ipAddr3);

    serverStatus = false;
    setIcon(serverStatus);
    switchButton = new QPushButton("Start", this);
    switchButton->setFocus(Qt::OtherFocusReason);
    connect(switchButton, SIGNAL(clicked()), this, SLOT(save()));
    // connect(switchButton, SIGNAL(clicked()), this, SLOT(start()));
    // connect(switchButton, SIGNAL(clicked()), this, SLOT(stop()));

    txBytes = 0;
    QLabel *txCountLabel = new QLabel("TX:");
    txCount = new QLineEdit;
    txCount->setAlignment(Qt::AlignRight);
    txCount->setReadOnly(true);
    txTcpSocket = new QTcpSocket(this);
    txDecode = new DecodeChannel("cap/tx%1.dat");
    connect(txTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
             this, SLOT(displayError(QAbstractSocket::SocketError)));
    connect(txTcpSocket, SIGNAL(connected()), this, SLOT(connectedChannel()));
    connect(txTcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedChannel()));
    connect(txTcpSocket, SIGNAL(readyRead()), this, SLOT(readTxChannel()));
    
    rxBytes = 0;
    QLabel *rxCountLabel = new QLabel("RX:");
    rxCount = new QLineEdit;
    rxCount->setAlignment(Qt::AlignRight);
    rxCount->setReadOnly(true);
    rxTcpSocket = new QTcpSocket(this);
    rxDecode = new DecodeChannel("cap/rx%1.dat");
    connect(rxTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
             this, SLOT(displayError(QAbstractSocket::SocketError)));
    connect(rxTcpSocket, SIGNAL(connected()), this, SLOT(connectedChannel()));
    connect(rxTcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedChannel()));
    connect(rxTcpSocket, SIGNAL(readyRead()), this, SLOT(readRxChannel()));

    QTimer *timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(refreshCount()));
	timer->start(500);

    statusBar = new QStatusBar;
    statusBar->showMessage("TTY Proxy Capture is ready ...");

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(ipAddrLabel, 0, 0);
    mainLayout->addLayout(ipAddrLayout, 0, 1, 1, 2);
    mainLayout->addWidget(switchButton, 0, 3);

    mainLayout->addWidget(txCountLabel, 1, 0);
    mainLayout->addWidget(txCount, 1, 1, 1, 2);

    mainLayout->addWidget(rxCountLabel, 2, 0);
    mainLayout->addWidget(rxCount, 2, 1, 1, 2);

    mainLayout->addWidget(statusBar, 3, 0, 1, 4);

    setLayout(mainLayout);

    trayIcon->show();
}
void DClusterUserHasDevicesListPage::on_recvDataFromOtherPage(quint16 cmdCode, char *data, quint16 dataLen)
{
    emit readyRead(cmdCode, data, dataLen);
}
Example #17
0
void ZTPManager::procPkg(const QByteArray &recvBuff,const QString &remoteHost,quint16 remotePort)
{
    Fragment* fragment = new Fragment(recvBuff);
    if(!fragment->isValid())
    {
        fragment->print();
        return;
    }
    FragmentList* fragMentList = NULL;

//    qDebug()<<"fragment :"<<fragment->identifier<<" "<<fragment->checksum<<" "<<fragment->fragment_count<<" "<<fragment->fragment_offset<<" "<<fragment->len;
//    qDebug()<<"fragment isvalid:"<<fragment->isValid();
    if(!workMap.contains(fragment->identifier) || workMap[fragment->identifier] == NULL)
    {
        fragMentList = new FragmentList(fragment->identifier);
        connect(fragMentList,SIGNAL(timeout(quint16)),this,SLOT(onTimeout(quint16)));
        workMap.insert(fragment->identifier,fragMentList);
    }
    else
    {
        fragMentList =  workMap[fragment->identifier];
    }
    if(fragMentList == NULL)
    {
        return;
    }
//    workMap[fragment->identifier]->timer.start(_timeout);  //内存泄漏隐患
    fragMentList->fragment_list.append(fragment);
    if(fragMentList->fragment_list.length() == fragment->fragment_count)
    {
        qSort(fragMentList->fragment_list.begin(),fragMentList->fragment_list.end(),lessThan);
        QByteArray recvBuff;
        for(int i = 0; i < fragment->fragment_count;i++)
        {
            recvBuff.append(fragMentList->fragment_list[i]->data);
        }
        FragmentList* node = fragMentList;
        workMap.remove(fragment->identifier);
//        node->timer.stop();//内存泄漏隐患
        delete node;        // ZZZZZZZZZZZZZZZZZZZZZZZ
        qint64 len;
        memcpy(&len,recvBuff.data()+6,8);
        if(recvBuff.length()!=len)
        {
            qDebug("recv ZTP data error: has data %lld bytes and actually recv %d bytes!!\n",
                len,recvBuff.length());
        }
        ZTPprotocol* ztp = new ZTPprotocol(recvBuff);
        ztp->addPara("RemoteHost",remoteHost);
        ztp->addPara("RemotePort",QString::number(remotePort));

        ztpListMutex.lock();
        if(ztpList.length()>=500)
        {
            delete ztp;
            ztpListMutex.unlock();
            return;
        }
        ztpList.append(ztp);
        ztpListMutex.unlock();
        emit readyRead();
    }
}
Example #18
0
MySocket::MySocket(QObject *parent) :
    QUdpSocket(parent)
{
    connect(this, SIGNAL(readyRead()),
            this, SLOT(myOnReceive()));
}
/*
 * Header format:
 * 
 * Pos Type     Data
 * -------------------------
 * 0   quint8   Type
 * 1   quint32  Optional id
 * 5   quint32  Data size
 * -------------------------
 * Total size: 9 bytes
 */
void LocalSocketPrivate::readData()
{
// 	qDebug("[%p] LocalSocketPrivate::readData()", this);
	
	// Try to read data
	disableReadNotifier();
  // Reset data size
  m_currentReadDataBuffer.clear();
  int numRead = 0;
  int nRead   = 0;
  do {
    // Resize read buffer
    if(m_currentReadDataBuffer.isEmpty()) {
      m_currentReadDataBuffer.resize(1024);
    } else if (readBufferSize() - m_currentReadDataBuffer.size() < 1024) {
      // We cannot use additional 1 KiB space anymore
      break;
    } else {
      // Add 1 KiB up to readBufferSize()
      m_currentReadDataBuffer.resize(m_currentReadDataBuffer.size() + 1024);
    }
    
    nRead	=	read(m_currentReadDataBuffer.data() + m_currentReadDataBuffer.size() - 1024, 1024);
    numRead += nRead;
  } while(nRead == 1024);
	enableReadNotifier();
	
	// Handle read data
	if(numRead > 0)
	{
		m_currentReadData.append(m_currentReadDataBuffer.constData(), numRead);
		
		// Analyze read data
		while(!m_currentReadData.isEmpty())
		{
// 			qDebug("[%p] LocalSocketPrivate::readData() - reading data", this);
			
			// Read package size if available
			if(!m_currentRequiredReadDataSize && m_currentReadData.size() >= HEADER_SIZE)
			{
				memcpy((char*)&m_currentRequiredReadDataSize, m_currentReadData.constData() + (HEADER_SIZE - sizeof(quint32)), sizeof(m_currentRequiredReadDataSize));
				// Add header size
				m_currentRequiredReadDataSize	+=	HEADER_SIZE;
			}
			
			// Check if we can read a package
			if(!m_currentRequiredReadDataSize || m_currentReadData.size() < m_currentRequiredReadDataSize)
			{
// 				qDebug("[%p] LocalSocketPrivate::readData() - Cannot read package yet: %d/%d", this, m_currentReadData.size(), m_currentRequiredReadDataSize);
				break;
			}
			
// 			static	int	_r_count	=	0;
// 			_r_count++;
// 			qDebug("[%p] LocalSocketPrivate::readData() - count: %d", this, _r_count);
			
			// Read meta data
			int					dataPos	=	0;
			quint8			readVarType;
			quint32			readVarOptId;
			quint32			readVarDataSize;
			
			// Type
			memcpy((char*)&readVarType, m_currentReadData.constData() + dataPos, sizeof(readVarType));
			dataPos	+=	sizeof(readVarType);
			// Optional id
			memcpy((char*)&readVarOptId, m_currentReadData.constData() + dataPos, sizeof(readVarOptId));
			dataPos	+=	sizeof(readVarOptId);
			// Data size
			memcpy((char*)&readVarDataSize, m_currentReadData.constData() + dataPos, sizeof(readVarDataSize));
			dataPos	+=	sizeof(readVarDataSize);
			
			Variant		readVar((Variant::Type)readVarType);
			readVar.setOptionalId(readVarOptId);
			
			// Set data
			if(readVarDataSize)
			{
				readVar.setValue(m_currentReadData.mid(dataPos, readVarDataSize));
				dataPos	+=	readVarDataSize;
			}
			
			// Remove data from buffer
			m_currentReadData.remove(0, dataPos);
			m_currentRequiredReadDataSize	=	0;
			
			// Append to temporary read buffer if necessary
			if(readVar.type() == Variant::SocketDescriptor || !m_tempReadBuffer.isEmpty())
				m_tempReadBuffer.append(readVar);
			else
			{
				{
					QWriteLocker	writeLock(&m_readBufferLock);
					m_readBuffer.append(readVar);
				}
				// We have read a package
				emit(readyRead());
			}
		}
	}
	
	checkTempReadData(true);
  
  // Lower read buffer size
  if(m_currentReadDataBuffer.size() > 1024)
    m_currentReadDataBuffer.resize(1024);
	
// 	qDebug("[%p] LocalSocketPrivate::~readData()", this);
}
Example #20
0
//点击打开串口按钮
void MainWindow::on_openMyComBtn_clicked()  //打开串口按钮 按下 槽函数
{

    //portName = ui->portNameComboBox->currentText();     //获取串口名
    myCom = new Win_QextSerialPort(portName, QextSerialBase::EventDriven);      //定义串口对象,并传递参数,在构造函数中对其初始化
    bool openFlag = myCom -> open(QIODevice::ReadWrite);    //以可读写方式打开串口,必须先打开串口再对相关参数做设置
    if(FALSE == openFlag)
    {
        QMessageBox::warning(this, tr("Warning"), tr("串口不存在或已被占用!"), QMessageBox::Yes);
        return;
    }
    /*
    if(ui->baudRateComboBox->currentText() == tr("9600"))   //设置波特率
        myCom->setBaudRate(BAUD9600);
    else if(ui->baudRateComboBox->currentText() == tr("115200"))
        myCom->setBaudRate(BAUD115200);
*/
    if(baudRateName == "BAUD9600")
        myCom->setBaudRate(BAUD9600);
    else if(baudRateName == "BAUD115200")
        myCom->setBaudRate(BAUD115200);
/*
    if(ui->dataBitsComboBox->currentText() == tr("8"))      //设置数据位数
        myCom->setDataBits(DATA_8);
    else if(ui->dataBitsComboBox->currentText() == tr("7"))
        myCom->setDataBits(DATA_7);
*/
    if(databitsName == "DATA_8")
        myCom->setDataBits(DATA_8);
    else if(databitsName == "DATA_7")
        myCom->setDataBits(DATA_7);
/*
    if(ui->parityComboBox->currentText() == tr("无校验"))     //设置校验位
        myCom->setParity(PAR_NONE);
    else if(ui->parityComboBox->currentText() == tr("奇校验"))
        myCom->setParity(PAR_ODD);
    else if(ui->parityComboBox->currentText() == tr("偶校验"))
        myCom->setParity(PAR_EVEN);
*/
    if(parityName == "NONE")
        myCom->setParity(PAR_NONE);
    else if(parityName == "ODD")
        myCom->setParity(PAR_ODD);
    else if(parityName == "EVEN")
        myCom->setParity(PAR_EVEN);
/*
    if(ui->stopBitsComboBox->currentText() == tr("1"))      //设置停止位
        myCom->setStopBits(STOP_1);
    else if(ui->stopBitsComboBox->currentText() == tr("2"))
        myCom->setStopBits(STOP_2);
*/
    if(stopbitsName == "STOP_1")
        myCom->setStopBits(STOP_1);
    else if(stopbitsName == "STOP_2")
        myCom->setStopBits(STOP_2);

    myCom->setFlowControl(FLOW_OFF);    //设置数据流控,这里直接设置为无数据流控

    myCom->setTimeout(500);     //设置延时


    connect(myCom, SIGNAL(readyRead()), this, SLOT(readMyCom()));   //信号关联槽,当串口缓冲区有数据时,进行串口读操作

    ui->openMyComBtn->setEnabled(false);    //打开串口后,“打开串口“按钮不可用
    ui->closeMyComBtn->setEnabled(true);    //打开串口后,”关闭串口“按钮可用
    ui->sendMsgBtn->setEnabled(true);       //打开串口后,”发送数据“按钮可用

    //ui->baudRateComboBox->setEnabled(false);    //当开启串口后,不能再修改相关参数
    //ui->dataBitsComboBox->setEnabled(false);
    //ui->parityComboBox->setEnabled(false);
    //ui->stopBitsComboBox->setEnabled(false);
    //ui->portNameComboBox->setEnabled(false);

    HEXSendSelect->setEnabled(false);
    HEXDisplaySelect->setEnabled(false);
    comMenu->setEnabled(false);
    ui->pauseBtn->setEnabled(true);
    ui->comStatusLabel->setEnabled(true);
}
Example #21
0
bool RecipeDB::backup( const QString &backup_file, QString *errMsg )
{
	kDebug()<<"Backing up current database to "<<backup_file;

	process = new KProcess;

	m_dumpFile = KFilterDev::deviceForFile(backup_file,"application/x-gzip");
	if ( !m_dumpFile->open( QIODevice::WriteOnly ) ) {
		kDebug()<<"Couldn't open "<<backup_file;
		return false;
	}

	m_dumpFile->setTextModeEnabled( true );

	QStringList command = backupCommand();
	if ( command.count() == 0 ) {
		kDebug()<<"Backup not available for this database backend";
		return false;
	}

	KConfigGroup config = KGlobal::config()->group( "DBType" );

	QString dbVersionString = QString::number(latestDBVersion());
	m_dumpFile->write(QByteArray("-- Generated for Krecipes v")); 
		m_dumpFile->write(krecipes_version().toUtf8()); m_dumpFile->write(QByteArray("\n"));
	m_dumpFile->write(QByteArray("-- Krecipes database schema: "));
		m_dumpFile->write(dbVersionString.toUtf8()); m_dumpFile->write(QByteArray("\n"));
	m_dumpFile->write(QByteArray("-- Krecipes database backend: "));
		m_dumpFile->write(config.readEntry( "Type" ).toUtf8()); m_dumpFile->write(QByteArray("\n"));

	kDebug()<<"Running '"<<command.first()<<"' to create backup file";
	*process << command /*<< ">" << backup_file*/;

	QApplication::connect( process, SIGNAL(readyRead()), this, SLOT(processDumpOutput()) );
	QApplication::connect( process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)) );
	QApplication::connect( process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError(QProcess::ProcessError)) );

	process->setOutputChannelMode( KProcess::MergedChannels );
	m_processFinished = false;
	m_processError = false;
	haltOperation = false;
	m_operationHalted = false;

	emit progressBegin(0,QString(),
		QString("<center><b>%1</b></center>%2")
			.arg(i18nc("@info:progress", "Creating complete backup"))
			.arg(i18n("Depending on the number of recipes and amount of data, this could take some time.")),50);

	m_localEventLoop = new QEventLoop;

	//This timer is to let the GUI kill the process even if it's hanged,
	//i.e. we will not receive readyRead() signals anymore for any reason.
	m_timer = new QTimer;
	QApplication::connect( m_timer, SIGNAL(timeout()), this, SLOT(cancelWatcher()) );
	m_timer->start(1000);

	process->start();
	m_localEventLoop->exec();
	delete m_timer;
	delete m_localEventLoop;
	
	if ( m_operationHalted ) {
		//User cancelled it; we'll still consider the operation successful,
		//but delete the file we created.
		kDebug()<<"Process killed, deleting partial backup.";
		QFile::remove(backup_file);
	} else if ( m_processError && !m_processFinished) {
		if ( errMsg ) *errMsg = i18n("Unable to find or run the program '%1'.  Either it is not installed on your system or it is not in $PATH.",command.first());
		QFile::remove(backup_file);
		delete process;
		process = NULL;
		delete m_dumpFile;
		emit progressDone();
		return false;
	} else if ((m_exitCode != 0) || (m_exitStatus != QProcess::NormalExit)) {
		kDebug()<<"Process failed.";
		//Since the process failed, dumpStream should have output from the app as to why it did
		QString appOutput;
		m_dumpFile->close();
		if ( m_dumpFile->open( QIODevice::ReadOnly ) ) {
			QTextStream appErrStream( m_dumpFile );

			//ignore our own versioning output
			appErrStream.readLine();
			appErrStream.readLine();
			appErrStream.readLine();

			appOutput = appErrStream.readAll();
		}
		else
			kDebug()<<"Unable to open file to get error output.";

		if ( errMsg ) *errMsg = i18n("Backup failed.\n%1", appOutput);
		QFile::remove(backup_file);
		delete process;
		process = NULL;
		delete m_dumpFile;
		emit progressDone();
		return false;
	}

	kDebug()<<"Backup finished.";

	delete process;
	process = NULL;
	delete m_dumpFile;
	emit progressDone();
	return true;
}
Example #22
0
bool ssh::dossh()
{
#ifdef USE_QSSH
    {
        if(m_connection && m_connection->state() != QSsh::SshConnection::Unconnected)
        {
            helpers::log("ssh: already connecting...", LOG_INF, qApp, 0);
            return true;
        }

        m_connection = new QSsh::SshConnection(params, this);
        connect(m_connection, SIGNAL(connected()), SLOT(onQsshConnected()));
        connect(m_connection, SIGNAL(error(QSsh::SshError)), SLOT(onQsshConnectionError(QSsh::SshError)));
        helpers::log("ssh: connecting START...", LOG_INF, qApp, 0);
        m_connection->connectToHost();
        return false;
    }
#else
    helpers::log("ssh: START: " + QString::number(QSslSocket::supportsSsl()), QSslSocket::supportsSsl() ? LOG_INF : LOG_ERR, qApp, 0);

//http://stackoverflow.com/questions/15213139/simple-qssl-client-server-cannot-start-handshake-on-non-plain-connection

    QSslSocket *socket = new QSslSocket(this);

    socket->ignoreSslErrors();
    socket->setPeerVerifyMode(QSslSocket::VerifyNone);
    socket->setProtocol(QSsl::SslV3);

    connect(socket, SIGNAL(encrypted()), this, SLOT(ready()));
    connect(socket, SIGNAL(encryptedBytesWritten(qint64)), this, SLOT(encryptedBytesWritten(qint64)));
    connect(socket, SIGNAL(modeChanged(QSslSocket::SslMode)), this, SLOT(modeChanged(QSslSocket::SslMode)));
    connect(socket, SIGNAL(peerVerifyError(const QSslError &)), this, SLOT(peerVerifyError(const QSslError &)));
    connect(socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));

    connect(socket, SIGNAL(connected()), this, SLOT(connected()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError)));
    connect(socket, SIGNAL(hostFound()), this, SLOT(hostFound()));
    connect(socket, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)), this, SLOT(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)));
    connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(stateChanged(QAbstractSocket::SocketState)));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));

    {
        {
              QFile file( "c:/Users/gherczeg/.ssh/id_boot2docker" );
              if( ! file.open( QIODevice::ReadOnly ) )
              {
                  QMessageBox::question(0, "Erreur", "Impossible de charger id_boot2docker");
                  return;
              }
              QSslKey key(&file);
              file.close();
              helpers::log("ssh:keyok: "+QString::number(!key.isNull()), !key.isNull() ? LOG_INF : LOG_ERR, qApp, 0);
              socket->setPrivateKey( key );
        }
        foreach (const QSslCertificate &cert, QSslCertificate::fromPath("c:/Users/gherczeg/.boot2docker/certs/boot2docker-vm/*.pem", QSsl::Pem, QRegExp::Wildcard))
        {
            helpers::log("ssh:certok1: "+QString::number(!cert.isNull()), !cert.isNull() ? LOG_INF : LOG_ERR, qApp, 0);
            socket->setLocalCertificate( cert );
            socket->sslConfiguration().caCertificates().append(cert);
            socket->addCaCertificate( cert );
            socket->addDefaultCaCertificate(cert);
        }
    }

    socket->connectToHostEncrypted("127.0.0.1", 2022);
    //socket->connectToHost("127.0.0.1", 2022);

    bool bok = socket->waitForEncrypted(100000);
    //bool bok = socket->waitForConnected(100000);
    if(!bok)
    {
        helpers::log("ssh:!waited:"+QString::number(bok),LOG_ERR, qApp, 0);
        return;
    }
    helpers::log("ssh:waited4ecnrypt/connect:"+QString::number(bok),LOG_INF, qApp, 0);
    socket->startClientEncryption();
    bool wait4Read1 = socket->waitForReadyRead(100000);
    helpers::log("ssh:wait4Read1:"+QString::number(wait4Read1),wait4Read1 ? LOG_INF : LOG_ERR, qApp, 0);
    QString s = "docker: do!";
    qint64 written = socket->write(s.toStdString().c_str());
    helpers::log("ssh:written:"+QString::number(written),written > 0 ? LOG_INF : LOG_ERR, qApp, 0);
    bool flushed = socket->flush();
    helpers::log("ssh:flush:"+QString::number(flushed),flushed ? LOG_INF : LOG_ERR, qApp, 0);
    bool wait4Write = socket->waitForBytesWritten(100000);
    helpers::log("ssh:wait4Write:"+QString::number(wait4Write),wait4Write ? LOG_INF : LOG_ERR, qApp, 0);
    bool wait4Read2 = socket->waitForReadyRead(100000);
    helpers::log("ssh:wait4Read2:"+QString::number(wait4Read2),wait4Read2 ? LOG_INF : LOG_ERR, qApp, 0);
    socket->disconnectFromHost();
#endif
}
Example #23
0
/**
 * @brief MainWindow::MainWindow
 * @param parent
 */
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    fConnected(false),
    bytesRequired(0),
    boardStatus(0)
{
    ui->setupUi(this);
    cbDevList = new QComboBox(ui->mainToolBar);
    cbDevList->setMinimumWidth(250);
    cbDevList->setEnabled(false);
    ui->mainToolBar->insertWidget(ui->actionHandleConnection, cbDevList);
    ui->mainToolBar->insertSeparator(ui->actionHandleConnection);
    lbI2CErrors = new QLabel(ui->statusBar);
    lbI2CErrors->setText("I2C Errors: 0");
    ui->statusBar->insertPermanentWidget(0, lbI2CErrors);

    serial = new QSerialPort(this);

    connect(ui->actionHandleConnection, SIGNAL(triggered()), this,
            SLOT(HandleSerialConnection()));
    connect(ui->actionRead, SIGNAL(triggered()), this, SLOT(HandleReadSettings()));
    connect(ui->actionSet, SIGNAL(triggered()), this, SLOT(HandleApplySettings()));
    connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(HandleSaveSettings()));
    connect(&timer, SIGNAL(timeout()), this, SLOT(ProcessTimeout()));
    connect(serial, SIGNAL(readyRead()), this, SLOT(ReadSerialData()));
    connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this,
            SLOT(HandleSerialError(QSerialPort::SerialPortError)));
    connect(ui->pushSensor1AccCalibrate, SIGNAL(clicked()), this, SLOT(HandleAccCalibrate()));
    connect(ui->pushSensor1GyroCalibrate, SIGNAL(clicked()), this, SLOT(HandleGyroCalibrate()));

    FillPortsInfo();

    for(int i = 0; i < 4; i++) {
        ui->comboPitchCommand->addItem(OutputCommands[i].item_name, OutputCommands[i].item_id);
        ui->comboRollCommand->addItem(OutputCommands[i].item_name, OutputCommands[i].item_id);
        ui->comboYawCommand->addItem(OutputCommands[i].item_name, OutputCommands[i].item_id);
    }
    ui->comboPitchCommand->setCurrentIndex(3);
    ui->comboRollCommand->setCurrentIndex(3);
    ui->comboYawCommand->setCurrentIndex(3);

    for(int i = 0; i < 5; i++) {
        ui->comboPitchDeadTime->addItem(OutputDeadTime[i].item_name, OutputDeadTime[i].item_id);
        ui->comboRollDeadTime->addItem(OutputDeadTime[i].item_name, OutputDeadTime[i].item_id);
        ui->comboYawDeadTime->addItem(OutputDeadTime[i].item_name, OutputDeadTime[i].item_id);
    }
    ui->comboPitchDeadTime->setCurrentIndex(4);
    ui->comboRollDeadTime->setCurrentIndex(4);
    ui->comboYawDeadTime->setCurrentIndex(4);

    for(int i = 0; i < 6; i++) {
        ui->comboInputChannelPitch->addItem(InputChannel[i].item_name, InputChannel[i].item_id);
        ui->comboInputChannelRoll->addItem(InputChannel[i].item_name, InputChannel[i].item_id);
        ui->comboInputChannelYaw->addItem(InputChannel[i].item_name, InputChannel[i].item_id);
    }
    ui->comboInputChannelPitch->setCurrentIndex(5);
    ui->comboInputChannelRoll->setCurrentIndex(5);
    ui->comboInputChannelYaw->setCurrentIndex(5);

    for(int i = 0; i < 3; i++) {
        ui->comboInputModePitch->addItem(InputMode[i].item_name, InputMode[i].item_id);
        ui->comboInputModeRoll->addItem(InputMode[i].item_name, InputMode[i].item_id);
        ui->comboInputModeYaw->addItem(InputMode[i].item_name, InputMode[i].item_id);
    }
    ui->comboInputModePitch->setCurrentIndex(0);
    ui->comboInputModeRoll->setCurrentIndex(0);
    ui->comboInputModeYaw->setCurrentIndex(0);

    for(int i = 0; i < 6; i++) {
        ui->comboSensor1AxisTOP->addItem(SensorAxis[i].item_name, SensorAxis[i].item_id);
        ui->comboSensor1AxisRIGHT->addItem(SensorAxis[i].item_name, SensorAxis[i].item_id);
    }
    ui->comboSensor1AxisTOP->setCurrentIndex(2);
    ui->comboSensor1AxisRIGHT->setCurrentIndex(3);

    ui->comboData->addItem(PlotData[0].item_name, PlotData[0].item_id);
    ui->comboData->setCurrentIndex(0);

    ui->plotData->addGraph();
     /* line color red for first graph. */
    ui->plotData->graph(0)->setPen(QPen(Qt::red));
    ui->plotData->addGraph();
    /* line color green for second graph. */
    ui->plotData->graph(1)->setPen(QPen(Qt::green));
    ui->plotData->addGraph();
    /* line color blue for third graph. */
    ui->plotData->graph(2)->setPen(QPen(Qt::blue));

    ui->plotData->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    ui->plotData->xAxis->setDateTimeFormat("hh:mm:ss");
    ui->plotData->xAxis->setAutoTickStep(false);
    ui->plotData->xAxis->setTickStep(2);
    ui->plotData->axisRect()->setupFullAxesBox();

    ui->plotData->yAxis->setLabel("Attitude, deg");

    /* make left and bottom axes transfer their ranges to right and top axes: */
    connect(ui->plotData->xAxis, SIGNAL(rangeChanged(QCPRange)),
            ui->plotData->xAxis2, SLOT(setRange(QCPRange)));
    connect(ui->plotData->yAxis, SIGNAL(rangeChanged(QCPRange)),
            ui->plotData->yAxis2, SLOT(setRange(QCPRange)));

    connect(ui->checkDataX, SIGNAL(clicked()), this, SLOT(HandleDataXClicked()));
    connect(ui->checkDataY, SIGNAL(clicked()), this, SLOT(HandleDataYClicked()));
    connect(ui->checkDataZ, SIGNAL(clicked()), this, SLOT(HandleDataZClicked()));
}
Example #24
0
{
  PacketUdp *udp = new PacketUdp(QHostAddress(TESTADDR), 10000);
  mainWindow->onEthernetDeviceArrived(udp);
  QCOMPARE(mainWindow->ui.deviceList->count(), 1);
  QSettings settings;
  serverPort = settings.value("xml_listen_port", DEFAULT_XML_LISTEN_PORT).toInt();
  qRegisterMetaType< QList<Board*> >("QList<Board*>");
}

/*
  Connect to the OSC XML server, make sure it opens the connection OK, & sends a board update.
*/
void TestXmlServer::clientConnect()
{
  updateSpy = new QSignalSpy(mainWindow->oscXmlServer, SIGNAL(boardListUpdated(QList<Board*>, bool)));
  QSignalSpy client1DataSpy(&xmlClient1, SIGNAL(readyRead()));

  xmlClient1.connectToHost(QHostAddress::LocalHost, serverPort);
  int count = 0;
  while (xmlClient1.state() != QAbstractSocket::ConnectedState) {
    QTest::qWait(250);
    if (count++ > 10)
      QFAIL("client 1 couldn't connect to server.");
  }
  QTest::qWait(100);

  //QCOMPARE(updateSpy->count(), 1 );
  QCOMPARE(client1DataSpy.count(), 1);
  QList<QByteArray> newDocuments = xmlClient1.readAll().split('\0');
  foreach (const QByteArray & document, newDocuments) {
    qDebug() << "data" << QString(document);
Example #25
0
void GuestToolsListener::setupConnection()
{
    qDebug() << "setting up guest tools";
    addModules();
    connect(toolSocket, SIGNAL(readyRead()), this, SLOT(receiveData()));
}
Example #26
0
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    displayTimer = new QTimer();
    displayTimer->setInterval(1000);
    connect(displayTimer,SIGNAL(timeout()),this,SLOT(onDisplayTime()));
    displayTimer->start();
    updateSocket = new QUdpSocket();
    updateSocket->bind(UDP_UPDATE_LINSTEN_PORT,QUdpSocket::ShareAddress);
    connect(updateSocket,SIGNAL(readyRead()),this,SLOT(onUpdateUdpRead()));
    file.setFileName(UPDATE_TEMP_FILE_NAME);
    fileManager = new FileManager;
    cmdSocket = new QUdpSocket();
    cmdSocket->bind(UDP_CMD_LINSTEN_PORT,QUdpSocket::ShareAddress);
    connect(cmdSocket,SIGNAL(readyRead()),this,SLOT(onCmdUdpRead()));

//    serialManager = new SerialManager;

//    form0_welcome = new FormWelcome;
//    form1_account = new FormLicense;
    form2_main = new FormMain;
    form3_vibrationAdjust = new FormVibrationAdjust;
    form4_mode = new FormModeSelect;
    form5_accuracy = new FormAccuracyAdjust;
//    form6_system = new FormSystem;
//    form7_shutdown = new FormShutdown;
//    form8_admin = new FormAdmin;
//    form9_ash = new FormAshClean;
//    form10_bkg = new FormCCDCurve;
//    form11_valve = new FormValveTest;
//    form12_accuracyDetail = new FormAccuracyDetailAdjust;
//    form13_whole = new FormWholeSetting;
//    form14_monitor = new FormCntCheck;
    form15_all = new FormAll;

//    connect(form0_welcome,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(form1_account,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
    connect(form2_main,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
    connect(form3_vibrationAdjust,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
    connect(form4_mode,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
    connect(form5_accuracy,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(form6_system,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(form7_shutdown,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(form8_admin,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(form9_ash,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(form10_bkg,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(form11_valve,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(form12_accuracyDetail,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(form13_whole,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(form14_monitor,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));
//    connect(fileManager,SIGNAL(switchToPage(int)),ui->stackedWidget,SLOT(setCurrentIndex(int)));

    connect(fileManager,SIGNAL(sigConfigChanged()),form3_vibrationAdjust,SLOT(updateData()));
    connect(fileManager,SIGNAL(sigConfigChanged()),form4_mode,SLOT(updateData()));
//    connect(fileManager,SIGNAL(sigConfigChanged()),form9_ash,SLOT(updateData()));
//    connect(fileManager,SIGNAL(sigConfigChanged()),form10_bkg,SLOT(updateData()));
//    connect(fileManager,SIGNAL(sigConfigChanged()),form11_valve,SLOT(updateData()));
//    connect(fileManager,SIGNAL(sigConfigChanged()),form12_accuracyDetail,SLOT(updateData()));
//    connect(fileManager,SIGNAL(sigConfigChanged()),form13_whole,SLOT(updateData()));

//    connect(serialManager,SIGNAL(cleanAshRequire()),form9_ash,SLOT(autoCleanAsh()));
//    connect(serialManager,SIGNAL(updateCCD(QByteArray)),form10_bkg,SLOT(updateCCD(QByteArray)));
//    connect(serialManager,SIGNAL(cntUpload(int,int,int)),form14_monitor,SLOT(cntUpload(int,int,int)));
//    connect(serialManager,SIGNAL(resetSuccess()),form14_monitor,SLOT(resetSuccess()));

    ui->stackedWidget->insertWidget(0,form15_all);
//    ui->stackedWidget->insertWidget(0,form14_monitor);
//    ui->stackedWidget->insertWidget(0,form13_whole);
//    ui->stackedWidget->insertWidget(0,form12_accuracyDetail);
//    ui->stackedWidget->insertWidget(0,form11_valve);
//    ui->stackedWidget->insertWidget(0,form10_bkg);
//    ui->stackedWidget->insertWidget(0,form9_ash);
//    ui->stackedWidget->insertWidget(0,form8_admin);
//    ui->stackedWidget->insertWidget(0,form7_shutdown);
//    ui->stackedWidget->insertWidget(0,form6_system);
    ui->stackedWidget->insertWidget(0,form5_accuracy);
    ui->stackedWidget->insertWidget(0,form4_mode);
    ui->stackedWidget->insertWidget(0,form3_vibrationAdjust);
    ui->stackedWidget->insertWidget(0,form2_main);
//    ui->stackedWidget->insertWidget(0,form1_account);
//    ui->stackedWidget->insertWidget(0,form0_welcome);
    ui->stackedWidget->setCurrentIndex(0);
    cmdBuf.clear();
}
Example #27
0
void GameState::init()
{
    QAbstractSocket::SocketState state = getSocket()->state();
    QObject::connect(getSocket().data(), SIGNAL(readyRead()), this, SLOT(readyReadHandler()));

}
RoboControllerSDK::RoboControllerSDK(QString serverAddr/*=QString("127.0.0.1")*/,
                                     quint16 udpStatusPortSend/*=14550*/,
                                     quint16 udpStatusPortListen/*=14555*/,
                                     quint16 udpControlPort/*=14560*/,
                                     quint16 tcpPort/*=14500*/) :
    mTcpSocket(NULL),
    mUdpStatusSocket(NULL),
    mUdpControlSocket(NULL)
{
    mStopped = true;
    mWatchDogTimeMsec = 1000;
    mMsgCounter = 0;

    // Ping Timer
    connect( &mPingTimer, SIGNAL(timeout()), this, SLOT(onPingTimerTimeout()));

    // >>>>> TCP Socket
    mTcpSocket = new QTcpSocket(this);

    mServerAddr = serverAddr;
    mTcpPort = tcpPort;

    connect(mTcpSocket, SIGNAL(readyRead()),
            this, SLOT(onTcpReadyRead()));
    connect(mTcpSocket, SIGNAL(hostFound()),
            this, SLOT(onTcpHostFound()));
    connect(mTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(onTcpError(QAbstractSocket::SocketError)));

    try
    {
        connectToTcpServer();
    }
    catch( RcException &e )
    {
        qDebug() << e.getExcMessage();
        throw e;
    }
    // <<<<< TCP Socket

    // >>>>> UDP Sockets
    mUdpControlSocket = new QUdpSocket(this);
    mUdpStatusSocket = new QUdpSocket(this);

    mUdpControlPortSend = udpControlPort;
    mUdpStatusPortSend = udpStatusPortSend;
    mUdpStatusPortListen = udpStatusPortListen;

    /*connect( mUdpControlSocket, SIGNAL(readyRead()),
             this, SLOT(onUdpControlReadyRead()) ); // The control UDP Socket does not receive!*/
    connect( mUdpStatusSocket, SIGNAL(readyRead()),
             this, SLOT(onUdpStatusReadyRead()) );

    connect( mUdpControlSocket, SIGNAL(error(QAbstractSocket::SocketError)),
             this, SLOT(onUdpControlError(QAbstractSocket::SocketError)) );
    connect( mUdpStatusSocket, SIGNAL(error(QAbstractSocket::SocketError)),
             this, SLOT(onUdpStatusError(QAbstractSocket::SocketError)) );

    try
    {
        connectToUdpServers();
    }
    catch( RcException &e )
    {
        qDebug() << e.getExcMessage();
        throw e;
    }

    // <<<<< UDP Sockets
    mMotorCtrlMode = mcPID; // RoboController is in PID mode by default

    // Start thread
    mStopped = false;
    start();
}
Example #29
0
// Slot called when the server starts
void instanceManager::connected()
{
    client = server->nextPendingConnection();
    connect( client, SIGNAL(readyRead ()), this, SLOT(readParams()));
}
SerialPort::SerialPort(QObject *parent) : QObject(parent)
{
    connect(&serialport, SIGNAL(readyRead()), this, SLOT(emit_ready_read()));
}