<commit_before>/****************************************************************************
**
** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QDebug>
#include <QDir>
#include <QStringList>
#include <QFile>
#include <QTextStream>
#include <QDomDocument>
#include <QDomNode>
#include <QDomNodeList>

QString makeTable(QHash<QString, QStringList> &results, QString fileName,
                  QString testName1, QString testName2)
{
    if(results[fileName+testName1].count()<2 || results[fileName+testName2].count()<2)
        return QString("No valid data
");
    int test1Total = results[fileName+testName1].at(2).toInt();
    int test2Total = results[fileName+testName2].at(2).toInt();
    int fasterTime, slowerTime;
    if(test1Total<test2Total)
    {
        fasterTime=test1Total;
        slowerTime=test2Total;
    }
    else
    {
        fasterTime=test2Total;
        slowerTime=test1Total;
    }
    bool isFirstFaster=(test1Total < test2Total ? true:false);
    QString table("

	"
        "%3	%4

median
mean
total	"
        "%5	%6	%7 is faster by %8%	"
        "

");
    return table.arg(QString(isFirstFaster?"g":"w")).arg(QString((isFirstFaster?"w":"g"))).
    arg(testName1).arg(testName2).arg(results[fileName+testName1].join("
")).
    arg(results[fileName+testName2].join("
")).arg((isFirstFaster?testName1:testName2)).
    arg(((slowerTime-fasterTime)*100)/slowerTime);
}

QString makeTableCombined(QHash<QString, QStringList> &results, QString fileName,
                  QStringList testNames1, QStringList testNames2)
{
    for(int i=0; i<testNames1.count(); i++)
        if(results[fileName+testNames1[i]].count()<2)
            return QString("No valid data
");
    int test1Total = 0;
    for(int i=0; i<testNames1.count(); i++)
        test1Total+= results[fileName+testNames1[i]].at(2).toInt();
    int test2Total = 0;
    for(int i=0; i<testNames2.count(); i++)
        test2Total+= results[fileName+testNames2[i]].at(2).toInt();
    int fasterTime, slowerTime;
    if(test1Total<test2Total)
    {
        fasterTime=test1Total;
        slowerTime=test2Total;
    }
    else
    {
        fasterTime=test2Total;
        slowerTime=test1Total;
    }
    bool isFirstFaster=(test1Total < test2Total ? true:false);
    QString table("

	"
    "%3	%4

total	"
    "%5	%6	%7 is faster by %8%"
    "

");
    return table.arg(QString(isFirstFaster?"g":"w")).arg((isFirstFaster?"w":"g")).arg(testNames1.join(" + ")).
    arg(testNames2.join(" + ")).arg(test1Total).arg(test2Total).arg((isFirstFaster?testNames1:testNames2)
    .join(" + ")).arg(((slowerTime-fasterTime)*100)/slowerTime);
}
int main(int argc, char *argv[])
{
    Q_UNUSED(argc);
    Q_UNUSED(argv);
    QString dirPath = QDir::homePath() + QDir::separator();
    QDir myDir(dirPath);
    QStringList fileList = myDir.entryList(QStringList() << "benchmark-*.xml");
    QString pageOutput;
    pageOutput = ""
    ""
    "<title>Benchmark result comparison</title>"
    ""
    ""
    "
Report generated by Benchmark Comparison Tool (part of QSparql test library)
";
    QHash<QString, QStringList> results;
    QHash<QString, QString> tracker_ver;
    QHash<QString, QString> qsparql_ver;
    QStringList testNames;
    QString pageOutput2(pageOutput);

    //lets iterate through files, read them and parse
    for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
    {
        QString filename(dirPath+fileList.at(dirIterator));
        QDomDocument doc("xmlResult");
        QFile file(filename);
        if (!file.open(QIODevice::ReadOnly))
        {
            qDebug() << "Couldn't open file "<< filename;
            pageOutput.append("Error: Couldn't open file "+filename);
        }
        else
        if (!doc.setContent(&file)) {
            file.close();
            qDebug() << "Couldn't set file content for  QDomDocument "<< filename;
            pageOutput.append("Couldn't set file content for  QDomDocument  "+filename);
        }
        else
        {
            file.close();

            QDomNode asset = doc.elementsByTagName("benchmark").at(0).firstChild();
            QDomNode assetIterator = asset.firstChild();
            QString tracker, qsparql, created;
            for(QDomNode assetIterator = asset.firstChild(); !assetIterator.isNull();
                                                assetIterator = assetIterator.nextSibling())
            {
                QString tagName = assetIterator.toElement().tagName();
                if(tagName == "tracker")
                    tracker = assetIterator.toElement().text();
                else if(tagName == "qsparql")
                    qsparql = assetIterator.toElement().text();
                else if(tagName == "created")
                    created = assetIterator.toElement().text();
            }

            //QString description = assetIterator.toElement().text();
            tracker_ver[fileList.at(dirIterator)]=tracker;
            qsparql_ver[fileList.at(dirIterator)]=qsparql;
            QDomNodeList testList = doc.elementsByTagName("benchmark").at(0).lastChild().
                                    toElement().elementsByTagName("test");
            for(int i=0; i< testList.count(); i++)
            {
                QString name = testList.at(i).toElement().attribute("name");
                if(!testNames.contains(name))
                    testNames << name;
                QDomNode median = testList.at(i).toElement().firstChild();
                QString medianValue = median.toElement().attribute("value");
                QDomNode mean = median.nextSibling();
                QString meanValue = mean.toElement().attribute("value");
                QDomNode total = mean.nextSibling();
                QString totalValue = total.toElement().attribute("value");
                QStringList runResults;
                runResults << medianValue << meanValue << totalValue;
                results[fileList.at(dirIterator)+name] = runResults;
            }
        }
    }

    //overall comparison html page
    pageOutput.append("

Test name	");
    for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
    {
        QStringList nameparts = fileList.at(dirIterator).split(".");
        pageOutput.append("" + nameparts[0] + "
" +nameparts[1] + "
"+
                          qsparql_ver[fileList.at(dirIterator)]+"
"+
                          ""+tracker_ver[fileList.at(dirIterator)]+"" +
                          "
tests comaprison	");
    }
    pageOutput.append("
\n");
    QStringList previousResult;
    for(int testIterator=0; testIterator < testNames.count(); testIterator++)
    {
        previousResult.clear();
        pageOutput.append(QString("
"+testNames[testIterator].remove(".xml")+
                          "
median
mean
total	");
        for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
        {
            pageOutput.append("");
            for(int partResultIterator=0; partResultIterator < results[fileList.at(dirIterator)+
                                            testNames[testIterator]].count(); partResultIterator++)
            {
                int currentValue=results[fileList.at(dirIterator)+testNames[testIterator]].
                                                            at(partResultIterator).toInt();
                pageOutput.append(QString("%1").arg(currentValue));
                if(previousResult.count() == results[fileList.at(dirIterator)+
                   testNames[testIterator]].count() && previousResult.count()-1 == partResultIterator)
                {
                    int previousValue=previousResult[partResultIterator].toInt();
                    int diff = (previousValue?(((previousValue-currentValue)*100)/previousValue):100);
                    pageOutput.append(QString("  %1%").arg(diff*-1).
                                                                        arg(diff<0?"1":"2"));
                }
                pageOutput.append("
");
            }
            pageOutput.append("	\n");
            previousResult = results[fileList.at(dirIterator)+testNames[testIterator]];
        }
        pageOutput.append("
\n\n");
    }
    pageOutput.append("

");
    pageOutput.append("");

    //between-tests-comparison html page
    pageOutput2.append("
In-between tests comaprison
Back to the mainpage

");
    for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
    {
        QStringList nameparts = fileList.at(dirIterator).split(".");
        pageOutput2.append("
" +
        "

"+ nameparts[0]+ "." + nameparts[1] +"
" + ""+
        qsparql_ver[fileList.at(dirIterator)]+"
"+
        ""+tracker_ver[fileList.at(dirIterator)]+"

" +
        makeTable(results, fileList.at(dirIterator), "read-music-Async-fin", "read-music-Sync-fin")+
        makeTable(results, fileList.at(dirIterator), "read-music-Async-read", "read-music-Sync-read")+
        makeTable(results, fileList.at(dirIterator), "read-music-Async-ForwardOnly-fin", "read-music-Async-fin")+
        makeTable(results, fileList.at(dirIterator), "read-music-Async-ForwardOnly-read", "read-music-Async-read")+
        makeTableCombined(results, fileList.at(dirIterator), QStringList() << "read-music-Async-fin"
                            << "read-music-Async-read", QStringList() << "read-music-Sync-fin" << "read-music-Sync-read")+
        makeTableCombined(results, fileList.at(dirIterator), QStringList() << "read-music-Async-fin"
                            << "read-music-Async-read", QStringList() << "read-music-Async-ForwardOnly-fin"
                            << "read-music-Async-ForwardOnly-read"));
    }
    pageOutput2.append("");

    QFile data(dirPath+"index.html");
    if (data.open(QFile::WriteOnly | QFile::Truncate)) {
        QTextStream out(&data);
        out << pageOutput;
        qDebug() << "Report saved in " << dirPath;
        data.close();
    }
    else
        qDebug() << "Couldn't save report in " << dirPath << "Check writing permissions!";
    data.setFileName(dirPath+"tests-comparison.html");
    if (data.open(QFile::WriteOnly | QFile::Truncate)) {
        QTextStream out(&data);
        out << pageOutput2;
        qDebug() << "Report saved in " << dirPath;
    }
    else
        qDebug() << "Couldn't save report in " << dirPath << "Check writing permissions!";
    return 0;
}<commit_msg>Fix for crash when generating comparison report with old xml format<commit_after>/****************************************************************************
**
** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QDebug>
#include <QDir>
#include <QStringList>
#include <QFile>
#include <QTextStream>
#include <QDomDocument>
#include <QDomNode>
#include <QDomNodeList>

QString makeTable(QHash<QString, QStringList> &results, QString fileName,
                  QString testName1, QString testName2)
{
    if(results[fileName+testName1].count()<2 || results[fileName+testName2].count()<2)
        return QString("No valid data
");
    int test1Total = results[fileName+testName1].at(2).toInt();
    int test2Total = results[fileName+testName2].at(2).toInt();
    int fasterTime, slowerTime;
    if(test1Total<test2Total)
    {
        fasterTime=test1Total;
        slowerTime=test2Total;
    }
    else
    {
        fasterTime=test2Total;
        slowerTime=test1Total;
    }
    bool isFirstFaster=(test1Total < test2Total ? true:false);
    QString table("

	"
        "%3	%4

median
mean
total	"
        "%5	%6	%7 is faster by %8%	"
        "

");
    return table.arg(QString(isFirstFaster?"g":"w")).arg(QString((isFirstFaster?"w":"g"))).
    arg(testName1).arg(testName2).arg(results[fileName+testName1].join("
")).
    arg(results[fileName+testName2].join("
")).arg((isFirstFaster?testName1:testName2)).
    arg(((slowerTime-fasterTime)*100)/slowerTime);
}

QString makeTableCombined(QHash<QString, QStringList> &results, QString fileName,
                  QStringList testNames1, QStringList testNames2)
{
    for(int i=0; i<testNames1.count(); i++)
        if(results[fileName+testNames1[i]].count()<2 || results[fileName+testNames2[i]].count()<2)
            return QString("No valid data
");
    int test1Total = 0;
    for(int i=0; i<testNames1.count(); i++)
        test1Total+= results[fileName+testNames1[i]].at(2).toInt();
    int test2Total = 0;
    for(int i=0; i<testNames2.count(); i++)
        test2Total+= results[fileName+testNames2[i]].at(2).toInt();
    int fasterTime, slowerTime;
    if(test1Total<test2Total)
    {
        fasterTime=test1Total;
        slowerTime=test2Total;
    }
    else
    {
        fasterTime=test2Total;
        slowerTime=test1Total;
    }
    bool isFirstFaster=(test1Total < test2Total ? true:false);
    QString table("

	"
    "%3	%4

total	"
    "%5	%6	%7 is faster by %8%"
    "

");
    return table.arg(QString(isFirstFaster?"g":"w")).arg((isFirstFaster?"w":"g")).arg(testNames1.join(" + ")).
    arg(testNames2.join(" + ")).arg(test1Total).arg(test2Total).arg((isFirstFaster?testNames1:testNames2)
    .join(" + ")).arg(((slowerTime-fasterTime)*100)/slowerTime);
}
int main(int argc, char *argv[])
{
    Q_UNUSED(argc);
    Q_UNUSED(argv);
    QString dirPath = QDir::homePath() + QDir::separator();
    QDir myDir(dirPath);
    QStringList fileList = myDir.entryList(QStringList() << "benchmark-*.xml");
    QString pageOutput;
    pageOutput = ""
    ""
    "<title>Benchmark result comparison</title>"
    ""
    ""
    "
Report generated by Benchmark Comparison Tool (part of QSparql test library)
";
    QHash<QString, QStringList> results;
    QHash<QString, QString> tracker_ver;
    QHash<QString, QString> qsparql_ver;
    QStringList testNames;
    QString pageOutput2(pageOutput);

    //lets iterate through files, read them and parse
    for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
    {
        QString filename(dirPath+fileList.at(dirIterator));
        QDomDocument doc("xmlResult");
        QFile file(filename);
        if (!file.open(QIODevice::ReadOnly))
        {
            qDebug() << "Couldn't open file "<< filename;
            pageOutput.append("Error: Couldn't open file "+filename);
        }
        else
        if (!doc.setContent(&file)) {
            file.close();
            qDebug() << "Couldn't set file content for  QDomDocument "<< filename;
            pageOutput.append("Couldn't set file content for  QDomDocument  "+filename);
        }
        else
        {
            file.close();

            QDomNode asset = doc.elementsByTagName("benchmark").at(0).firstChild();
            QDomNode assetIterator = asset.firstChild();
            QString tracker, qsparql, created;
            for(QDomNode assetIterator = asset.firstChild(); !assetIterator.isNull();
                                                assetIterator = assetIterator.nextSibling())
            {
                QString tagName = assetIterator.toElement().tagName();
                if(tagName == "tracker")
                    tracker = assetIterator.toElement().text();
                else if(tagName == "qsparql")
                    qsparql = assetIterator.toElement().text();
                else if(tagName == "created")
                    created = assetIterator.toElement().text();
            }

            //QString description = assetIterator.toElement().text();
            tracker_ver[fileList.at(dirIterator)]=tracker;
            qsparql_ver[fileList.at(dirIterator)]=qsparql;
            QDomNodeList testList = doc.elementsByTagName("benchmark").at(0).lastChild().
                                    toElement().elementsByTagName("test");
            for(int i=0; i< testList.count(); i++)
            {
                QString name = testList.at(i).toElement().attribute("name");
                if(!testNames.contains(name))
                    testNames << name;
                QDomNode median = testList.at(i).toElement().firstChild();
                QString medianValue = median.toElement().attribute("value");
                QDomNode mean = median.nextSibling();
                QString meanValue = mean.toElement().attribute("value");
                QDomNode total = mean.nextSibling();
                QString totalValue = total.toElement().attribute("value");
                QStringList runResults;
                runResults << medianValue << meanValue << totalValue;
                results[fileList.at(dirIterator)+name] = runResults;
            }
        }
    }

    //overall comparison html page
    pageOutput.append("

Test name	");
    for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
    {
        QStringList nameparts = fileList.at(dirIterator).split(".");
        pageOutput.append("" + nameparts[0] + "
" +nameparts[1] + "
"+
                          qsparql_ver[fileList.at(dirIterator)]+"
"+
                          ""+tracker_ver[fileList.at(dirIterator)]+"" +
                          "
tests comaprison	");
    }
    pageOutput.append("
\n");
    QStringList previousResult;
    for(int testIterator=0; testIterator < testNames.count(); testIterator++)
    {
        previousResult.clear();
        pageOutput.append(QString("
"+testNames[testIterator].remove(".xml")+
                          "
median
mean
total	");
        for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
        {
            pageOutput.append("");
            for(int partResultIterator=0; partResultIterator < results[fileList.at(dirIterator)+
                                            testNames[testIterator]].count(); partResultIterator++)
            {
                int currentValue=results[fileList.at(dirIterator)+testNames[testIterator]].
                                                            at(partResultIterator).toInt();
                pageOutput.append(QString("%1").arg(currentValue));
                if(previousResult.count() == results[fileList.at(dirIterator)+
                   testNames[testIterator]].count() && previousResult.count()-1 == partResultIterator)
                {
                    int previousValue=previousResult[partResultIterator].toInt();
                    int diff = (previousValue?(((previousValue-currentValue)*100)/previousValue):100);
                    pageOutput.append(QString("  %1%").arg(diff*-1).
                                                                        arg(diff<0?"1":"2"));
                }
                pageOutput.append("
");
            }
            pageOutput.append("	\n");
            previousResult = results[fileList.at(dirIterator)+testNames[testIterator]];
        }
        pageOutput.append("
\n\n");
    }
    pageOutput.append("

");
    pageOutput.append("");

    //between-tests-comparison html page
    pageOutput2.append("
In-between tests comaprison
Back to the mainpage

");
    for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
    {
        QStringList nameparts = fileList.at(dirIterator).split(".");
        pageOutput2.append("
" +
        "

"+ nameparts[0]+ "." + nameparts[1] +"
" + ""+
        qsparql_ver[fileList.at(dirIterator)]+"
"+
        ""+tracker_ver[fileList.at(dirIterator)]+"

" +
        makeTable(results, fileList.at(dirIterator), "read-music-Async-fin", "read-music-Sync-fin")+
        makeTable(results, fileList.at(dirIterator), "read-music-Async-read", "read-music-Sync-read")+
        makeTable(results, fileList.at(dirIterator), "read-music-Async-ForwardOnly-fin", "read-music-Async-fin")+
        makeTable(results, fileList.at(dirIterator), "read-music-Async-ForwardOnly-read", "read-music-Async-read")+
        makeTableCombined(results, fileList.at(dirIterator), QStringList() << "read-music-Async-fin"
                            << "read-music-Async-read", QStringList() << "read-music-Sync-fin" << "read-music-Sync-read")+
        makeTableCombined(results, fileList.at(dirIterator), QStringList() << "read-music-Async-fin"
                            << "read-music-Async-read", QStringList() << "read-music-Async-ForwardOnly-fin"
                            << "read-music-Async-ForwardOnly-read"));
    }
    pageOutput2.append("");

    QFile data(dirPath+"index.html");
    if (data.open(QFile::WriteOnly | QFile::Truncate)) {
        QTextStream out(&data);
        out << pageOutput;
        qDebug() << "Report saved in " << dirPath;
        data.close();
    }
    else
        qDebug() << "Couldn't save report in " << dirPath << "Check writing permissions!";
    data.setFileName(dirPath+"tests-comparison.html");
    if (data.open(QFile::WriteOnly | QFile::Truncate)) {
        QTextStream out(&data);
        out << pageOutput2;
        qDebug() << "Report saved in " << dirPath;
    }
    else
        qDebug() << "Couldn't save report in " << dirPath << "Check writing permissions!";
    return 0;
}<|endoftext|>


<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (c) FFLAS-FFPACK
* Written by Clement Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the  GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
* ========LICENCE========
*/
#define  __FFLASFFPACK_FORCE_SEQ

