예제 #1
0
TipsOfTheDay::TipsOfTheDay(QString xmlPath, QObject *parent) : QAbstractListModel(parent)
{
    tipList = new QList<TipOfTheDay>;

    QFile xmlFile(xmlPath);

    QTextStream errorStream(stderr);
    if (!QFile::exists(xmlPath)) {
        errorStream << tr("File does not exist.\n");
        return;
    } else if (!xmlFile.open(QIODevice::ReadOnly)) {
        errorStream << tr("Failed to open file.\n");
        return;
    }

    QXmlStreamReader reader(&xmlFile);

    while (!reader.atEnd()) {
        if (reader.readNext() == QXmlStreamReader::EndElement) {
            break;
        }

        if (reader.name() == "tip") {
            QString title, content, imagePath;
            QDate date;
            reader.readNext();
            while (!reader.atEnd()) {
                if (reader.readNext() == QXmlStreamReader::EndElement) {
                    break;
                }

                if (reader.name() == "title") {
                    title = reader.readElementText();
                } else if (reader.name() == "text") {
                    content = reader.readElementText();
                } else if (reader.name() == "image") {
                    imagePath = "theme:tips/images/" + reader.readElementText();
                } else if (reader.name() == "date") {
                    date = QDate::fromString(reader.readElementText(), Qt::ISODate);
                } else {
                    // unkown element, do nothing
                }
            }
            tipList->append(TipOfTheDay(title, content, imagePath, date));
        }
    }
}
예제 #2
0
int InqludeClient::run()
{
    DataProvider::Ptr provider = DataProvider::createProvider();

    QCommandLineParser parser;
    parser.setApplicationDescription(tr("Command-line client for the inqlude.org repository of Qt libraries"));
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("command", tr("Command: \n"
                "\tlist               List libraries\n"
                "\tdownload <lib>     Download a given library\n"));
    // This leads to --list or -list, it would be nice for QCommandLineParser to support "list" too, but how
    // would it know where to stop parsing options? I guess this would require builtin support for "one-word commands" then.
    //QCommandLineOption optList("list", tr("List libraries"));
    //parser.addOption(optList);

    parser.process(*qApp);


    const QStringList args = parser.positionalArguments();
    const QString command = args.isEmpty() ? QString() : args.first();
    if (command == QLatin1String("list")) {
        QTextStream outStream(stdout);
        ListHandler handler(outStream);
        handler.setQuitOnCompletion(true);
        connect(provider.data(), &DataProvider::dataAvailable, &handler, &ListHandler::list);
        ensureDataAvailable(provider);
        return qApp->exec();
    } else if (command == QLatin1String("download")) {
        if (args.count() < 2) {
            parser.showHelp(1);
        }
        const QString library = args.at(1);
        QTextStream errorStream(stdout);
        DownloadHandler handler(errorStream, library);
        handler.setQuitOnCompletion(true);
        connect(provider.data(), &DataProvider::dataAvailable, &handler, &DownloadHandler::download);
        ensureDataAvailable(provider);
        return qApp->exec();
    }

    parser.showHelp(1);
    return 1;
}
예제 #3
0
파일: main.cpp 프로젝트: Fale/qtmoko
int main(int argc, char *argv[])
{
    enum ExitCode
    {
        Success,
        ParseFailure,
        ArgumentError,
        WriteError,
        FileFailure
    };

    QCoreApplication app(argc, argv);

    QTextStream errorStream(stderr);

    if (argc != 2)
    {
        errorStream << PrettyPrint::tr(
                       "Usage: prettyprint <path to XML file>\n");
        return ArgumentError;
    }

    QString inputFilePath(QCoreApplication::arguments().at(1));
    QFile inputFile(inputFilePath);

    if (!QFile::exists(inputFilePath))
    {
        errorStream << PrettyPrint::tr(
                       "File %1 does not exist.\n").arg(inputFilePath);
        return FileFailure;

    } else if (!inputFile.open(QIODevice::ReadOnly)) {
        errorStream << PrettyPrint::tr(
                       "Failed to open file %1.\n").arg(inputFilePath);
        return FileFailure;
    }

    QFile outputFile;
    if (!outputFile.open(stdout, QIODevice::WriteOnly))
    {
        QTextStream(stderr) << PrettyPrint::tr("Failed to open stdout.");
        return WriteError;
    }

    QXmlStreamReader reader(&inputFile);
    int indentation = 0;
    QHash<int,QPair<int, int> > indentationStack;

    while (!reader.atEnd())
    {
        reader.readNext();
        if (reader.isStartElement()) {
            indentationStack[indentation] = QPair<int,int>(
                reader.lineNumber(), reader.columnNumber());
            indentation += 1;
        } else if (reader.isEndElement()) {
            indentationStack.remove(indentation);
            indentation -= 1;
        }

        if (reader.error())
        {
            errorStream << PrettyPrint::tr(
                           "Error: %1 in file %2 at line %3, column %4.\n").arg(
                               reader.errorString(), inputFilePath,
                               QString::number(reader.lineNumber()),
                               QString::number(reader.columnNumber()));
            if (indentationStack.contains(indentation-1)) {
                int line = indentationStack[indentation-1].first;
                int column = indentationStack[indentation-1].second;
                errorStream << PrettyPrint::tr(
                               "Opened at line %1, column %2.\n").arg(
                                   QString::number(line),
                                   QString::number(column));
            }
            return ParseFailure;

        } else if (reader.isStartElement() && !reader.name().isEmpty()) {
            outputFile.write(QByteArray().fill(' ', indentation));
            outputFile.write(reader.name().toString().toLocal8Bit());
            outputFile.write(QString(" line %1, column %2\n").arg(
                reader.lineNumber()).arg(reader.columnNumber()).toLocal8Bit());
        }
    }

    return Success;
}
예제 #4
0
int tcp_ping(QStringList command) {
    qDebug() << "tcp_ping(" << command.join(" ") << ")" << endl;

    /**
     * Check input
     */
    QTextStream errorStream(stderr);

    if(command.size() != 3 || command.at(0)!="ping" || command.at(1)!="tcp" ) {

        errorStream << "Error: tcp_ping(" << command.join(" ") << ") is no valid call (ping tcp <ip_address> <port> rzv|max|random|default)" << endl;
        return 1;
    }

    QByteArray byteArray;

    /**
     * CIP for "rzv"
     */
    if(command.at(2)=="rzv") {
        qDebug() << "rzv" << endl;

        byteArray.append(QByteArray(42, '\0'));
     }

    /**
     * CIP for "default"
     */
    if(command.at(2)=="default") {
        qDebug() << "default" << endl;

        // Header: request (1), profile (1), version (1), channel (1)
        byteArray.append(QByteArray(4, '\0'));

        // Header: UUID (16)
        QUuid uuid;
        uuid = QUuid::createUuid();
        QByteArray uuid_arr = uuid.toRfc4122();

        for(int j=0; j<16;j++) {

            byteArray.append(uuid_arr.at(j));
        }

        // Header: Empty IP address (4), port number (2), time (8), type (1), size (1)
        byteArray.append(QByteArray(16, '\0'));

        // Contextinformation: type (1), root-CIC (2), size (1)
        byteArray.append(QByteArray(4, '\0'));

        // Application: type (1), size (1)
        byteArray.append(QByteArray(2, '\0'));
     }

    /**
     * CIP for "max"
     */
    if(command.at(2)=="max") {
        qDebug() << "max" << endl;

        // Header: fix
        byteArray.append(QByteArray(34, '\0'));

        // Header: size (1)
        byteArray.append(QByteArray(QByteArray::fromHex("0xff")));
        byteArray.append(QByteArray(255, '\0'));

        // Contextinformation: fix
        byteArray.append(QByteArray(2, '\0'));

        // Contextinformation: size (255)
        byteArray.append(QByteArray(QByteArray::fromHex("0xff")));
        byteArray.append(QByteArray(255*2, '\0'));

        // Application Data: fix
        byteArray.append(QByteArray(0, '\0'));

        // Application Data: size (255)
        byteArray.append(QByteArray(QByteArray::fromHex("0xff")));
        byteArray.append(QByteArray(255, '\0'));


     }

    /**
     * CIP for "random"
     */
    if(command.at(2)=="random") {
        qDebug() << "random" << endl;

        QByteArray randValues;
        qsrand(QTime::currentTime().msec());
        for(int i=0; i <= 1064; i++) {
            randValues.append(qFloor(qrand()/CRN_RANDOM_DIVISOR));
        }


        int i = 0;
        quint8 rand;

        // Header: request (1)
        byteArray.append(randValues.at(i++));


        // Header: profile (1)
        byteArray.append(randValues.at(i++));


        // Header: version (1)
        byteArray.append(randValues.at(i++));


        // Header: channel (1)
        byteArray.append(randValues.at(i++));

        // Header: UUID (16)
        QUuid uuid;
        uuid = QUuid::createUuid();
        QByteArray uuid_arr = uuid.toRfc4122();

        for(int j=0; j<16;j++) {

            byteArray.append(uuid_arr.at(j));
        }

        // Header: Empty IP address (4) and port number (2)
        byteArray.append(QByteArray(6, '\0'));

        // Header: time (8)
        byteArray.append(QByteArray(8, '\0'));

        // Header: type (1)
        byteArray.append(randValues.at(i++));

        // Header: size (1) and data
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand, rand));

        // Contextinformation: type (1)
        byteArray.append(randValues.at(i++));

        // Contextinformation: root-CIC (2)
        byteArray.append(randValues.at(i++));
        byteArray.append(randValues.at(i++));

        // Contextinformation: size (1)
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand*2, rand));

        // Application: type (1)
        byteArray.append(randValues.at(i++));

        // Application: size (1)
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand, rand));

    } // rand

    /**
     * Sent via TCP
     */
    QTcpSocket *tcpSocket;
    tcpSocket = new QTcpSocket();
    QTextStream outStream(stdout);

    QString out;

    tcpSocket->abort();
    tcpSocket->connectToHost("127.0.0.1", 22365);

    qDebug() << "waitForConnected!";
    if (tcpSocket->waitForConnected(5000)) {

        qDebug() << "Connected!";
    }
    else {
        errorStream << "Error: tcp_ping(" << command.join(" ") << ") No connection available!" << endl;
        return 1;
    }

    out = QString("BytesWritten: %1").arg(tcpSocket->write(byteArray, byteArray.length()));

    qDebug() << out;

    int numRead = 0, numReadTotal = 0;
    char buffer[MAXMSG];

    forever {
        numRead  = tcpSocket->read(buffer, MAXMSG);
        qDebug() << "read buffer";

        qDebug() << buffer;

        numReadTotal += numRead;
        if (numRead == 0 && !tcpSocket->waitForReadyRead())
            break;
    }
    qDebug() << numReadTotal << " bytes red";

    tcpSocket->flush();
    tcpSocket->disconnectFromHost();
    tcpSocket->close();

    outStream << out << endl;

    return 0;
}
예제 #5
0
int set_head(QStringList command) {
    qDebug() << "set_head(" << command.join(" ") << ")" << endl;

    /**
     * Debug
     */
    for(int i=0;i<command.size();i++) {
        qDebug() << "command.at(" << i << ")" << command.at(i) << endl;
    }

    /**
     * Check input
     */
    QTextStream errorStream(stderr);

    if(command.size() != 5) {

        errorStream << "Error: set_head(" << command.join(" ") << "): No valid number of arguments!" << endl;
        man("usage set_head");
        return 1;
    }


    if(command.at(0)!="set_head") {

        errorStream << "Error: set_head(" << command.join(" ") << "): No valid command!" << endl;
        man("usage set_head");
        return 1;
    }

    if(! command.at(2).contains(QRegExp("^(binary|integer|hex|cip)$"))) {

        errorStream << "Error: set_head(" << command.join(" ") << "): No valid CIP omode!" << endl;
        man("usage set_head");
        return 1;
    }

    if(! command.at(3).contains(QRegExp("^(request|profile|version|channel|uuid|ip|port|time|type|size|data)$"))) {

        errorStream << "Error: set_head(" << command.join(" ") << "): No valid header key!" << endl;
        man("usage set_head");
        return 1;
    }

    /**
     * Check value for integer and single value
     */
    if(command.at(2)=="integer" && command.at(3).contains(QRegExp("^(request|profile|version|channel|type|size)$"))
            && // not uint8 (0-255)
            ((! command.at(4).contains(QRegExp("^\\d\\d?\\d?$")))
            || command.at(4).toInt() < 0
            || command.at(4).toInt() > 255)) {

        errorStream << "Error: set_head(" << command.join(" ") << "): No valid header value!" << endl;
        man("usage set_head");
        return 1;
    }

    /**
     * Check value for binary and single value
     */
    if(command.at(2)=="binary" && command.at(3).contains(QRegExp("^(request|profile|version|channel|type|size)$"))
            && // not uint8 (00000000-11111111)
            ((! command.at(4).contains(QRegExp("^(0|1){8}$"))))) {

        errorStream << "Error: set_head(" << command.join(" ") << "): No valid header value!" << endl;
        man("usage set_head");
        return 1;
    }

    /**
     * Check value for hex and single value
     */
    if(command.at(2)=="hex" && command.at(3).contains(QRegExp("^(request|profile|version|channel|type|size)$"))
            && // not uint8 (00-ff)
            ((! command.at(4).contains(QRegExp("^(\\d|a|b|c|d|e|f){2}$"))))) {

        errorStream << "Error: set_head(" << command.join(" ") << "): No valid header value!" << endl;
        man("usage set_head");
        return 1;
    }


    /**
     * Check value for binary and uuid
     */
    if(command.at(2)=="binary" && command.at(3)=="uuid") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for integer and uuid
     */
    if(command.at(2)=="integer" && command.at(3)=="uuid") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for hex and uuid
     */
    if(command.at(2)=="hex" && command.at(3)=="uuid"
            && // not (0-16^32)
            ((! command.at(4).contains(QRegExp("^(\\d|a|b|c|d|e|f){32}$"))))) {

        errorStream << "Error: set_head(" << command.join(" ") << "): No valid header value!" << endl;
        man("usage set_head");
        return 1;
    }

    /**
     * Check value for cip and uuid
     */
    if(command.at(2)=="cip" && command.at(3)=="uuid") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }


    /**
     * Check value for binary and ip
     */
    if(command.at(2)=="binary" && command.at(3)=="ip") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for integer and ip
     */
    if(command.at(2)=="integer" && command.at(3)=="ip") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for hex and ip
     */
    if(command.at(2)=="hex" && command.at(3)=="ip") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for cip and ip
     */
    if(command.at(2)=="cip" && command.at(3)=="ip") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }




    /**
     * Check value for binary and port
     */
    if(command.at(2)=="binary" && command.at(3)=="port") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for integer and port
     */
    if(command.at(2)=="integer" && command.at(3)=="port") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for hex and port
     */
    if(command.at(2)=="hex" && command.at(3)=="port") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for cip and port
     */
    if(command.at(2)=="cip" && command.at(3)=="port") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }




    /**
     * Check value for binary and time
     */
    if(command.at(2)=="binary" && command.at(3)=="time") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for integer and time
     */
    if(command.at(2)=="integer" && command.at(3)=="time") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for hex and time
     */
    if(command.at(2)=="hex" && command.at(3)=="time") {
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * Check value for cip and time
     */
    if(command.at(2)=="cip" && command.at(3)=="time" && command.at(4)!="now") {
        errorStream << "Error: set_head(" << command.join(" ") << "): No valid header value!" << endl;
        man("usage set_head time");
        return 1;
    }



    /**
     * Read file
     */

    QString filePath;

    filePath = CIP_ROOT;
    filePath += "/" + command.at(1);

    qDebug() << "filePath: " << filePath << endl;

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {

        errorStream << "Error: set_head(" << command.join(" ") << ") can not read " << filePath << endl;
        return 1;
    }

    QByteArray byteArray;
    byteArray = file.readAll();
    file.close();

    qDebug() << "byteArray.size(): " << byteArray.size() << endl;



    /**
     * Define map with start position
     */

    QMap<QString, int> keys;
    int pos;

    keys["request"] = 0;
    keys["profile"] = 1;
    keys["version"] = 2;
    keys["channel"] = 3;
    keys["uuid"] = 4;
    keys["ip"] = 20;
    keys["port"] = 24;
    keys["time"] = 26;
    keys["type"] = 34;
    keys["size"] = 35;



    QByteArray value;
    bool ok;


    /**
     * One byte keys (without size)
     */

    if(command.at(3).contains(QRegExp("^(request|profile|version|channel|type|size)$"))) {


        if (keys.contains(command.at(3))) {
            qDebug() << "keys.contains(" << command.at(3) << ")" << endl;

            if(command.at(2)=="binary") {
                value.append(command.at(4).toUInt(&ok, 2));

                if(!ok) {
                    errorStream << "Cannot convert "<< command.at(4) << " to base 2!" << endl;
                    return 1;
                }
            }

            if(command.at(2)=="integer") {
                value.append(command.at(4).toUInt(&ok, 10));

                if(!ok) {
                    errorStream << "Cannot convert "<< command.at(4) << " to base 10!" << endl;
                    return 1;
                }
            }

            if(command.at(2)=="hex") {
                value.append(command.at(4).toUInt(&ok, 16));

                if(!ok) {
                    errorStream << "Cannot convert "<< command.at(4) << " to base 16!" << endl;
                    return 1;
                }
            }

            if(command.at(2)=="cip") {
                errorStream << "Not yet specified!" << endl;
                return 1;
            }

            pos = keys[command.at(3)];

            qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl;
            byteArray.replace(pos, 1, value);
        }
        else {
            errorStream << "Cannot find key for "<< command.at(3) << "!" << endl;
            return 1;
        }

    }

    /**
     * uuid (16)
     */
    if(command.at(3)=="uuid") {
        if (keys.contains(command.at(3))) {
            qDebug() << "keys.contains(" << command.at(3) << ")" << endl;


            value.append(command.at(4).toLatin1());
            value.insert(20, '-');
            value.insert(16, '-');
            value.insert(12, '-');
            value.insert(8, '-');

            qDebug() << "value: " << value << endl;

            QUuid uuid(value);

            pos = keys[command.at(3)];

            qDebug() << "byteArray.replace(" << pos << ", 16, " << uuid << ")" << endl;
            byteArray.replace(pos, 16, uuid.toRfc4122());

        }
        else {
            errorStream << "Cannot find key for "<< command.at(3) << "!" << endl;
            return 1;
        }
    }

    /**
     * ip (4)
     */
    if(command.at(3)=="ip") {
        if (keys.contains(command.at(3))) {
            qDebug() << "keys.contains(" << command.at(3) << ")" << endl;
        }
        else {
            errorStream << "Cannot find key for "<< command.at(3) << "!" << endl;
            return 1;
        }
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * port (2)
     */
    if(command.at(3)=="port") {
        if (keys.contains(command.at(3))) {
            qDebug() << "keys.contains(" << command.at(3) << ")" << endl;
        }
        else {
            errorStream << "Cannot find key for "<< command.at(3) << "!" << endl;
            return 1;
        }
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }

    /**
     * time (8)
     */
    if(command.at(3)=="time") {
        if (keys.contains(command.at(3))) {
            qDebug() << "keys.contains(" << command.at(3) << ")" << endl;
        }
        else {
            errorStream << "Cannot find key for "<< command.at(3) << "!" << endl;
            return 1;
        }

        uint unixTime = QDateTime::currentDateTime().toTime_t();
        qDebug().noquote().nospace() << "NOW: " << QDateTime::fromTime_t(unixTime).toString() << endl;

        pos = keys[command.at(3)];

        for(int j = 0; j < 8; j++) {

            byteArray[pos++] = unixTime%256;
            qDebug().noquote().nospace() << "time[" << j << "]: " << QString("%1").arg(unixTime%256, 8, 2, QLatin1Char('0'));

            unixTime = unixTime >> 8;
        }
    }

    /**
     * size (1)
     */
    if(command.at(3)=="size") {
        if (keys.contains(command.at(3))) {
            qDebug() << "keys.contains(" << command.at(3) << ")" << endl;
        }
        else {
            errorStream << "Cannot find key for "<< command.at(3) << "!" << endl;
            return 1;
        }

        pos = keys[command.at(3)];

        qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl;
        byteArray.replace(pos, 1, value);
    }

    /**
     * data (size)
     */
    if(command.at(3)=="data") {
        if (keys.contains(command.at(3))) {
            qDebug() << "keys.contains(" << command.at(3) << ")" << endl;
        }
        else {
            errorStream << "Cannot find key for "<< command.at(3) << "!" << endl;
            return 1;
        }
        errorStream << "Not yet implemented!" << endl;
        return 1;
    }


    /**
     * Write file
     */

    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {

        errorStream << "Error: set_head(" << command.join(" ") << ") can not write to file " << filePath << endl;
        return 1;
    }
    file.write(byteArray);

    file.close();

    qDebug() << "filePath: " << filePath << endl;

    return 0;
}
예제 #6
0
파일: main.cpp 프로젝트: Afreeca/qt
int main(int argc, char *argv[])
{
    enum ExitCode
    {
        Success,
        ParseFailure,
        ArgumentError,
        WriteError,
        FileFailure
    };

    QCoreApplication app(argc, argv);

    QTextStream errorStream(stderr);

    if (argc != 2)
    {
        errorStream << XmlStreamLint::tr(
                       "Usage: xmlstreamlint <path to XML file>\n");
        return ArgumentError;
    }

    QString inputFilePath(QCoreApplication::arguments().at(1));
    QFile inputFile(inputFilePath);

    if (!QFile::exists(inputFilePath))
    {
        errorStream << XmlStreamLint::tr(
                       "File %1 does not exist.\n").arg(inputFilePath);
        return FileFailure;

    } else if (!inputFile.open(QIODevice::ReadOnly)) {
        errorStream << XmlStreamLint::tr(
                       "Failed to open file %1.\n").arg(inputFilePath);
        return FileFailure;
    }

    QFile outputFile;
    if (!outputFile.open(stdout, QIODevice::WriteOnly))
    {
        errorStream << XmlStreamLint::tr("Failed to open stdout.");
        return WriteError;
    }

//! [0]
    QXmlStreamReader reader(&inputFile);
    QXmlStreamWriter writer(&outputFile);
//! [0]

//! [1]
    while (!reader.atEnd())
    {
        reader.readNext();

        if (reader.error())
        {
            errorStream << XmlStreamLint::tr(
                           "Error: %1 in file %2 at line %3, column %4.\n").arg(
                               reader.errorString(), inputFilePath,
                               QString::number(reader.lineNumber()),
                               QString::number(reader.columnNumber()));
            return ParseFailure;
//! [1]

//! [2]
        } else
            writer.writeCurrentToken(reader);
    }
//! [2]

    return Success;
}
예제 #7
0
int set_app(QStringList command) {
    qDebug() << "set_app(" << command.join(" ") << ")" << endl;


    /**
     * Debug
     */
    for(int i=0;i<command.size();i++) {
        qDebug() << "command.at(" << i << ")" << command.at(i) << endl;
    }


    /**
     * Check input
     */
    QTextStream errorStream(stderr);

    if(command.size() != 5) {

        errorStream << "Error: set_app(" << command.join(" ") << "): No valid number of arguments!" << endl;
        man("usage set_app");
        return 1;
    }


    if(command.at(0)!="set_app") {

        errorStream << "Error: set_app(" << command.join(" ") << "): No valid command!" << endl;
        man("usage set_app");
        return 1;
    }

    if(! command.at(2).contains(QRegExp("^(binary|integer|hex|cip)$"))) {

        errorStream << "Error: set_app(" << command.join(" ") << "): No valid CIP mode!" << endl;
        man("usage set_app");
        return 1;
    }


    if(! command.at(3).contains(QRegExp("^(type|size|data)$"))) {

        errorStream << "Error: set_app(" << command.join(" ") << "): No valid key!" << endl;
        man("usage set_app");
        return 1;
    }


    /**
     * Check value for integer and single value
     */
    if(command.at(2)=="integer" && command.at(3).contains(QRegExp("^(type|size)$"))
            && // not uint8 (0-255)
            ((! command.at(4).contains(QRegExp("^\\d\\d?\\d?$")))
            || command.at(4).toInt() < 0
            || command.at(4).toInt() > 255)) {

        errorStream << "Error: set_ci(" << command.join(" ") << "): No valid value!" << endl;
        man("usage set_ci");
        return 1;
    }

    /**
     * Check value for binary and single value
     */
    if(command.at(2)=="binary" && command.at(3).contains(QRegExp("^(type|size)$"))
            && // not uint8 (00000000-11111111)
            ((! command.at(4).contains(QRegExp("^(0|1){8}$"))))) {

        errorStream << "Error: set_ci(" << command.join(" ") << "): No valid value!" << endl;
        man("usage set_ci");
        return 1;
    }

    /**
     * Check value for hex and single value
     */
    if(command.at(2)=="hex" && command.at(3).contains(QRegExp("^(type|size)$"))
            && // not uint8 (00-ff)
            ((! command.at(4).contains(QRegExp("^(\\d|a|b|c|d|e|f){2}$"))))) {

        errorStream << "Error: set_ci(" << command.join(" ") << "): No valid value!" << endl;
        man("usage set_ci");
        return 1;
    }


    /**
     * Read file
     */

    QString filePath;

    filePath = CIP_ROOT;
    filePath += "/" + command.at(1);

    qDebug() << "filePath: " << filePath << endl;

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {

        errorStream << "Error: set_ci(" << command.join(" ") << ") can not read " << filePath << endl;
        return 1;
    }

    QByteArray byteArray;
    byteArray = file.readAll();
    file.close();

    qDebug() << "byteArray.size(): " << byteArray.size() << endl;



    /**
     * Define map with start position
     */

    QMap<QString, int> keys;
    int pos;

    int i = byteArray.at(35) + 39;
    i += byteArray.at(i)*2;

    keys["type"] = ++i;
    keys["size"] = ++i;
    keys["data"] = ++i;

    QByteArray value;
    bool ok;


    /**
     * One byte keys (without size)
     */

    if(command.at(3).contains(QRegExp("^(type|size)$"))) {


        if (keys.contains(command.at(3))) {
            qDebug() << "keys.contains(" << command.at(3) << ")" << endl;

            if(command.at(2)=="binary") {
                value.append(command.at(4).toUInt(&ok, 2));

                if(!ok) {
                    errorStream << "Cannot convert "<< command.at(4) << " to base 2!" << endl;
                    return 1;
                }
            }

            if(command.at(2)=="integer") {
                value.append(command.at(4).toUInt(&ok, 10));

                if(!ok) {
                    errorStream << "Cannot convert "<< command.at(4) << " to base 10!" << endl;
                    return 1;
                }
            }

            if(command.at(2)=="hex") {
                value.append(command.at(4).toUInt(&ok, 16));

                if(!ok) {
                    errorStream << "Cannot convert "<< command.at(4) << " to base 16!" << endl;
                    return 1;
                }
            }

            if(command.at(2)=="cip") {
                errorStream << "Not yet specified!" << endl;
                return 1;
            }

            pos = keys[command.at(3)];

            qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl;
            byteArray.replace(pos, 1, value);
        }
        else {
            errorStream << "Cannot find key for "<< command.at(3) << "!" << endl;
            return 1;
        }
    }


    /**
     * data
     */
    if(command.at(3)=="data") {
        if (keys.contains(command.at(3))) {
            qDebug() << "keys.contains(" << command.at(3) << ")" << endl;
        }
        else {
            errorStream << "Cannot find key for "<< command.at(3) << "!" << endl;
            return 1;
        }

        // Remove old contents
        qDebug().noquote().nospace() << "Remove " << (int) byteArray.at(keys["size"]) << " byte(s) of data" << endl;

        pos = keys["size"];
        int oldContentsSize = byteArray.at(keys["size"]);

        for (int i=0; i < oldContentsSize; i++) {
            byteArray.remove(pos, 1);
            qDebug().noquote().nospace() << "Remove " << pos << endl;
        }


        // Set size
        QString size = QString("%1").arg(command.at(4).size());

        value.append(size.toUInt(&ok, 10));

        if(!ok) {
            errorStream << "Cannot convert "<< command.at(4) << " to base 10!" << endl;
            return 1;
        }

        byteArray.replace(keys["size"], 1, value);
        qDebug().noquote().nospace() << "Set size to " << size << endl;


        // Set contents
        pos = keys[command.at(3)];

        const QChar *data = command.at(4).data();
        while (!data->isNull()) {
            qDebug() << data->toLatin1() << " (" << data->unicode() << ")";
            byteArray.insert(pos++, data->toLatin1());
            ++data;
        }

    }


    /**
     * Write file
     */

    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {

        errorStream << "Error: set_ci(" << command.join(" ") << ") can not write to file " << filePath << endl;
        return 1;
    }
    file.write(byteArray);

    file.close();

    qDebug() << "filePath: " << filePath << endl;




    return 0;
}
예제 #8
0
int udp_ping(QStringList command) {
    qDebug() << "udp_ping(" << command.join(" ") << ")" << endl;
    qDebug() << "udp_ping(" << command.join(" ") << ")" << endl;

    /**
     * Check input
     */
    QTextStream errorStream(stderr);

    if(command.size() != 3 || command.at(0)!="ping" || command.at(1)!="udp" ) {

        errorStream << "Error: udp_ping(" << command.join(" ") << ") is no valid call (ping udp <ip_address> <port> rzv|max|random|default)" << endl;
        return 1;
    }


    /**
     * <functionality>
     */


    QByteArray byteArray;

    /**
     * CIP for "rzv"
     */
    if(command.at(2)=="rzv") {
        qDebug() << "rzv" << endl;

        byteArray.append(QByteArray(42, '\0'));
     }


    /**
     * Sent via TCP
     */
    QUdpSocket *udpSocket;
    udpSocket = new QUdpSocket();
    QTextStream outStream(stdout);

    QString out;

    udpSocket->abort();
    udpSocket->connectToHost("127.0.0.1", 22366);

    qDebug() << "waitForConnected!";
    if (udpSocket->waitForConnected(5000)) {
        qDebug() << "Connected!";
    }
    else {
        errorStream << "Error: udp_ping(" << command.join(" ") << "): No connection available!" << endl;
        return 1;
    }

    qDebug() << QString("BytesWritten: %1").arg(udpSocket->write(byteArray, byteArray.length()));
    udpSocket->flush();

    int numRead = 0, numReadTotal = 0;
    char buffer[MAXMSG];

    forever {
        numRead  = udpSocket->read(buffer, MAXMSG);
        qDebug() << "read buffer: " << numRead;

        numReadTotal += numRead;
        if (numRead <= 0 && !udpSocket->waitForReadyRead(30))
            break;
    }
    qDebug() << numReadTotal << " bytes red";

    if(numReadTotal==-1) {
        errorStream << "Error: udp_ping(" << command.join(" ") << "): " << udpSocket->errorString() << endl;
        return 1;
    }
    else {
        for(int i=0; i < numReadTotal; i++) {
            qDebug() << QString("receipt[%1]: %2\n").arg(i).arg(buffer[i], 8, 2, QLatin1Char('0')) << endl;;
        }
        QByteArray receipt(buffer);


        qDebug() << "receipt.size(): " << receipt.size();

        for(int i = 0; i < receipt.size();++i) {
           qDebug() << QString("receipt[%1]: %2\n").arg(i).arg(receipt.at(i), 8, 2, QLatin1Char('0')) << endl;;
        }
        qDebug() << "buffer: " << buffer;
    }

    udpSocket->disconnectFromHost();
    udpSocket->close();

    outStream << out << endl;

    return 0;
}
예제 #9
0
int udp_broadcast(QStringList command) {
    qDebug() << "udp_broadcast(" << command.join(" ") << ")" << endl;

    qDebug() << LINE_SEP << endl;
    man("usage help");
    qDebug() << LINE_SEP << endl;

    qDebug() << LINE_SEP << endl;
    man("description help");
    qDebug() << LINE_SEP << endl;

    qDebug() << LINE_SEP << endl;
    man("help help");
    qDebug() << LINE_SEP << endl;


    /**
     * Check input
     */
    QTextStream errorStream(stderr);

    if(command.size() != 5) {

        errorStream << "Error: udp_broadcast(" << command.join(" ") << ") has no valid number of arguments" << endl;
        man("usage udp_broadcast");
        return 1;
    }


    if(command.at(0)!="broadcast") {

        errorStream << "Error: udp_broadcast(" << command.join(" ") << ") has no valid prototcol (broadcast udp <ip_address> <port> rzv|max|random|default)" << endl;
        return 1;
    }

    if(command.at(1)!="udp") {

        errorStream << "Error: udp_broadcast(" << command.join(" ") << ") has no valid prototcol (broadcast udp <ip_address> <port> rzv|max|random|default)" << endl;
        return 1;
    }

    if(! command.at(2).contains(QRegExp("^\\d\\d?\\d?.\\d\\d?\\d?.\\d\\d?\\d?.\\d\\d?\\d?$"))) {

        errorStream << "Error: udp_broadcast(" << command.join(" ") << ") has no valid IP address (broadcast udp <ip_address> <port> rzv|max|random|default)" << endl;
        return 1;
    }

    if(! command.at(3).contains(QRegExp("^\\d\\d?\\d?\\d?\\d?\\d?$"))) {

        errorStream << "Error: udp_broadcast(" << command.join(" ") << ") has no valid port number (broadcast udp <ip_address> <port> rzv|max|random|default)" << endl;
        return 1;
    }

    if(! command.at(4).contains(QRegExp("(rzv|max|random|default)"))) {

        errorStream << "Error: udp_broadcast(" << command.join(" ") << ") has no valid CIP specification (broadcast udp <ip_address> <port> rzv|max|random|default)" << endl;
        return 1;
    }


    /**
     * <functionality>
     */


    QByteArray byteArray;

    /**
     * CIP for "rzv"
     */
    if(command.at(4)=="rzv") {
        qDebug() << "rzv" << endl;

        byteArray.append(QByteArray(42, '\0'));
     }

    /**
     * CIP for "test"
     */
    if(command.at(4)=="test") {
        qDebug() << "test" << endl;

        byteArray = "Broadcast message ";
     }


    udpSocket = new QUdpSocket();

//    udpSocket->writeDatagram(byteArray, byteArray.length(),
//                             QHostAddress::Broadcast, 22366);
//    "0.0.0.0"

    udpSocket->writeDatagram(byteArray, byteArray.length(),
                             QHostAddress(command.at(2)), QString(command.at(3)).toUInt());

    return 0;
}
예제 #10
0
int offer(QStringList command) {
    qDebug() << "offer(" << command.join(" ") << ")" << endl;


    /**
     * Debug
     */
    for(int i=0;i<command.size();i++) {
        qDebug() << "command.at(" << i << ")" << command.at(i) << endl;
    }


    /**
     * Check input
     */
    QTextStream errorStream(stderr);

    if(command.size() != 3) {

        errorStream << "Error: offer(" << command.join(" ") << "): No valid number of arguments!" << endl;
        man("usage offer");
        return 1;
    }


    if(command.at(0)!="offer") {

        errorStream << "Error: offer(" << command.join(" ") << "): No valid command!" << endl;
        man("usage offer");
        return 1;
    }

    if(! command.at(2).contains(QRegExp("^(random)$"))) {

        errorStream << "Error: offer(" << command.join(" ") << "): No valid mode!" << endl;
        man("usage offer");
        return 1;
    }


    QByteArray byteArray;

    /**
     * Offer CIP for "random"
     */
    if(command.at(2)=="random") {
        qDebug() << "random" << endl;


        /*
         * Create random CIP
         */



        QByteArray randValues;
        qsrand(QTime::currentTime().msec());

        for(int i=0; i <= 1064; i++) {
            randValues.append((quint8) qFloor(qrand()/CRN_RANDOM_DIVISOR));
        }


        quint8 i = 0;
        quint8 rand;

        // Header: request (1)
        byteArray.append(randValues.at(i++));


        // Header: profile (1)
        byteArray.append(randValues.at(i++));


        // Header: version (1)
        byteArray.append(randValues.at(i++));


        // Header: channel (1)
        byteArray.append(randValues.at(i++));

        // Header: UUID (16)
        QUuid uuid;
        uuid = QUuid::createUuid();
        QByteArray uuid_arr = uuid.toRfc4122();

        for(int j=0; j<16;j++) {

            byteArray.append(uuid_arr.at(j));
        }

        // Header: Empty IP address (4) and port number (2)
        byteArray.append(QByteArray(6, '\0'));

        // Header: time (8)
        byteArray.append(QByteArray(8, '\0'));

        // Header: type (1)
        byteArray.append(randValues.at(i++));

        // Header: size (1) and data
        qDebug() << "xxxxxxxxxxxxxxx: " << i;
        rand = randValues.at(i++);
        qDebug() << "xxxxxxxxxxxxxxx: " << i;
        qDebug() << "xxxxxxxxxxxxxxx: " << rand;
        byteArray.append(rand);
        byteArray.append(QByteArray(rand, rand));

        // Contextinformation: type (1)
        byteArray.append(randValues.at(i++));

        // Contextinformation: root-CIC (2)
        byteArray.append(randValues.at(i++));
        byteArray.append(randValues.at(i++));

        // Contextinformation: size (1)
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand*2, rand));

        // Application: type (1)
        byteArray.append(randValues.at(i++));

        // Application: size (1)
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand, rand));



        /**
         * Define map with start position
         */

        QMap<QString, quint8> keys;
        quint8 pos;

        keys["request"] = 0;
        keys["profile"] = 1;
        keys["version"] = 2;
        keys["channel"] = 3;
        keys["uuid"] = 4;
        keys["ip"] = 20;
        keys["port"] = 24;
        keys["time"] = 26;
        keys["head_type"] = 34;
        keys["head_size"] = 35;

        i = byteArray.at(35) + 35;
        qDebug() << "XXXXXXXXXXXX: " << i;

        keys["ci_type"] = ++i;
        keys["content"] = ++i;
        keys["mask"] = ++i;
        keys["ci_size"] = ++i;
        keys["contents"] = ++i;



        QByteArray value;


        /*
         * Transform to Offer
         */

        // Header request -> 2
        pos = keys["request"];
        value.clear();
        value.append((quint8) 2);

        qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl;
        byteArray.replace(pos, 1, value);


        // Header channel -> 1
        pos = keys["channel"];
        value.clear();
        value.append((quint8) 1);

        qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl;
        byteArray.replace(pos, 1, value);


        // Header version -> 1
        pos = keys["version"];
        value.clear();
        value.append((quint8) 1);

        qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl;
        byteArray.replace(pos, 1, value);


        // CI type -> 1
        pos = keys["ci_type"];
        value.clear();
        value.append((quint8) 1);

        qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl;
        byteArray.replace(pos, 1, value);


        // CI root-CIC->content -> 1
        pos = keys["content"];
        value.clear();
        value.append((quint8) 1);

        qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl;
        byteArray.replace(pos, 1, value);


        // CI root-CIC->mask -> 0
        pos = keys["mask"];
        value.clear();
        value.append('\0');

        qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl;
        byteArray.replace(pos, 1, value);



    } // rand



    /**
     * Write file
     */

    QString filePath;

    filePath = CIP_ROOT;
    filePath += "/" + command.at(1);

    QFile file(filePath);

    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {

        errorStream << "Error: touch(" << command.join(" ") << ") can not write to file " << filePath << endl;
        return 1;
    }
    file.write(byteArray);

    file.close();

    qDebug() << "filePath: " << filePath << endl;


    return 0;
}