#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>

#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"
#include "fflas-ffpack/utils/args-parser.h"

using namespace std;

int main(int argc, char** argv) {

	size_t iter = 1;
	size_t    n    = 500;
	std::string file = "";
  	static int variant =0;
	size_t b = 150;
	Argument as[] = {
		{ 'b', "-b B", "Set the bitsize of the random characteristic.",  TYPE_INT , &b },
		{ 'n', "-n N", "Set the dimension of the matrix.",               TYPE_INT , &n },
		{ 'i', "-i R", "Set number of repetitions.",                     TYPE_INT , &iter },
		{ 'f', "-f FILE", "Set the input file (empty for random).",  TYPE_STR , &file },
		{ 'a', "-a algorithm", "Set the algorithmic variant", TYPE_INT, &variant },

		END_OF_ARGUMENTS
	};

  FFLAS::parseArguments(argc,argv,as);
  typedef Givaro::ZRing<Givaro::Integer> Field;
  FFPACK::FFPACK_CHARPOLY_TAG CT;
  switch (variant){
      case 0: CT = FFPACK::FfpackAuto; break;
      case 1: CT = FFPACK::FfpackLUK; break;
      case 2: CT = FFPACK::FfpackDanilevski; break;
      case 3: CT = FFPACK::FfpackArithProg; break;
      case 4: CT = FFPACK::FfpackKG; break;
      case 5: CT = FFPACK::FfpackKGFast; break;
      case 6: CT = FFPACK::FfpackHybrid; break;
      case 7: CT = FFPACK::FfpackKGFastG; break;
      default: CT = FFPACK::FfpackAuto; break;
  }
  typedef Field::Element Element;

  Field F;
  FFLAS::Timer chrono;
  double time=0.0;

  Element *A;
  size_t bs=1;
  size_t size=b;
  for (size_t i=0;i<iter;++i){

	  if (!file.empty()){
		  A = read_field (F, file.c_str(), &n, &n);
	  }
	  else{
		  A = FFLAS::fflas_new<Element>(n*n);
		  Field::RandIter G(F,size);
		  for (size_t j=0; j< (size_t)n*n; ++j)
			  G.random(*(A+j));
	  }

	  typedef Givaro::Poly1Dom<Field> PolRing;
	  PolRing R(F);
	  PolRing::Element cpol;
	  chrono.clear();
	  chrono.start();
	  FFPACK::CharPoly (R, cpol, n, A, n, CT);
	  chrono.stop();

	  time+=chrono.usertime();

	  bs = FFLAS::bitsize (F,n,n,A,n);
	  FFLAS::fflas_delete( A);
  }

	// -----------
	// Standard output for benchmark - Alexis Breust 2014/11/14
  std::cerr << "n: "<<n<<" bitsize: "<<bs<<" Time: " << time / double(iter)
        << " Gflops: " << (2.*double(n)/1000.*double(n)/1000.*double(n)/1000.0) / time * double(iter);
  FFLAS::writeCommandString(std::cerr, as) << std::endl;

  return 0;
}

<commit_msg>smaller default bench<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (c) FFLAS-FFPACK
* Written by Clement Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the  GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
* ========LICENCE========
*/
#define  __FFLASFFPACK_FORCE_SEQ

#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>

#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"
#include "fflas-ffpack/utils/args-parser.h"

using namespace std;

int main(int argc, char** argv) {

	size_t iter = 1;
	size_t    n    = 100;
	std::string file = "";
  	static int variant =0;
	size_t b = 150;
	Argument as[] = {
		{ 'b', "-b B", "Set the bitsize of the random characteristic.",  TYPE_INT , &b },
		{ 'n', "-n N", "Set the dimension of the matrix.",               TYPE_INT , &n },
		{ 'i', "-i R", "Set number of repetitions.",                     TYPE_INT , &iter },
		{ 'f', "-f FILE", "Set the input file (empty for random).",  TYPE_STR , &file },
		{ 'a', "-a algorithm", "Set the algorithmic variant", TYPE_INT, &variant },

		END_OF_ARGUMENTS
	};

  FFLAS::parseArguments(argc,argv,as);
  typedef Givaro::ZRing<Givaro::Integer> Field;
  FFPACK::FFPACK_CHARPOLY_TAG CT;
  switch (variant){
      case 0: CT = FFPACK::FfpackAuto; break;
      case 1: CT = FFPACK::FfpackLUK; break;
      case 2: CT = FFPACK::FfpackDanilevski; break;
      case 3: CT = FFPACK::FfpackArithProg; break;
      case 4: CT = FFPACK::FfpackKG; break;
      case 5: CT = FFPACK::FfpackKGFast; break;
      case 6: CT = FFPACK::FfpackHybrid; break;
      case 7: CT = FFPACK::FfpackKGFastG; break;
      default: CT = FFPACK::FfpackAuto; break;
  }
  typedef Field::Element Element;

  Field F;
  FFLAS::Timer chrono;
  double time=0.0;

  Element *A;
  size_t bs=1;
  size_t size=b;
  for (size_t i=0;i<iter;++i){

	  if (!file.empty()){
		  A = read_field (F, file.c_str(), &n, &n);
	  }
	  else{
		  A = FFLAS::fflas_new<Element>(n*n);
		  Field::RandIter G(F,size);
		  for (size_t j=0; j< (size_t)n*n; ++j)
			  G.random(*(A+j));
	  }

	  typedef Givaro::Poly1Dom<Field> PolRing;
	  PolRing R(F);
	  PolRing::Element cpol;
	  chrono.clear();
	  chrono.start();
	  FFPACK::CharPoly (R, cpol, n, A, n, CT);
	  chrono.stop();

	  time+=chrono.usertime();

	  bs = FFLAS::bitsize (F,n,n,A,n);
	  FFLAS::fflas_delete( A);
  }

	// -----------
	// Standard output for benchmark - Alexis Breust 2014/11/14
  std::cerr << "n: "<<n<<" bitsize: "<<bs<<" Time: " << time / double(iter)
        << " Gflops: " << (2.*double(n)/1000.*double(n)/1000.*double(n)/1000.0) / time * double(iter);
  FFLAS::writeCommandString(std::cerr, as) << std::endl;

  return 0;
}

<|endoftext|>


<commit_before>#include <iostream>                                         /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h>                                          /* Standard input/output definitions */
#include <stdint.h>                                         /* Standard input/output definitions */
#include <stdlib.h>                                         /* defines several general purpose functions */
#include <unistd.h>                                         /* UNIX standard function definitions */
#include <fcntl.h>                                          /* File control definitions */
#include <ctype.h>                                          /* isxxx() */
#include <ros/ros.h>                                        /* ROS */
#include <geometry_msgs/Twist.h>                            /* ROS Twist message */
#include <base_controller/encoders.h>                       /* Custom message /encoders */
#include <base_controller/md49data.h>                       /* Custom message /encoders */

#include <serialport/serialport.h>
#define REPLY_SIZE 18
#define TIMEOUT 1000

int32_t EncoderL;                                           /* stores encoder value left read from md49 */
int32_t EncoderR;                                           /* stores encoder value right read from md49 */
char reply[REPLY_SIZE];
unsigned char speed_l=128, speed_r=128;                     /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128;           /* speed to set for MD49 */
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4;                                    /* Base width in meters */

//unsigned char serialBuffer[18];                             /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);

using namespace std;
cereal::CerealPort device;
base_controller::encoders encoders;
base_controller::md49data md49data;

void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){

        if (vel_cmd.linear.x>0){
            speed_l = 255;
            speed_r = 255;
        }
        if (vel_cmd.linear.x<0){
            speed_l = 0;
            speed_r = 0;
        }
        if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
            speed_l = 128;
            speed_r = 128;
        }
        if (vel_cmd.angular.z>0){
            speed_l = 0;
            speed_r = 255;
        }
        if (vel_cmd.angular.z<0){
            speed_l = 255;
            speed_r = 0;
        }
        if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
            //set_MD49_speed(speed_l,speed_r);
            last_speed_l=speed_l;
            last_speed_r=speed_r;
        }

    /*
        //ANFANG Alternative
        if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
        else if(vel_cmd.linear.x == 0){
            // turning
            vr = vel_cmd.angular.z * base_width / 2.0;
            vl = (-1) * vr;
        }
        else if(vel_cmd.angular.z == 0){
            // forward / backward
            vl = vr = vel_cmd.linear.x;
        }
        else{
            // moving doing arcs
            vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
            if (vl > max_vl) {vl=max_vl;}
            if (vl < min_vl) {vl=min_vl;}
            vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
            if (vr > max_vr) {vr=max_vr;}
            if (vr < min_vr) {vr=min_vr;}
        }
        //ENDE Alternative
    */
}

int main( int argc, char* argv[] ){

    ros::init(argc, argv, "base_controller" );
    ros::NodeHandle n;
    ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
    ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
    ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10);

    // Init node
    // *********
    ros::Rate loop_rate(10);
    ROS_INFO("base_controller running...");
    ROS_INFO("=============================");
    ROS_INFO("Subscribing to topic /cmd_vel");
    ROS_INFO("Publishing to topic /encoders");
    ROS_INFO("Publishing to topic /md49data");

    // Open serial port
    // ****************
    try{ device.open("/dev/ttyAMA0", 38400); }
    catch(cereal::Exception& e)
    {
      ROS_FATAL("Failed to open the serial port!!!");
      ROS_BREAK();
    }
    ROS_INFO("The serial port is opened.");

    while(n.ok())
    {
        // Read encoder and other data from MD49
        // (data is read from serial_controller_node
        //  and avaiable through md49_data.txt)
        // *****************************************
        read_MD49_Data();

        // Publish encoder values to topic /encoders (custom message)
        // **********************************************************
        encoders.encoder_l=EncoderL;
        encoders.encoder_r=EncoderR;
        encoders_pub.publish(encoders);

        // Publish MD49 data to topic /md49data (custom message)
        // *****************************************************
        md49data.speed_l = reply[8];
        md49data.speed_r = reply[9];
        md49data.volt = reply[10];
        md49data.current_l = reply[11];
        md49data.current_r = reply[12];
        md49data.error = reply[13];
        md49data.acceleration = reply[14];
        md49data.mode = reply[15];
        md49data.regulator = reply[16];
        md49data.timeout = reply[17];
        md49data_pub.publish(md49data);

        // ****
        ros::spinOnce();
        loop_rate.sleep();

    }// end.mainloop

    return 1;
} // end.main

void read_MD49_Data (void){

    // Send 'R' over the serial port
    device.write("R");
    // Get the reply, the last value is the timeout in ms
    try{ device.read(reply, REPLY_SIZE, TIMEOUT); }
    catch(cereal::TimeoutException& e)
    {
      ROS_ERROR("Timeout on serialport! No data read");
    }
    //ROS_INFO("Received MD49 data");

    // Put toghether new encodervalues
    // *******************************
    EncoderL = reply[0] << 24;                        // Put together first encoder value
    EncoderL |= (reply[1] << 16);
    EncoderL |= (reply[2] << 8);
    EncoderL |= (reply[3]);
    EncoderR = reply[4] << 24;                        // Put together second encoder value
    EncoderR |= (reply[5] << 16);
    EncoderR |= (reply[6] << 8);
    EncoderR |= (reply[7]);

/*
    // Output MD49 data on screen
    // **************************
    printf("\033[2J");                                      //  clear the screen
    printf("\033[H");                                       //  position cursor at top-left corner
    printf ("MD49-Data read from AVR-Master: \n");
    printf("========================================\n");
    printf("Encoder1 Byte1: %i ",reply[0]);
    printf("Byte2: %i ",reply[1]);
    printf("Byte3: % i ",reply[2]);
    printf("Byte4: %i \n",reply[3]);
    printf("Encoder2 Byte1: %i ",reply[4]);
    printf("Byte2: %i ",reply[5]);
    printf("Byte3: %i ",reply[6]);
    printf("Byte4: %i \n",reply[7]);
    printf("EncoderL: %i ",EncoderL);
    printf("EncoderR: %i \n",EncoderR);
    printf("========================================\n");
    printf("Speed1: %i ",reply[8]);
    printf("Speed2: %i \n",reply[9]);
    printf("Volts: %i \n",reply[10]);
    printf("Current1: %i ",reply[11]);
    printf("Current2: %i \n",reply[12]);
    printf("Error: %i \n",reply[13]);
    printf("Acceleration: %i \n",reply[14]);
    printf("Mode: %i \n",reply[15]);
    printf("Regulator: %i \n",reply[16]);
    printf("Timeout: %i \n",reply[17]);
*/

}

void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){

/*
    char buffer[33];
    ofstream myfile;
    myfile.open ("md49_commands.txt");
    //myfile << "Writing this to a file.\n";
    if (speed_l==0){
        myfile << "000";
        myfile << "\n";
    }
    else if (speed_l<10){
        myfile << "00";
        myfile << itoa(speed_l,buffer,10);
        myfile << "\n";
    }
    else if (speed_l<100){
        myfile << "0";
        myfile << itoa(speed_l,buffer,10);
        myfile << "\n";
    }
    else{
        myfile << itoa(speed_l,buffer,10);
        myfile << "\n";
    }

    if (speed_r==0){
        myfile << "000";
        myfile << "\n";
    }
    else if (speed_r<10){
        myfile << "00";
        myfile << itoa(speed_r,buffer,10);
        myfile << "\n";
    }
    else if (speed_r<100){
        myfile << "0";
        myfile << itoa(speed_r,buffer,10);
        myfile << "\n";
    }
    else{
        myfile << itoa(speed_r,buffer,10);
        myfile << "\n";
    }
    myfile.close();
*/

}

char* itoa(int value, char* result, int base) {
        // check that the base if valid
        if (base < 2 || base > 36) { *result = '\0'; return result; }

        char* ptr = result, *ptr1 = result, tmp_char;
        int tmp_value;

        do {
            tmp_value = value;
            value /= base;
            *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
        } while ( value );

        // Apply negative sign
        if (tmp_value < 0) *ptr++ = '-';
        *ptr-- = '\0';
        while(ptr1 < ptr) {
            tmp_char = *ptr;
            *ptr--= *ptr1;
            *ptr1++ = tmp_char;
        }
        return result;
    }
<commit_msg>Update code<commit_after>#include <iostream>                                         /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h>                                          /* Standard input/output definitions */
#include <stdint.h>                                         /* Standard input/output definitions */
#include <stdlib.h>                                         /* defines several general purpose functions */
#include <unistd.h>                                         /* UNIX standard function definitions */
#include <fcntl.h>                                          /* File control definitions */
#include <ctype.h>                                          /* isxxx() */
#include <ros/ros.h>                                        /* ROS */
#include <geometry_msgs/Twist.h>                            /* ROS Twist message */
#include <base_controller/encoders.h>                       /* Custom message /encoders */
#include <base_controller/md49data.h>                       /* Custom message /encoders */

#include <serialport/serialport.h>
#define REPLY_SIZE 18
#define TIMEOUT 1000

int32_t EncoderL;                                           /* stores encoder value left read from md49 */
int32_t EncoderR;                                           /* stores encoder value right read from md49 */
char reply[REPLY_SIZE];
unsigned char speed_l=128, speed_r=128;                     /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128;           /* speed to set for MD49 */
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4;                                    /* Base width in meters */

//unsigned char serialBuffer[18];                             /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);

using namespace std;
cereal::CerealPort device;
base_controller::encoders encoders;
base_controller::md49data md49data;

void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){

        if (vel_cmd.linear.x>0){
            speed_l = 255;
            speed_r = 255;
        }
        if (vel_cmd.linear.x<0){
            speed_l = 0;
            speed_r = 0;
        }
        if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
            speed_l = 128;
            speed_r = 128;
        }
        if (vel_cmd.angular.z>0){
            speed_l = 0;
            speed_r = 255;
        }
        if (vel_cmd.angular.z<0){
            speed_l = 255;
            speed_r = 0;
        }
        //if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
            //set_MD49_speed(speed_l,speed_r);
            //last_speed_l=speed_l;
            //last_speed_r=speed_r;
        //}

    /*
        //ANFANG Alternative
        if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
        else if(vel_cmd.linear.x == 0){
            // turning
            vr = vel_cmd.angular.z * base_width / 2.0;
            vl = (-1) * vr;
        }
        else if(vel_cmd.angular.z == 0){
            // forward / backward
            vl = vr = vel_cmd.linear.x;
        }
        else{
            // moving doing arcs
            vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
            if (vl > max_vl) {vl=max_vl;}
            if (vl < min_vl) {vl=min_vl;}
            vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
            if (vr > max_vr) {vr=max_vr;}
            if (vr < min_vr) {vr=min_vr;}
        }
        //ENDE Alternative
    */
}

int main( int argc, char* argv[] ){

    ros::init(argc, argv, "base_controller" );
    ros::NodeHandle n;
    ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
    ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
    ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10);

    // Init node
    // *********
    ros::Rate loop_rate(10);
    ROS_INFO("base_controller running...");
    ROS_INFO("=============================");
    ROS_INFO("Subscribing to topic /cmd_vel");
    ROS_INFO("Publishing to topic /encoders");
    ROS_INFO("Publishing to topic /md49data");

    // Open serial port
    // ****************
    try{ device.open("/dev/ttyAMA0", 38400); }
    catch(cereal::Exception& e)
    {
      ROS_FATAL("Failed to open the serial port!!!");
      ROS_BREAK();
    }
    ROS_INFO("The serial port is opened.");

    while(n.ok())
    {
        // Read encoder and other data from MD49
        // (data is read from serial_controller_node
        //  and avaiable through md49_data.txt)
        // *****************************************
        read_MD49_Data();

        // Publish encoder values to topic /encoders (custom message)
        // **********************************************************
        encoders.encoder_l=EncoderL;
        encoders.encoder_r=EncoderR;
        encoders_pub.publish(encoders);

        // Publish MD49 data to topic /md49data (custom message)
        // *****************************************************
        md49data.speed_l = reply[8];
        md49data.speed_r = reply[9];
        md49data.volt = reply[10];
        md49data.current_l = reply[11];
        md49data.current_r = reply[12];
        md49data.error = reply[13];
        md49data.acceleration = reply[14];
        md49data.mode = reply[15];
        md49data.regulator = reply[16];
        md49data.timeout = reply[17];
        md49data_pub.publish(md49data);

        // ****
        ros::spinOnce();
        loop_rate.sleep();

    }// end.mainloop

    return 1;
} // end.main

void read_MD49_Data (void){

    // Send 'R' over the serial port
    device.write("R");
    // Get the reply, the last value is the timeout in ms
    try{ device.read(reply, REPLY_SIZE, TIMEOUT); }
    catch(cereal::TimeoutException& e)
    {
      ROS_ERROR("Timeout on serialport! No data read");
    }
    //ROS_INFO("Received MD49 data");

    // Put toghether new encodervalues
    // *******************************
    EncoderL = reply[0] << 24;                        // Put together first encoder value
    EncoderL |= (reply[1] << 16);
    EncoderL |= (reply[2] << 8);
    EncoderL |= (reply[3]);
    EncoderR = reply[4] << 24;                        // Put together second encoder value
    EncoderR |= (reply[5] << 16);
    EncoderR |= (reply[6] << 8);
    EncoderR |= (reply[7]);

/*
    // Output MD49 data on screen
    // **************************
    printf("\033[2J");                                      //  clear the screen
    printf("\033[H");                                       //  position cursor at top-left corner
    printf ("MD49-Data read from AVR-Master: \n");
    printf("========================================\n");
    printf("Encoder1 Byte1: %i ",reply[0]);
    printf("Byte2: %i ",reply[1]);
    printf("Byte3: % i ",reply[2]);
    printf("Byte4: %i \n",reply[3]);
    printf("Encoder2 Byte1: %i ",reply[4]);
    printf("Byte2: %i ",reply[5]);
    printf("Byte3: %i ",reply[6]);
    printf("Byte4: %i \n",reply[7]);
    printf("EncoderL: %i ",EncoderL);
    printf("EncoderR: %i \n",EncoderR);
    printf("========================================\n");
    printf("Speed1: %i ",reply[8]);
    printf("Speed2: %i \n",reply[9]);
    printf("Volts: %i \n",reply[10]);
    printf("Current1: %i ",reply[11]);
    printf("Current2: %i \n",reply[12]);
    printf("Error: %i \n",reply[13]);
    printf("Acceleration: %i \n",reply[14]);
    printf("Mode: %i \n",reply[15]);
    printf("Regulator: %i \n",reply[16]);
    printf("Timeout: %i \n",reply[17]);
*/

}

void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){

    const char* command;
    //command=("Xs%i%i",speed_l,speed_r);
    device.write("Xs",2);
    device.write(command,1);
    //device.write(speed_r,1);

}

char* itoa(int value, char* result, int base) {
        // check that the base if valid
        if (base < 2 || base > 36) { *result = '\0'; return result; }

        char* ptr = result, *ptr1 = result, tmp_char;
        int tmp_value;

        do {
            tmp_value = value;
            value /= base;
            *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
        } while ( value );

        // Apply negative sign
        if (tmp_value < 0) *ptr++ = '-';
        *ptr-- = '\0';
        while(ptr1 < ptr) {
            tmp_char = *ptr;
            *ptr--= *ptr1;
            *ptr1++ = tmp_char;
        }
        return result;
    }
<|endoftext|>


<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_
#define CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_

#include <vector>

#include "clustering/administration/issues/local.hpp"
#include "concurrency/watchable.hpp"
#include "containers/clone_ptr.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/serialize_macros.hpp"

// All local issue types are declared here to avoid circular dependencies
class log_write_issue_t : public local_issue_t {
public:
    log_write_issue_t();
    explicit log_write_issue_t(const std::string &_message);

    const datum_string_t &get_name() const { return log_write_issue_type; }
    bool is_critical() const { return false; }

    std::string message;
private:
    ql::datum_t build_info(const metadata_t &metadata) const;
    datum_string_t build_description(const ql::datum_t &info) const;

    static const datum_string_t log_write_issue_type;
    static const uuid_u base_issue_id;
};

RDB_DECLARE_SERIALIZABLE(log_write_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(log_write_issue_t);

class outdated_index_issue_t : public local_issue_t {
public:
    typedef std::map<namespace_id_t, std::set<std::string> > index_map_t;

    outdated_index_issue_t();
    explicit outdated_index_issue_t(const index_map_t &indexes);
    const datum_string_t &get_name() const { return outdated_index_issue_type; }
    bool is_critical() const { return false; }

    index_map_t indexes;
private:
    ql::datum_t build_info(const metadata_t &metadata) const;
    datum_string_t build_description(const ql::datum_t &info) const;

    static const datum_string_t outdated_index_issue_type;
    static const uuid_u base_issue_id;
};

RDB_DECLARE_SERIALIZABLE(outdated_index_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(outdated_index_issue_t);

class server_down_issue_t : public local_issue_t {
public:
    server_down_issue_t();
    explicit server_down_issue_t(const machine_id_t &_down_server_id);

    const datum_string_t &get_name() const { return server_down_issue_type; }
    bool is_critical() const { return true; }

    machine_id_t down_server_id;
private:
    ql::datum_t build_info(const metadata_t &metadata) const;
    datum_string_t build_description(const ql::datum_t &info) const;

    static const datum_string_t server_down_issue_type;
    static const issue_id_t base_issue_id;
};

RDB_DECLARE_SERIALIZABLE(server_down_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(server_down_issue_t);

class server_ghost_issue_t : public local_issue_t {
public:
    server_ghost_issue_t();
    explicit server_ghost_issue_t(const machine_id_t &_ghost_server_id);

    const datum_string_t &get_name() const { return server_ghost_issue_type; }
    bool is_critical() const { return false; }

    machine_id_t ghost_server_id;
private:
    ql::datum_t build_info(const metadata_t &metadata) const;
    datum_string_t build_description(const ql::datum_t &info) const;

    static const datum_string_t server_ghost_issue_type;
    static const issue_id_t base_issue_id;
};

RDB_DECLARE_SERIALIZABLE(server_ghost_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(server_ghost_issue_t);

// Every local issue type should have the following:
//  - an entry in the local_issues_t
//  - a local_issue_t::make_*_issue function for the local issue type
struct local_issues_t {
    std::vector<log_write_issue_t> log_write_issues;
    std::vector<server_down_issue_t> server_down_issues;
    std::vector<server_ghost_issue_t> server_ghost_issues;
    std::vector<outdated_index_issue_t> outdated_index_issues;
};

RDB_DECLARE_SERIALIZABLE(local_issues_t);
RDB_DECLARE_EQUALITY_COMPARABLE(local_issues_t);

class local_issue_aggregator_t : public home_thread_mixin_t {
public:
    local_issue_aggregator_t();

    clone_ptr_t<watchable_t<local_issues_t> > get_issues_watchable();

private:
    friend class local_issue_tracker_t;

    watchable_variable_t<local_issues_t> issues_watchable;

    DISABLE_COPYING(local_issue_aggregator_t);
};

#endif /* CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_ */
<commit_msg>updating comments<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_
#define CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_

#include <vector>

#include "clustering/administration/issues/local.hpp"
#include "concurrency/watchable.hpp"
#include "containers/clone_ptr.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/serialize_macros.hpp"

// All local issue types are declared here to avoid circular dependencies
// This is because local issue trackers require definitions for the metadata,
// but the metadata requires definitions of all local issue types.
//
// Every local issue type should have the following:
//  - an issue_t subclass defined in this file
//  - an entry in the local_issues_t for that issue_t subclass
//  - handling in remote_issue_tracker_t
//  - a combine() method in the issue tracker
class log_write_issue_t : public local_issue_t {
public:
    log_write_issue_t();
    explicit log_write_issue_t(const std::string &_message);

    const datum_string_t &get_name() const { return log_write_issue_type; }
    bool is_critical() const { return false; }

    std::string message;
private:
    ql::datum_t build_info(const metadata_t &metadata) const;
    datum_string_t build_description(const ql::datum_t &info) const;

    static const datum_string_t log_write_issue_type;
    static const uuid_u base_issue_id;
};

RDB_DECLARE_SERIALIZABLE(log_write_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(log_write_issue_t);

class outdated_index_issue_t : public local_issue_t {
public:
    typedef std::map<namespace_id_t, std::set<std::string> > index_map_t;

    outdated_index_issue_t();
    explicit outdated_index_issue_t(const index_map_t &indexes);
    const datum_string_t &get_name() const { return outdated_index_issue_type; }
    bool is_critical() const { return false; }

    index_map_t indexes;
private:
    ql::datum_t build_info(const metadata_t &metadata) const;
    datum_string_t build_description(const ql::datum_t &info) const;

    static const datum_string_t outdated_index_issue_type;
    static const uuid_u base_issue_id;
};

RDB_DECLARE_SERIALIZABLE(outdated_index_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(outdated_index_issue_t);

class server_down_issue_t : public local_issue_t {
public:
    server_down_issue_t();
    explicit server_down_issue_t(const machine_id_t &_down_server_id);

    const datum_string_t &get_name() const { return server_down_issue_type; }
    bool is_critical() const { return true; }

    machine_id_t down_server_id;
private:
    ql::datum_t build_info(const metadata_t &metadata) const;
    datum_string_t build_description(const ql::datum_t &info) const;

    static const datum_string_t server_down_issue_type;
    static const issue_id_t base_issue_id;
};

RDB_DECLARE_SERIALIZABLE(server_down_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(server_down_issue_t);

class server_ghost_issue_t : public local_issue_t {
public:
    server_ghost_issue_t();
    explicit server_ghost_issue_t(const machine_id_t &_ghost_server_id);

    const datum_string_t &get_name() const { return server_ghost_issue_type; }
    bool is_critical() const { return false; }

    machine_id_t ghost_server_id;
private:
    ql::datum_t build_info(const metadata_t &metadata) const;
    datum_string_t build_description(const ql::datum_t &info) const;

    static const datum_string_t server_ghost_issue_type;
    static const issue_id_t base_issue_id;
};

RDB_DECLARE_SERIALIZABLE(server_ghost_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(server_ghost_issue_t);

struct local_issues_t {
    std::vector<log_write_issue_t> log_write_issues;
    std::vector<server_down_issue_t> server_down_issues;
    std::vector<server_ghost_issue_t> server_ghost_issues;
    std::vector<outdated_index_issue_t> outdated_index_issues;
};

RDB_DECLARE_SERIALIZABLE(local_issues_t);
RDB_DECLARE_EQUALITY_COMPARABLE(local_issues_t);

class local_issue_aggregator_t : public home_thread_mixin_t {
public:
    local_issue_aggregator_t();

    clone_ptr_t<watchable_t<local_issues_t> > get_issues_watchable();

private:
    friend class local_issue_tracker_t;

    watchable_variable_t<local_issues_t> issues_watchable;

    DISABLE_COPYING(local_issue_aggregator_t);
};

#endif /* CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_ */
<|endoftext|>


<commit_before>// Copyright (C) 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "fake_downloader.h"

#include <cassert>
#include <fstream>
#include <map>
#include <string>
#include <utility>

namespace i18n {
namespace addressinput {

// static
const char FakeDownloader::kFakeDataUrl[] = "test:///";

namespace {

// The name of the test data file.
const char kDataFileName[] = TEST_DATA_DIR "/countryinfo.txt";

// The number of characters in the fake data URL prefix.
const size_t kFakeDataUrlLength = sizeof FakeDownloader::kFakeDataUrl - 1;

std::string CCKey(const std::string& key) {
  const char kSplitChar = '/';

  std::string::size_type split = key.find(kSplitChar);
  if (split == std::string::npos) {
    return key;
  }
  split = key.find(kSplitChar, split + 1);
  if (split == std::string::npos) {
    return key;
  }

  return key.substr(0, split);
}

std::map<std::string, std::string> InitData() {
  std::map<std::string, std::string> data;
  std::ifstream file(kDataFileName);
  assert(file.is_open());

  std::string line;
  while (file.good()) {
    std::getline(file, line);

    std::string::size_type divider = line.find('=');
    if (divider == std::string::npos) {
      continue;
    }

    std::string key = line.substr(0, divider);
    std::string cc_key = CCKey(key);
    std::string value = line.substr(divider + 1);
    std::string url = FakeDownloader::kFakeDataUrl + cc_key;
    std::map<std::string, std::string>::iterator data_it = data.find(url);
    if (data_it != data.end()) {
      data_it->second += ", \"" + key + "\": " + value;
    } else {
      data.insert(std::make_pair(url, "{\"" + key + "\": " + value));
    }
  }
  file.close();

  for (std::map<std::string, std::string>::iterator data_it = data.begin();
       data_it != data.end(); ++data_it) {
    data_it->second += "}";
  }

  return data;
}

const std::map<std::string, std::string>& GetData() {
  static const std::map<std::string, std::string> kData(InitData());
  return kData;
}

}  // namespace

FakeDownloader::FakeDownloader() {}

FakeDownloader::~FakeDownloader() {}

void FakeDownloader::Download(const std::string& url,
                              scoped_ptr<Callback> downloaded) {
  std::map<std::string, std::string>::const_iterator data_it =
      GetData().find(url);
  bool success = data_it != GetData().end();
  std::string data = success ? data_it->second : std::string();
  if (!success &&
      url.compare(
          0, kFakeDataUrlLength, kFakeDataUrl, kFakeDataUrlLength) == 0) {
    // URLs that start with
    // "https://i18napis.appspot.com/ssl-aggregate-address/" prefix, but do not
    // have associated data will always return "{}" with status code 200.
    // FakeDownloader imitates this behavior for URLs that start with "test:///"
    // prefix.
    success = true;
    data = "{}";
  }
  (*downloaded)(success, url, make_scoped_ptr(new std::string(data)));
}

}  // namespace addressinput
}  // namespace i18n
<commit_msg>Include language-specific rules in fake downloader for libaddressinput.<commit_after>// Copyright (C) 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "fake_downloader.h"

#include <cassert>
#include <fstream>
#include <map>
#include <string>
#include <utility>

namespace i18n {
namespace addressinput {

// static
const char FakeDownloader::kFakeDataUrl[] = "test:///";

namespace {

// The name of the test data file.
const char kDataFileName[] = TEST_DATA_DIR "/countryinfo.txt";

// The number of characters in the fake data URL prefix.
const size_t kFakeDataUrlLength = sizeof FakeDownloader::kFakeDataUrl - 1;

// Returns "data/HK" for "data/HK--en".
std::string RemoveLanguageCode(const std::string& key) {
  std::string::size_type language_code_pos = key.find("--");
  return language_code_pos == std::string::npos
      ? key
      : key.substr(0, language_code_pos);
}

std::string CCKey(const std::string& key) {
  const char kSplitChar = '/';

  std::string::size_type split = key.find(kSplitChar);
  if (split == std::string::npos) {
    return key;
  }
  split = key.find(kSplitChar, split + 1);
  if (split == std::string::npos) {
    return key;
  }

  return key.substr(0, split);
}

std::map<std::string, std::string> InitData() {
  std::map<std::string, std::string> data;
  std::ifstream file(kDataFileName);
  assert(file.is_open());

  std::string line;
  while (file.good()) {
    std::getline(file, line);

    std::string::size_type divider = line.find('=');
    if (divider == std::string::npos) {
      continue;
    }

    std::string key = line.substr(0, divider);
    std::string cc_key = RemoveLanguageCode(CCKey(key));
    std::string value = line.substr(divider + 1);
    std::string url = FakeDownloader::kFakeDataUrl + cc_key;
    std::map<std::string, std::string>::iterator data_it = data.find(url);
    if (data_it != data.end()) {
      data_it->second += ", \"" + key + "\": " + value;
    } else {
      data.insert(std::make_pair(url, "{\"" + key + "\": " + value));
    }
  }
  file.close();

  for (std::map<std::string, std::string>::iterator data_it = data.begin();
       data_it != data.end(); ++data_it) {
    data_it->second += "}";
  }

  return data;
}

const std::map<std::string, std::string>& GetData() {
  static const std::map<std::string, std::string> kData(InitData());
  return kData;
}

}  // namespace

FakeDownloader::FakeDownloader() {}

FakeDownloader::~FakeDownloader() {}

void FakeDownloader::Download(const std::string& url,
                              scoped_ptr<Callback> downloaded) {
  std::map<std::string, std::string>::const_iterator data_it =
      GetData().find(url);
  bool success = data_it != GetData().end();
  std::string data = success ? data_it->second : std::string();
  if (!success &&
      url.compare(
          0, kFakeDataUrlLength, kFakeDataUrl, kFakeDataUrlLength) == 0) {
    // URLs that start with
    // "https://i18napis.appspot.com/ssl-aggregate-address/" prefix, but do not
    // have associated data will always return "{}" with status code 200.
    // FakeDownloader imitates this behavior for URLs that start with "test:///"
    // prefix.
    success = true;
    data = "{}";
  }
  (*downloaded)(success, url, make_scoped_ptr(new std::string(data)));
}

}  // namespace addressinput
}  // namespace i18n
<|endoftext|>


<commit_before>#include <iostream>                                         /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h>                                          /* Standard input/output definitions */
#include <stdint.h>                                         /* Standard input/output definitions */
#include <stdlib.h>                                         /* defines several general purpose functions */
#include <unistd.h>                                         /* UNIX standard function definitions */
#include <fcntl.h>                                          /* File control definitions */
#include <errno.h>                                          /* Error number definitions */
#include <termios.h>                                        /* POSIX terminal control definitions */
#include <ctype.h>                                        /* isxxx() */

const char* serialport="/dev/ttyAMA0";                      /* defines used serialport */
int serialport_bps=B38400;                                  /* defines baudrate od serialport */
int32_t EncoderL;                                           /* stores encoder value left read from md49 */
int32_t EncoderR;                                           /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128;                               /* speed to set for MD49 */

int filedesc;                                               // File descriptor of serial port we will talk to
int fd;                                                     /* serial port file descriptor */
unsigned char serialBuffer[16];                             /* Serial buffer to store uart data */
struct termios orig;                                        // Port options

using namespace std;

int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);
unsigned char md49_data[18];

int main( int argc, char* argv[] ){

    // Open serial port
    // ****************
    filedesc = openSerialPort("/dev/ttyAMA0", serialport_bps);
    if (filedesc == -1) exit(1);
    usleep(10000);                                      // Sleep for UART to power up and set options

    while( 1 )
    {

        // Read encoder and other data from MD49
        // and put into sqlite db
        // *************************************
        read_MD49_Data();
        usleep(200000);

        // Read commands from sqlite db and
        // set speed and other commands to MD49
        // ************************************
        string line;
        ifstream myfile ("md49_commands.txt");
        if (myfile.is_open())
        {
            int i=0;
            while ( getline (myfile,line) )
            {
                //cout << line << '\n';
                char data[10];
                std::copy(line.begin(), line.end(), data);
                md49_data[i]=atoi(data);
                i =i++;
            }
            myfile.close();
            speed_l=md49_data[0];
            speed_r=md49_data[1];
        }
        else cout << "Unable to open file";
        set_MD49_speed(speed_l, speed_r);
        usleep(200000);

    }// end.mainloop

    return 1;
} // end.main

int openSerialPort(const char * device, int bps){
   struct termios neu;
   char buf[128];

   //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
   fd = open(device, O_RDWR | O_NOCTTY);

   if (fd == -1)
   {
      sprintf(buf, "openSerialPort %s error", device);
      perror(buf);
   }
   else
   {
      tcgetattr(fd, &orig); 						/* save current serial settings */
      tcgetattr(fd, &neu);
      cfmakeraw(&neu);
      //fprintf(stderr, "speed=%d\n", bps);
      cfsetispeed(&neu, bps);
      cfsetospeed(&neu, bps);
      tcflush(fd, TCIFLUSH);
      tcsetattr(fd, TCSANOW, &neu); 				/* set new serial settings */
      fcntl (fd, F_SETFL, O_RDWR);
   }
   return fd;
}

void writeBytes(int descriptor, int count) {
    if ((write(descriptor, serialBuffer, count)) == -1) {	// Send data out
        perror("Error writing");
        close(descriptor);				// Close port if there is an error
        exit(1);
    }

}

void readBytes(int descriptor, int count) {
    if (read(descriptor, serialBuffer, count) == -1) {	// Read back data into buf[]
        perror("Error reading ");
        close(descriptor);				// Close port if there is an error
        exit(1);
    }
}

void read_MD49_Data (void){
    serialBuffer[0] = 82;							// 82=R Steuerbyte um alle Daten vom MD49 zu lesen
    writeBytes(fd, 1);
    //Daten lesen und in Array schreiben
    readBytes(fd, 18);

    ofstream myfile;
    myfile.open ("md49_data.txt");
    //myfile << "Writing this to a file.\n";
    char buffer[33];

    EncoderL = serialBuffer[0] << 24;                        // Put together first encoder value
    EncoderL |= (serialBuffer[1] << 16);
    EncoderL |= (serialBuffer[2] << 8);
    EncoderL |= (serialBuffer[3]);
    EncoderR = serialBuffer[4] << 24;                        // Put together second encoder value
    EncoderR |= (serialBuffer[5] << 16);
    EncoderR |= (serialBuffer[6] << 8);
    EncoderR |= (serialBuffer[7]);

    printf("\033[2J");        /*  clear the screen  */
    printf("\033[H");         /*  position cursor at top-left corner */
    printf ("MD49-Data read from AVR-Master: \n");
    printf("====================================================== \n");
    printf("Encoder1 Byte1: %i ",serialBuffer[0]);
    if (serialBuffer[0]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[0],buffer,10);
    }
    myfile << "\n";
    printf("Byte2: %i ",serialBuffer[1]);
    if (serialBuffer[1]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[1],buffer,10);
    }
    myfile << "\n";
    printf("Byte3: % i ",serialBuffer[2]);
    if (serialBuffer[2]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[2],buffer,10);
    }
    myfile << "\n";
    printf("Byte4: %i \n",serialBuffer[3]);
    if (serialBuffer[3]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[3],buffer,10);
    }
    myfile << "\n";
    printf("Encoder2 Byte1: %i ",serialBuffer[4]);
    if (serialBuffer[4]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[4],buffer,10);
    }
    myfile << "\n";
    printf("Byte2: %i ",serialBuffer[5]);
    if (serialBuffer[5]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[5],buffer,10);
    }
    myfile << "\n";
    printf("Byte3: %i ",serialBuffer[6]);
    if (serialBuffer[6]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[6],buffer,10);
    }
    myfile << "\n";
    printf("Byte4: %i \n",serialBuffer[7]);
    if (serialBuffer[7]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[7],buffer,10);
    }
    myfile << "\n";
    printf("EncoderL: %i ",EncoderL);
   // myfile <<  itoa(EncoderL,buffer,10);
    //myfile << "\n";
    printf("EncoderR: %i \n",EncoderR);
    //myfile <<  itoa(EncoderR,buffer,10);
    //myfile << "\n";
    printf("====================================================== \n");
    printf("Speed1: %i ",serialBuffer[8]);
    if (serialBuffer[8]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[8],buffer,10);
    }
    myfile << "\n";
    printf("Speed2: %i \n",serialBuffer[9]);
    if (serialBuffer[9]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[9],buffer,10);
    }
    myfile << "\n";
    printf("Volts: %i \n",serialBuffer[10]);
    if (serialBuffer[10]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[10],buffer,10);
    }
    myfile << "\n";
    printf("Current1: %i ",serialBuffer[11]);
    if (serialBuffer[11]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[11],buffer,10);
    }
    myfile << "\n";
    printf("Current2: %i \n",serialBuffer[12]);
    if (serialBuffer[12]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[12],buffer,10);
    }
    myfile << "\n";
    printf("Error: %i \n",serialBuffer[13]);
    if (serialBuffer[13]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[13],buffer,10);
    }
    myfile << "\n";
    printf("Acceleration: %i \n",serialBuffer[14]);
    if (serialBuffer[14]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[14],buffer,10);
    }
    myfile << "\n";
    printf("Mode: %i \n",serialBuffer[15]);
    if (serialBuffer[15]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[15],buffer,10);
    }
    myfile << "\n";
    printf("Regulator: %i \n",serialBuffer[16]);
    if (serialBuffer[16]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[16],buffer,10);
    }
    myfile << "\n";
    printf("Timeout: %i \n",serialBuffer[17]);
    if (serialBuffer[17]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[17],buffer,10);
    }
    myfile << "\n";
    printf("speed_l = %i \n",speed_l);
    printf("speed_r = %i \n",speed_r);

    myfile.close();
}

void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
    serialBuffer[0] = 88;					// 88 =X Steuerbyte um Commands an MD49 zu senden
    serialBuffer[1] = 115;					// 115=s Steuerbyte setSpeed
    serialBuffer[2] = speed_l;				// speed1
    serialBuffer[3] = speed_r;				// speed2
    writeBytes(fd, 4);
}

char* itoa(int value, char* result, int base) {
        // check that the base if valid
        if (base < 2 || base > 36) { *result = '\0'; return result; }

        char* ptr = result, *ptr1 = result, tmp_char;
        int tmp_value;

        do {
            tmp_value = value;
            value /= base;
            *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
        } while ( value );

        // Apply negative sign
        if (tmp_value < 0) *ptr++ = '-';
        *ptr-- = '\0';
        while(ptr1 < ptr) {
            tmp_char = *ptr;
            *ptr--= *ptr1;
            *ptr1++ = tmp_char;
        }
        return result;
    }
<commit_msg>Update code<commit_after>#include <iostream>                                         /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h>                                          /* Standard input/output definitions */
#include <stdint.h>                                         /* Standard input/output definitions */
#include <stdlib.h>                                         /* defines several general purpose functions */
#include <unistd.h>                                         /* UNIX standard function definitions */
#include <fcntl.h>                                          /* File control definitions */
#include <errno.h>                                          /* Error number definitions */
#include <termios.h>                                        /* POSIX terminal control definitions */
#include <ctype.h>                                        /* isxxx() */

const char* serialport="/dev/ttyAMA0";                      /* defines used serialport */
int serialport_bps=B38400;                                  /* defines baudrate od serialport */
int32_t EncoderL;                                           /* stores encoder value left read from md49 */
int32_t EncoderR;                                           /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128;                               /* speed to set for MD49 */

int filedesc;                                               // File descriptor of serial port we will talk to
int fd;                                                     /* serial port file descriptor */
unsigned char serialBuffer[16];                             /* Serial buffer to store uart data */
struct termios orig;                                        // Port options

using namespace std;

int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);
unsigned char md49_data[18];

int main( int argc, char* argv[] ){

    // Open serial port
    // ****************
    filedesc = openSerialPort("/dev/ttyAMA0", serialport_bps);
    if (filedesc == -1) exit(1);
    usleep(10000);                                      // Sleep for UART to power up and set options

    while( 1 )
    {

        // Read encoder and other data from MD49
        // and put into sqlite db
        // *************************************
        read_MD49_Data();
        usleep(200000);

        // Read commands from sqlite db and
        // set speed and other commands to MD49
        // ************************************
        string line;
        ifstream myfile ("md49_commands.txt");
        if (myfile.is_open())
        {
            int i=0;
            while ( getline (myfile,line) )
            {
                //cout << line << '\n';
                char data[10];
                std::copy(line.begin(), line.end(), data);
                md49_data[i]=atoi(data);
                i =i++;
            }
            myfile.close();
            speed_l=md49_data[0];
            speed_r=md49_data[1];
        }
        else cout << "Unable to open file";
        set_MD49_speed(speed_l, speed_r);
        usleep(200000);

    }// end.mainloop

    return 1;
} // end.main

int openSerialPort(const char * device, int bps){
   struct termios neu;
   char buf[128];

   //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
   fd = open(device, O_RDWR | O_NOCTTY);

   if (fd == -1)
   {
      sprintf(buf, "openSerialPort %s error", device);
      perror(buf);
   }
   else
   {
      tcgetattr(fd, &orig); 						/* save current serial settings */
      tcgetattr(fd, &neu);
      cfmakeraw(&neu);
      //fprintf(stderr, "speed=%d\n", bps);
      cfsetispeed(&neu, bps);
      cfsetospeed(&neu, bps);
      tcflush(fd, TCIFLUSH);
      tcsetattr(fd, TCSANOW, &neu); 				/* set new serial settings */
      fcntl (fd, F_SETFL, O_RDWR);
   }
   return fd;
}

void writeBytes(int descriptor, int count) {
    if ((write(descriptor, serialBuffer, count)) == -1) {	// Send data out
        perror("Error writing");
        close(descriptor);				// Close port if there is an error
        exit(1);
    }

}

void readBytes(int descriptor, int count) {
    if (read(descriptor, serialBuffer, count) == -1) {	// Read back data into buf[]
        perror("Error reading ");
        close(descriptor);				// Close port if there is an error
        exit(1);
    }
}

void read_MD49_Data (void){
    serialBuffer[0] = 82;							// 82=R Steuerbyte um alle Daten vom MD49 zu lesen
    writeBytes(fd, 1);
    //Daten lesen und in Array schreiben
    readBytes(fd, 18);

    ofstream myfile;
    myfile.open ("md49_data.txt");
    //myfile << "Writing this to a file.\n";
    char buffer[33];

    EncoderL = serialBuffer[0] << 24;                        // Put together first encoder value
    EncoderL |= (serialBuffer[1] << 16);
    EncoderL |= (serialBuffer[2] << 8);
    EncoderL |= (serialBuffer[3]);
    EncoderR = serialBuffer[4] << 24;                        // Put together second encoder value
    EncoderR |= (serialBuffer[5] << 16);
    EncoderR |= (serialBuffer[6] << 8);
    EncoderR |= (serialBuffer[7]);

    printf("\033[2J");        /*  clear the screen  */
    printf("\033[H");         /*  position cursor at top-left corner */
    printf ("MD49-Data read from AVR-Master: \n");
    printf("====================================================== \n");
    printf("Encoder1 Byte1: %i ",serialBuffer[0]);
    if (serialBuffer[0]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[0],buffer,10);
    }
    myfile << "\n";
    printf("Byte2: %i ",serialBuffer[1]);
    if (serialBuffer[1]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[1],buffer,10);
    }
    myfile << "\n";
    printf("Byte3: % i ",serialBuffer[2]);
    if (serialBuffer[2]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[2],buffer,10);
    }
    myfile << "\n";
    printf("Byte4: %i \n",serialBuffer[3]);
    if (serialBuffer[3]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[3],buffer,10);
    }
    myfile << "\n";
    printf("Encoder2 Byte1: %i ",serialBuffer[4]);
    if (serialBuffer[4]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[4],buffer,10);
    }
    myfile << "\n";
    printf("Byte2: %i ",serialBuffer[5]);
    if (serialBuffer[5]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[5],buffer,10);
    }
    myfile << "\n";
    printf("Byte3: %i ",serialBuffer[6]);
    if (serialBuffer[6]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[6],buffer,10);
    }
    myfile << "\n";
    printf("Byte4: %i \n",serialBuffer[7]);
    if (serialBuffer[7]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[7],buffer,10);
    }
    myfile << "\n";
    printf("EncoderL: %i ",EncoderL);
   // myfile <<  itoa(EncoderL,buffer,10);
    //myfile << "\n";
    printf("EncoderR: %i \n",EncoderR);
    //myfile <<  itoa(EncoderR,buffer,10);
    //myfile << "\n";
    printf("====================================================== \n");
    printf("Speed1: %i ",serialBuffer[8]);
    if (serialBuffer[8]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[8],buffer,10);
    }
    myfile << "\n";
    printf("Speed2: %i \n",serialBuffer[9]);
    if (serialBuffer[9]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[9],buffer,10);
    }
    myfile << "\n";
    printf("Volts: %i \n",serialBuffer[10]);
    if (serialBuffer[10]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[10],buffer,10);
    }
    myfile << "\n";
    printf("Current1: %i ",serialBuffer[11]);
    if (serialBuffer[11]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[11],buffer,10);
    }
    myfile << "\n";
    printf("Current2: %i \n",serialBuffer[12]);
    if (serialBuffer[12]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[12],buffer,10);
    }
    myfile << "\n";
    printf("Error: %i \n",serialBuffer[13]);
    if (serialBuffer[13]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[13],buffer,10);
    }
    myfile << "\n";
    printf("Acceleration: %i \n",serialBuffer[14]);
    if (serialBuffer[14]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[14],buffer,10);
    }
    myfile << "\n";
    printf("Mode: %i \n",serialBuffer[15]);
    if (serialBuffer[15]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[15],buffer,10);
    }
    myfile << "\n";
    printf("Regulator: %i \n",serialBuffer[16]);
    if (serialBuffer[16]==0){
        myfile << "000";
    }
    else{
        if (serialBuffer[16]<10){
            myfile << "00";
            myfile << itoa(serialBuffer[16],buffer,10);
        }
        else{
            myfile << itoa(serialBuffer[16],buffer,10);
        }
    }
    myfile << "\n";
    printf("Timeout: %i \n",serialBuffer[17]);
    if (serialBuffer[17]==0){
        myfile << "000";
    }
    else{
        myfile << itoa(serialBuffer[17],buffer,10);
    }
    myfile << "\n";
    printf("speed_l = %i \n",speed_l);
    printf("speed_r = %i \n",speed_r);

    myfile.close();
}

void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
    serialBuffer[0] = 88;					// 88 =X Steuerbyte um Commands an MD49 zu senden
    serialBuffer[1] = 115;					// 115=s Steuerbyte setSpeed
    serialBuffer[2] = speed_l;				// speed1
    serialBuffer[3] = speed_r;				// speed2
    writeBytes(fd, 4);
}

char* itoa(int value, char* result, int base) {
        // check that the base if valid
        if (base < 2 || base > 36) { *result = '\0'; return result; }

        char* ptr = result, *ptr1 = result, tmp_char;
        int tmp_value;

        do {
            tmp_value = value;
            value /= base;
            *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
        } while ( value );

        // Apply negative sign
        if (tmp_value < 0) *ptr++ = '-';
        *ptr-- = '\0';
        while(ptr1 < ptr) {
            tmp_char = *ptr;
            *ptr--= *ptr1;
            *ptr1++ = tmp_char;
        }
        return result;
    }
<|endoftext|>