<commit_before>#include "mainview.h"
#include "ui_mainview.h"

#include "mibittip.h"
#include "mibitdialog.h"

#include <QDebug>
#include <QTimer>

mainView::mainView(QWidget *parent)
    : QWidget(parent), ui(new Ui::mainView)
{
    ui->setupUi(this);

    tip1 = new MibitTip(this, ui->dtedit, "tip.svg",QPixmap("important.png") );
    tip2 = new MibitTip(this, ui->edit1, "tip.svg", QPixmap("important.png") );
    tip3 = new MibitTip(this, ui->btnTest3, "tip.svg", QPixmap("important.png"), tpAbove );

    dialog1 = new MibitDialog(this,"Welcome to mibitWidgets Demo!","dialog-theme.svg",QPixmap("face-smile.png"), atSlideDown );
    dialog1->setSize(200,100);

    connect(ui->btnTest1, SIGNAL(clicked()), SLOT(showTip1()));
    connect(ui->btnTest2, SIGNAL(clicked()), SLOT(showTip2()));
    connect(ui->btnTest3, SIGNAL(clicked()), SLOT(showTip3()));

    connect(ui->btnDialog2, SIGNAL(clicked()), SLOT(showDialog2()));

    QTimer::singleShot(500,this,SLOT(showDialog1()));

}

mainView::~mainView()
{
    delete ui;
}

void mainView::showTip1()
{
    tip1->showTip("This is a demo for the mibitTip class.. The tip slides down below its partner control.");
}

void mainView::showTip2()
{
    tip2->showTip("This is a demo for the mibitTip class.. Just more text to display.");
}

void mainView::showTip3()
{
    tip3->showTip("This is a demo for the mibitTip class.. We also can draw it above the control, sliding up..");
}

void mainView::showDialog1()
{
    dialog1->showDialog();
}

void mainView::showDialog2()
{
    dialog1->showDialog("Dialog with a slide down animation!", atSlideDown);
}
<commit_msg>Fixing broken build due to modifing code location<commit_after>#include "mainview.h"
#include "ui_mainview.h"

#include "../mibittip.h"
#include "../mibitdialog.h"

#include <QDebug>
#include <QTimer>

mainView::mainView(QWidget *parent)
    : QWidget(parent), ui(new Ui::mainView)
{
    ui->setupUi(this);

    tip1 = new MibitTip(this, ui->dtedit, "tip.svg",QPixmap("important.png") );
    tip2 = new MibitTip(this, ui->edit1, "tip.svg", QPixmap("important.png") );
    tip3 = new MibitTip(this, ui->btnTest3, "tip.svg", QPixmap("important.png"), tpAbove );

    dialog1 = new MibitDialog(this,"Welcome to mibitWidgets Demo!","dialog-theme.svg",QPixmap("face-smile.png"), atSlideDown );
    dialog1->setSize(200,100);

    connect(ui->btnTest1, SIGNAL(clicked()), SLOT(showTip1()));
    connect(ui->btnTest2, SIGNAL(clicked()), SLOT(showTip2()));
    connect(ui->btnTest3, SIGNAL(clicked()), SLOT(showTip3()));

    connect(ui->btnDialog2, SIGNAL(clicked()), SLOT(showDialog2()));

    QTimer::singleShot(500,this,SLOT(showDialog1()));

}

mainView::~mainView()
{
    delete ui;
}

void mainView::showTip1()
{
    tip1->showTip("This is a demo for the mibitTip class.. The tip slides down below its partner control.");
}

void mainView::showTip2()
{
    tip2->showTip("This is a demo for the mibitTip class.. Just more text to display.");
}

void mainView::showTip3()
{
    tip3->showTip("This is a demo for the mibitTip class.. We also can draw it above the control, sliding up..");
}

void mainView::showDialog1()
{
    dialog1->showDialog();
}

void mainView::showDialog2()
{
    dialog1->showDialog("Dialog with a slide down animation!", atSlideDown);
}
<|endoftext|>


<commit_before>#ifndef GLOBAL_H_INCLUDED
#define GLOBAL_H_INCLUDED

// C++11 Standard.
#include <string>
#include <sstream>
#include <utility>
#include <type_traits> /// for is_class, ...
using namespace std;

///
/// GLOBAL_DEBUG
///

namespace wiz{
    #define COL_BASED
    #define ROW_BASED

	#define WIZ_IN const
	#define IN
	#define OUT
	#define INOUT

	#define AND &&
	#define OR ||
	#define NOT !
	#define EQUAL ==

	/*
    template <class T>
    inline T max( const T& t1, const T& t2 )
    {
        if( t2 < t1 ) { return t1; }
        return t2;
    }

    template <class T>
    inline T min( const T& t1, const T& t2 )
    {
        if( t1 < t2 ) { return t1; }
        return t2;
    }
	*/
    ///

    template <class T>
    class STD_SWAP
    {
    public:
        void operator()( T& t1, T& t2 )
        {
            std::swap( t1, t2 ); /// if c++11, maybe move...or make Move
        }
    };
    template <class T>
    class NORMAL_SWAP
    {
    public:
        void operator()( T& t1, T& t2 )
        {
            T temp = t1;
            t1 = t2;
            t2 = temp;
        }
    };
    template <class T>
    class HAS_SWAP_METHOD
    {
    public:
        void operator()( T& t1, T& t2 )
        {
            t1.swap( t2 );
        }
    };
    template <class T>
    class WIZ_SWAP
    {
    public:
        void operator()( T& t1, T& t2 )
        {
            std::swap( t1, t2 );
        }
    };
	template < class T, class SWAP=STD_SWAP<T> >
	inline void Swap( T& t1, T& t2 )
	{
	    SWAP()( t1, t2 );
	}

    /// TO DO
    /// MOVE, NO_MOVE
    /// ( T& t1, T& t2 )
    /// t1 = t2; // NO_MOVE
    /// t1 = move( t2 ); // MOVE

	template <class T>
	class ASC {
	public:
		bool operator() (const T& t1, const T& t2) const  { return t1 < t2; }
	};
	template <class T>
	class DSC // DESC
	{
	public:
		bool operator() (const T& t1, const T& t2) const { return t1 > t2; }
	};
	template <class T>
	class EQ { // EE -> EQ!
	public:
		bool operator() (const T& t1, const T& t2) const { return t1 == t2; }
	};
    /// TO DO
    /// ASC_EE, DSC_EE, NOT_EE, EE_SAME_VALUE, NOT_EE_SAME_VALUE , chk red-black tree!!
    template <class T>
	class ASC_EE {
	public:
		bool operator() (const T& t1, const T& t2) const { return t1 <= t2; }
	};
	template <class T>
	class DSC_EE {
	public:
		bool operator() (const T& t1, const T& t2) const { return t1 >= t2; }
	};
	template <class T>
	class NOT_EE {
	public:
		bool operator() (const T& t1, const T& t2) const { return t1 != t2; }
	};
    template <class T>
	class EE_SAME_VALUE {
	public:
		bool operator() (const T& t1, const T& t2) const { return t1.isSameValue( t2 ); }
	};
    template <class T>
	class NOT_EE_SAME_VALUE { /// chk..
	public:
		bool operator() (const T& t1, const T& t2) const { return !t1.isSameValue( t2 ); }
	};

    template <class T> /// T is pointer type..
	class PASC {
	public:
		bool operator() (const T t1, const T t2) const  { return *t1 < *t2; }
	};
    template <class T> /// T is pointer type..
    class PDSC // PDESC
    {
    public:
        bool operator() ( const T t1, const T t2 ) const
        {
            return *t1 > *t2;
        }
    };
    template <class T> /// T is pointer type..
	class PEE {
	public:
		bool operator() (const T t1, const T t2) const { return *t1 == *t2; }
	};

    /// TO DO
    /// PASC_PEE, PDSC_PEE, PNOT_EE, PEE_SAME_VALUE, PNOT_EE_SAME_VALUE
    /// LEFT_HAS_SMALL_VALUE, LEFT_HAS_LARGE_VALUE, PLEFT_HAS_SMALL_VALUE, PLEFT_HAS_LARGE_VALUE
	template <typename T> /// T <- char, int, long, long long...
	string toStr(const T x, const int base); /// chk!!

	template <class T, class COMP = ASC<T>, class COMP2 = ASC<int>, class EE = EQ<T> > /// 쒖꽌 諛붽씀湲 - 2015.07.18
	class WrapForInfinity
	{
		enum Op{ MIF = 0, GR = 1, IF = 2 };
		COMP comp;
		COMP2 comp2;
		EE ee;
		Op op; // Option
	private:
		explicit WrapForInfinity(const T& val, const Op& op) : val(val), op(op) { }
	public:
		explicit WrapForInfinity(const T& val = T()) : val(val), op(GR) { }
	public:
		T val;
		bool operator>(const WrapForInfinity<T,COMP,COMP2,EE>& wfi)const
		{
		    return wfi < (*this);
		}
		bool operator<(const WrapForInfinity<T,COMP,COMP2,EE>& wfi)const
		{
			if (GR == this->op&& GR == wfi.op)
			{
				return comp(this->val, wfi.val);
			}
			else
			{
				return comp2( this->op, wfi.op ); /// chk...
			}
		}
		bool operator==(const WrapForInfinity<T,COMP,COMP2,EE>& wfi)const
		{
		    if( wfi.op == IF && this->op == IF ) { return true; }
		    if( wfi.op == MIF && this->op == MIF ) { return true; }
			return (ee(wfi.val, this->val) && wfi.op == this->op);
		}
		bool operator!=( const WrapForInfinity<T,COMP,COMP2,EE>& wfi)const
		{
		    return !( *this == wfi );
		}
		bool operator<=(const WrapForInfinity<T,COMP,COMP2,EE>& wfi)const
		{
			return *this < wfi ||
				*this == wfi;
		}
		bool operator>=(const WrapForInfinity <T,COMP, COMP2, EE>& wfi)const
		{
			return wfi <= *this;
		}
		WrapForInfinity<T> operator+(const WrapForInfinity<T>& other)const
		{
			if (other.op == this->op) {
				return WrapForInfinity<T>(this->val + other.val, this->op);
			}
			else if (this->op == MIF && other.op == GR) {
				return WrapForInfinity<T>::GetMinusInfinity();
			}
			else if (this->op == IF && other.op == GR) {
				return WrapForInfinity<T>::GetInfinity();
			}
			else if (this->op == GR && other.op == IF) {
				return WrapForInfinity<T>::GetInfinity();
			}
			else if (this->op == GR && other.op == MIF) {
				return WrapForInfinity<T>::GetMinusInfinity();
			}
			else if (this->op == MIF && other.op == MIF) {
				return WrapForInfinity<T>::GetMinusInfinity();
			}
			else if (this->op == IF && other.op == IF) {
				return WrapForInfinity<T>::GetInfinity();
			}
			else
			{
				throw string(" + Error in wrapforinfiinity");
			}
		}
		WrapForInfinity<T> operator-(const WrapForInfinity<T>& other)const
		{
			if (other.op == this->op && this->op == GR) {
				return WrapForInfinity<T>(this->val - other.val, this->op);
			}
			else if (this->op == MIF && other.op == GR) {
				return WrapForInfinity<T>::GetMinusInfinity();
			}
			else if (this->op == GR && other.op == MIF) {
				return WrapForInfinity<T>::GetInfinity();
			}
			else if (this->op == IF && other.op == GR) {
				return WrapForInfinity<T>::GetInfinity();
			}
			else if (this->op == GR && other.op == IF) {
				return WrapForInfinity<T>::GetMinusInfinity();
			}
			else if (this->op == MIF && other.op == IF) {
				return WrapForInfinity<T>::GetMinusInfinity();
			}
			else if (this->op == IF && other.op == MIF) {
				return WrapForInfinity<T>::GetInfinity();
			}
			else
			{
				throw string(" - Error in wrapforinfiinity");
			}
		}
		string toString()const
		{
			if (this->op == MIF) return "minus infinity";
			else if (this->op == IF) return "plus infinity";
			else return wiz::toStr(this->val);
		}

		friend
        ostream& operator<<(ostream& stream, const WrapForInfinity<T,COMP,COMP2,EE>& wfi)
		{
		    if( wfi.op == MIF ) stream << "minus infinity";
            else if(wfi.op == IF ) stream << "plus infinity";
            else stream << wfi.val;

            return stream;
        }
		static WrapForInfinity<T, COMP, COMP2,EE > GetInfinity()
		{
			return WrapForInfinity<T, COMP, COMP2, EE >(T(), IF);
		}
		static WrapForInfinity<T, COMP, COMP2, EE > GetMinusInfinity()
		{
			return WrapForInfinity<T, COMP, COMP2, EE >(T(), MIF);
		}
	};

	template <typename T> /// x is 10吏꾩닔..
	inline T pos_1(const T x, const int base=10) // 1먮━ 媛怨꾩궛
	{
		if( x >= 0 ) { return x % base; }// x - ( x / 10 ) * 10; }
		else{ return (x / base) * base - x; }
		// -( x - ( (x/10) * 10 ) )
	}
	template <typename T> /// T <- char, int, long, long long...
	string toStr(const T x, const int base=10 ) /// chk!!
	{
		if( base < 2 || base > 16 ) { return "base is not valid"; }
		T i = x;

		const int INT_SIZE = sizeof(T) << 3; ///*8
		char* temp = new char[INT_SIZE + 1 + 1]; /// 1 NULL, 1 minus
		string tempString;
		int k;
		bool isMinus = (i < 0);
		temp[INT_SIZE+1] = '\0'; ///臾몄옄쒖떆..

		for (k = INT_SIZE; k >= 1; k--){
			T val = pos_1<T>(i, base); /// 0 ~ base-1
			/// number to ['0'~'9'] or ['A'~'F']
			if( val < 10 ) { temp[k] = val + '0'; }
			else { temp[k] = val-10 + 'A'; }

			i /= base;

			if (0 == i){ // レ옄.
				k--;
				break;
			}
		}

		if (isMinus){
			temp[k] = '-';
			tempString = string(temp + k);//
		}
		else{
			tempString = string(temp + k + 1); //
		}
		delete[] temp;

		return tempString;
	}

    /// chk.... need more thinking..., ToDo...
	template <typename T> /// T <- char, int, long, long long...
    string toStr2(const T x, const int str_space, const int base=10 ) /// chk!!
	{
	    if( base < 2 || base > 16 ) { return "base is not valid"; }
		T i = x;
		T k2 = 0;

		const int INT_SIZE = sizeof(T) << 3; ///*8
		char* temp = new char[INT_SIZE + 1 + 1]; /// 1 NULL, 1 minus
		for(int i=0; i < INT_SIZE+2; ++i ) { temp[i] = '0'; }//
		string tempString;
		int k;
		bool isMinus = (i < 0);
		temp[INT_SIZE+1] = '\0'; ///臾몄옄쒖떆..

		for (k = INT_SIZE; k >= 1; k--){
            T val = pos_1<T>(i, base); /// 0 ~ base-1
            /// number to ['0'~'9'] or ['A'~'F']
            if( val < 10 ) { temp[k] = val + '0'; }
            else { temp[k] = val-10 + 'A'; }

			i /= base;

			if (0 == i){ // レ옄.
				k--;
				break;
			}
		}

		if (isMinus){
			temp[k] = '-';
			tempString = string(temp + k);//
		}
		else{
            if( INT_SIZE+1 - (k+1) +1 < str_space+1 )
            {
                k2 = str_space+1 - ( INT_SIZE+1 - (k+1) + 1 );
            }
            else
            {
                k2 = 0;
            }
			tempString = string(temp + k + 1 - k2 ); //
		}
		delete[] temp;

		return tempString;
	}

	inline string str(const int x)
	{
		return toStr<int>(x);
	}

	template <typename T> /// 몄텧좊븣 뚯븘泥댄겕쒕떎
	inline string _toString(const T x)
	{
		std::stringstream strs;
		strs << x;
		return strs.str();
	}
	template <>
	inline string _toString(const long double x)
	{
		std::stringstream strs;
		strs << x;
		string temp = strs.str();
		size_t idx = temp.find('.');
		if (idx == temp.size()-1) {
			temp.push_back('0');
		}
		else if (idx == string::npos) {
			temp.push_back('.');
			temp.push_back('0');
		}
		return temp;
	}

	template <>
	inline string _toString(const long long x)
	{
		return toStr(x);
	}
	template <>
	inline string _toString(const int x)
	{
		return str(x);
	}
    template <>
	inline string _toString(const bool x)
	{
		if (x) { return "true"; }
		return "false";
	}

    // following remove
    inline bool isWhitespace( const char ch )
    {
        switch( ch )
        {
        case ' ':
        case '\t':
        case '\r':
        case '\n':
            return true;
        }
        return false;
    }

    template <typename T> // T must be unsigned type!
    inline T Unsigned_Maximum()
    {
        return -1;
    }

    template <typename T> // T must be signed type!
    T Signed_Maximum()
    {
        size_t byteSize = sizeof(T);
		T val = 0;

        val = 0x7F;
		for (size_t i = 1; i < byteSize; i++)
		{
			val = val << 8; // left shift 1 byte

			val = val | 0xFF;
		}
		return val;
    }
    // C++11
    template <typename T>
    inline T Maximum()
    {
        if( std::is_signed<T>::value )
        {
            return Signed_Maximum<T>();
        }
        if( std::is_unsigned<T>::value )
        {
            return Unsigned_Maximum<T>();
        }
        throw string( "unsupport type : double, class, and etc..." );
    }
	inline int getFirstIndex(const string& str, const char ch)
	{
		for (int i = 0; i < str.size(); ++i)
		{
			if (ch == str[i]) { return i; }
		}
		return -1;
	}
	class wizObject
	{
	private:
	public:
		wizObject() { }
		wizObject(const wizObject& object) { }

		virtual ~wizObject() { }

		virtual std::string toString()const = 0;
		//virtual void initial( const wizObject& object )=0;
		virtual wizObject& operator=(const wizObject& object) { return *this; }
		virtual wizObject* clone()const = 0;
	};

	template <typename T>
	T Rand() // T : maybe int, long, long long,.., ÀüÃ¼ ¹üÀ§ Rand...
	{
		size_t byteSize = sizeof(T);
		T val = 0;

		for (size_t i = 0; i < byteSize; i++)
		{
			val = val << 8; // left shift 1 byte

			val = val | (rand() % 256);
		}
		return val;
	}
	template <typename T>
	inline T Rand2() /// T : must be signed! and no return minus value.
	{
		T val = Rand<T>();
		return val & Signed_Maximum<T>();
	}
}
#endif
<commit_msg>Delete GLOBAL.H<commit_after><|endoftext|>


<commit_before>/*
    SWARM

    Copyright (C) 2012-2020 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

/*
  Blocked bloom filter with precomputed bit patterns
  as described in

  Putze F, Sanders P, Singler J (2009)
  Cache-, Hash- and Space-Efficient Bloom Filters
  Journal of Experimental Algorithmics, 14, 4
  https://doi.org/10.1145/1498698.1594230
*/

#include "swarm.h"

void bloomflex_patterns_generate(struct bloomflex_s * b);

void bloomflex_patterns_generate(struct bloomflex_s * b)
{
#if 0
  printf("Generating %" PRIu64 " patterns with %" PRIu64 " bits set.\n",
         b->pattern_count,
         b->pattern_k);
#endif
  for(auto i = 0U; i < b->pattern_count; i++)
    {
      uint64_t pattern {0};
      for(auto j = 0U; j < b->pattern_k; j++)
        {
          uint64_t onebit {0};
          onebit = 1ULL << (arch_random() & 63);
          while ((pattern & onebit) != 0U) {
            onebit = 1ULL << (arch_random() & 63);
          }
          pattern |= onebit;
        }
      b->patterns[i] = pattern;
    }
}

auto bloomflex_init(uint64_t size, unsigned int k) -> struct bloomflex_s *
{
  /* Input size is in bytes for full bitmap */

  auto * b = static_cast<struct bloomflex_s *>(xmalloc(sizeof(struct bloomflex_s)));
  b->size = size >> 3;

  b->pattern_shift = 16;
  b->pattern_count = 1 << b->pattern_shift;
  b->pattern_mask = b->pattern_count - 1;
  b->pattern_k = k;

  b->patterns = static_cast<uint64_t *>(xmalloc(b->pattern_count * 8));
  bloomflex_patterns_generate(b);

  b->bitmap = static_cast<uint64_t *>(xmalloc(size));
  memset(b->bitmap, UINT8_MAX, size);

  return b;
}

void bloomflex_exit(struct bloomflex_s * b)
{
  xfree(b->bitmap);
  xfree(b->patterns);
  xfree(b);
}
<commit_msg>avoid magic numbers<commit_after>/*
    SWARM

    Copyright (C) 2012-2020 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

/*
  Blocked bloom filter with precomputed bit patterns
  as described in

  Putze F, Sanders P, Singler J (2009)
  Cache-, Hash- and Space-Efficient Bloom Filters
  Journal of Experimental Algorithmics, 14, 4
  https://doi.org/10.1145/1498698.1594230
*/

#include "swarm.h"

void bloomflex_patterns_generate(struct bloomflex_s * b);

void bloomflex_patterns_generate(struct bloomflex_s * b)
{
  constexpr auto max_range {63U};  // i & max_range = cap values to 63 max
#if 0
  printf("Generating %" PRIu64 " patterns with %" PRIu64 " bits set.\n",
         b->pattern_count,
         b->pattern_k);
#endif
  for(auto i = 0U; i < b->pattern_count; i++)
    {
      uint64_t pattern {0};
      for(auto j = 0U; j < b->pattern_k; j++)
        {
          uint64_t onebit {0};
          onebit = 1ULL << (arch_random() & max_range);  // 0 <= shift <= 63
          while ((pattern & onebit) != 0U) {
            onebit = 1ULL << (arch_random() & max_range);
          }
          pattern |= onebit;
        }
      b->patterns[i] = pattern;
    }
}

auto bloomflex_init(uint64_t size, unsigned int k) -> struct bloomflex_s *
{
  /* Input size is in bytes for full bitmap */

  constexpr auto multiplier {16U};  // multiply by 65,536
  constexpr auto divider {3U};  // divide by 8
  auto * b = static_cast<struct bloomflex_s *>(xmalloc(sizeof(struct bloomflex_s)));
  b->size = size >> divider;

  b->pattern_shift = multiplier;
  b->pattern_count = 1 << b->pattern_shift;
  b->pattern_mask = b->pattern_count - 1;
  b->pattern_k = k;

  b->patterns = static_cast<uint64_t *>(xmalloc(b->pattern_count * sizeof(uint64_t)));
  bloomflex_patterns_generate(b);

  b->bitmap = static_cast<uint64_t *>(xmalloc(size));
  memset(b->bitmap, UINT8_MAX, size);

  return b;
}

void bloomflex_exit(struct bloomflex_s * b)
{
  xfree(b->bitmap);
  xfree(b->patterns);
  xfree(b);
}
<|endoftext|>


<commit_before>///
/// @file MainWindow.cpp
///
/// @Copyright (C) 2013 The Imaging Source GmbH; Edgar Thier <edgarthier@gmail.com>
///

#include "MainWindow.h"
#include "ui_mainwindow.h"

#include "../Camera.h"
#include "../utils.h"

#include <memory>
#include <thread>
#include <future>

#include <QThread>
#include <QFileDialog>
#include <QTreeView>
#include <QApplication>

using namespace tis;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->tabWidget->setCurrentIndex(0); // assure we always start with overview tab

    // assure camera list is sorted after the serial numbers in alphabetical order
    ui->cameraList->sortByColumn(0,Qt::AscendingOrder);
    ui->cameraList->setSortingEnabled(true);

    // disable dropping of leaves as top level items
    ui->cameraList->invisibleRootItem()->setFlags( Qt::ItemIsSelectable |
                                                   Qt::ItemIsUserCheckable |
                                                   Qt::ItemIsEnabled );

    // allow passing of camera_list between threads
    qRegisterMetaType<camera_list> ("camera_list");
    qRegisterMetaType<std::shared_ptr<Camera>> ("std::shared_ptr<Camera>");

    // connect thread signal to out update method
    connect(&uh, SIGNAL(update(camera_list)), this, SLOT(updateCycle(camera_list)));
    connect(&uh, SIGNAL(deprecated(std::shared_ptr<Camera>)), this, SLOT(deprecatedCamera(std::shared_ptr<Camera>)));

    uh.start();

    // hide progressbar until it is needed
    ui->progressFirmwareUpload->setHidden(true);

    // disable all tabs except first one
//    for (int x = 1; x < ui->tabWidget->count(); ++x)
//    {
//        ui->tabWidget->setTabEnabled(x, false);
//    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::displayCamera()
{
//    for (int x = 1; x < ui->tabWidget->count(); ++x)
//    {
//        ui->tabWidget->setTabEnabled(x, true);
//    }

    QList<QTreeWidgetItem*> selection = ui->cameraList->selectedItems();

    QTreeWidgetItem* item;
    if (!selection.empty())
    {
        item = selection.at(0);
    }
    else
    {
        return;
    }

    auto cam = getCameraFromList(cameras, item->text(coloumn.serial).toStdString());
    if (cam == NULL)
    {
        return;
    }

    selectedCamera = cam;
    blockUpload = false;

    // overview tab
    ui->displayModelName->setText(QString(cam->getModelName().c_str()));
    ui->displaySerialNumber->setText(QString(cam->getSerialNumber().c_str()));
    ui->displayVendor->setText(QString(cam->getVendorName().c_str()));

    ui->displayCurrentIP->setText(QString(cam->getCurrentIP().c_str()));
    ui->displayCurrentNetmask->setText(QString(cam->getCurrentSubnet().c_str()));
    ui->displayCurrentGateway->setText(QString(cam->getCurrentGateway().c_str()));
    ui->displayMAC->setText(QString(cam->getMAC().c_str()));

    // set name tab
    ui->editName->setText(QString(cam->getUserDefinedName().c_str()));

    // settings tab
    ui->editSettingsIP->setText(QString(cam->getPersistentIP().c_str()));
    ui->editSettingsNetmask->setText(QString(cam->getPersistentSubnet().c_str()));
    ui->editSettingsGateway->setText(QString(cam->getPersistentGateway().c_str()));

    if (cam->isDHCPactive())
    {
        ui->checkBoxDHCP->setChecked(true);
    }
    else
    {
        ui->checkBoxDHCP->setChecked(false);
    }

    if (cam->isStaticIPactive())
    {
        ui->checkBoxStatic->setChecked(true);
        // enable persistent config fields
        ui->editSettingsIP->setEnabled(true);
        ui->editSettingsNetmask->setEnabled(true);
        ui->editSettingsGateway->setEnabled(true);
    }
    else
    {
        ui->checkBoxStatic->setChecked(false);
        // disable persistent config fields
        ui->editSettingsIP->setEnabled(false);
        ui->editSettingsNetmask->setEnabled(false);
        ui->editSettingsGateway->setEnabled(false);
    }
     // firmware tab
    ui->labelVersion->setText(cam->getFirmwareVersion().c_str());
}

void MainWindow::addNetworkInterfacesToCameraList ()
{
    auto interfaces = detectNetworkInterfaces();

    for (const auto& interface : interfaces)
    {
        if ((ui->cameraList->findItems(QString(interface->getInterfaceName().c_str()), Qt::MatchContains).empty()))
        {
            QTreeWidgetItem* ifa = new QTreeWidgetItem();
            ifa->setText(0, QString(interface->getInterfaceName().c_str()));
            ifa->setFlags(Qt::ItemIsEnabled);
            ifa->setDisabled(false);
            ifa->sortChildren(0,Qt::AscendingOrder);

            ifa->setExpanded(true);

            ui->cameraList->addTopLevelItem(ifa);
        }
    }
}

void MainWindow::addCameraToCameraList (const std::shared_ptr<Camera> cam)
{
    QList<QTreeWidgetItem*> interface = ui->cameraList->findItems(QString(cam->getInterfaceName().c_str()), Qt::MatchContains);

    if (!interface.empty())
    {
        QTreeWidgetItem* new_cam = new QTreeWidgetItem();

        QString name = cam->getModelName().c_str();

        new_cam->setText(coloumn.model, name);
        new_cam->setText(coloumn.serial, QString(cam->getSerialNumber().c_str()));
        new_cam->setText(coloumn.name, QString(cam->getUserDefinedName().c_str()));
        new_cam->setText(coloumn.ip, QString(cam->getCurrentIP().c_str()));
        new_cam->setText(coloumn.netmask, QString(cam->getCurrentSubnet().c_str()));
        new_cam->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable
                          | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled);
        new_cam->setDisabled(false);
        interface.at(0)->addChild(new_cam);
    }
}

void MainWindow::updateCamera (QTreeWidgetItem& item, const std::shared_ptr<Camera> camera)
{
    item.setText(coloumn.name,   QString(camera->getUserDefinedName().c_str()));
    item.setText(coloumn.ip,     QString(camera->getCurrentIP().c_str()));
    item.setText(coloumn.netmask,QString(camera->getCurrentSubnet().c_str()));

    // if nothing is selected we are finished
    if (selectedCamera == NULL)
    {
        return;
    }

    if (camera->getSerialNumber().compare(selectedCamera->getSerialNumber()) == 0)
    {

        ui->displayModelName->setText(QString(camera->getModelName().c_str()));
        ui->displaySerialNumber->setText(QString(camera->getSerialNumber().c_str()));
        ui->displayVendor->setText(QString(camera->getVendorName().c_str()));

        ui->displayCurrentIP->setText(QString(camera->getCurrentIP().c_str()));
        ui->displayCurrentNetmask->setText(QString(camera->getCurrentSubnet().c_str()));
        ui->displayCurrentGateway->setText(QString(camera->getCurrentGateway().c_str()));
        ui->displayMAC->setText(QString(camera->getMAC().c_str()));

        // firmware tab
        ui->labelVersion->setText(camera->getFirmwareVersion().c_str());
    }
}

void MainWindow::updateCameraList ()
{
    QList<QTreeWidgetItem*> selection = ui->cameraList->selectedItems();

    QString s;
    if (!selection.empty())
    {
        s = selection.at(0)->text(0);
    }

    addNetworkInterfacesToCameraList();
    for (const auto& cam : cameras)
    {
        QList<QTreeWidgetItem*> list = ui->cameraList->findItems(
                    QString(cam->getSerialNumber().c_str()),Qt::MatchRecursive | Qt::MatchContains, coloumn.serial);
        if (list.size() != 1)
        {
            addCameraToCameraList(cam);
        }
        else
        {
            updateCamera(*list.at(0), cam);
        }
    }
}

void MainWindow::changeToSettings()
{
    int index = 1;

    for (int x = 0; x < ui->tabWidget->count(); ++x)
    {
        const QWidget* q = ui->tabWidget->widget(x);
        if (q->accessibleName().compare(QString("Settings")) == 0)
        {
            index = x;
            break;
        }
    }

    ui->tabWidget->setCurrentIndex(index);
}

void MainWindow::sendForceIP()
{
    std::string forceIP = ui->editForceIP->text().toStdString();
    std::string forceGateway = ui->editForceGateway->text().toStdString();
    std::string forceNetmask = ui->editForceNetmask->text().toStdString();

    std::string errorMessage;

    // check if input is valid
    if (!isValidIpAddress(forceIP))
    {
        errorMessage.append("Not a valid IP\n");
    }

    if (!isValidIpAddress(forceGateway))
    {
        errorMessage.append("Not a valid netmask\n");
    }
    if (!isValidIpAddress(forceNetmask))
    {
        errorMessage.append("Not a valid gateway");
    }

    if (!errorMessage.empty())
    {
        QString msg = errorMessage.c_str();
        box.showMessage(msg);
        return;
    }

    selectedCamera->forceIP(forceIP, forceNetmask, forceGateway);
}

void MainWindow::saveName()
{
    std::string name = ui->editName->text().toStdString();

    if (selectedCamera != NULL)
    {
        selectedCamera->setUserDefinedName(name);
    }

    ui->editName->setText("");
}

void MainWindow::saveSettings ()
{
    if (selectedCamera == NULL)
    {
        return;
    }

    // retrieve Settings

    bool activateDHCP = ui->checkBoxDHCP->isChecked();
    bool activateStatic = ui->checkBoxStatic->isChecked();

    std::string ip = ui->editSettingsIP->text().toStdString();
    std::string netmask = ui->editSettingsNetmask->text().toStdString();
    std::string gateway = ui->editSettingsGateway->text().toStdString();

    std::string errorMessage;

    // check if input is valid
    if (!isValidIpAddress(ip))
    {
        errorMessage.append("Not a valid IP\n");
    }

    if (!isValidIpAddress(netmask))
    {
        errorMessage.append("Not a valid netmask\n");
    }
    if (!isValidIpAddress(gateway))
    {
        errorMessage.append("Not a valid gateway");
    }

    if (!errorMessage.empty())
    {
        QString msg = errorMessage.c_str();
        box.showMessage(msg);
        return;
    }

    if (!selectedCamera->setPersistentIP(ip))
    {
        QString s = "Error setting Persistent IP.";
        box.showMessage(s);
        return;
    }
    if (!selectedCamera->setPersistentSubnet(netmask))
    {
        QString s = "Error setting Persistent Netmask.";
        box.showMessage(s);
        return;
    }
    if (!selectedCamera->setPersistentGateway(gateway))
    {
        QString s = "Error setting Persistent Gateway.";
        box.showMessage(s);
        return;
    }

    if (activateStatic)
    {
        selectedCamera->setStaticIPstate(true);
    }
    else
    {
        selectedCamera->setStaticIPstate(false);
    }

    if (activateDHCP)
    {
        selectedCamera->setDHCPstate(true);
    }
    else
    {
        selectedCamera->setDHCPstate(false);
    }
    selectedCamera->resetIP();
}

void MainWindow::allowPersistentConfig (bool allow)
{
    if (allow)
    {
        ui->editSettingsIP->setEnabled(true);
        ui->editSettingsNetmask->setEnabled(true);
        ui->editSettingsGateway->setEnabled(true);
    }
    else
    {
        ui->editSettingsIP->setEnabled(false);
        ui->editSettingsNetmask->setEnabled(false);
        ui->editSettingsGateway->setEnabled(false);
    }
}

void MainWindow::buttonFirmware_clicked ()
{
    // show file dialog and fill edit box with selected filepath
    QString fileName = QFileDialog::getOpenFileName(this,
                                                    tr("Open Firmware File"),
                                                    QDir::homePath(),
                                                    tr("Firmware Files (*.fwpack *.fw)"));
    ui->editFirmwarePath->setText(fileName);
}

void MainWindow::uploadFirmware ()
{

    if (blockUpload)
    {
        return;
    }

    std::string firmware_file = ui->editFirmwarePath->text().toStdString();
    if (firmware_file.empty())
    {
        return;
    }
    ui->progressFirmwareUpload->setVisible(true);

    auto func = [this] (int val)
    {

        ui->progressFirmwareUpload->setValue(val);
    };

    if (selectedCamera->uploadFirmware(firmware_file, func))
    {
        blockUpload = true;
        QString s = "Successfully uploaded Firmware. Please reconnect your camera for full funcionality.";
        box.showMessage(s);
    }
    else
    {
        QString s = "Error while uploading Firmware. Please try again.";
        box.showMessage(s);
    }
    ui->editFirmwarePath->setText("");
    ui->progressFirmwareUpload->setVisible(false);
}

void MainWindow::updateCycle (camera_list c)
{
    this->cameras = c;
    updateCameraList();
}

void MainWindow::deprecatedCamera (std::shared_ptr<Camera> camera)
{
    QTreeWidgetItem* item;

    QList<QTreeWidgetItem*> l = ui->cameraList->selectedItems();
    if (l.size() > 1)
    {
        // something is wrong; don't make it worse
        return;
    }

    // the lost camera is the selected one, therefore we have to clean up everything
    if (l.size() == 1 && camera->getSerialNumber().compare(l.at(0)->text(coloumn.serial).toStdString()) == 0)
    {
        item = l.at(0);
        QString defaultText = "<Select Device>";
        QString emptyString = "";
        ui->tabWidget->setCurrentIndex(0);

        // not working; gui is not updated
//        for (int x = 1; x < ui->tabWidget->count(); ++x)
//        {
//            ui->tabWidget->setTabEnabled(x, false);
//        }

        ui->displayModelName->setText(defaultText);
        ui->displaySerialNumber->setText(defaultText);
        ui->displayVendor->setText(defaultText);

        ui->displayCurrentIP->setText(defaultText);
        ui->displayCurrentNetmask->setText(defaultText);
        ui->displayCurrentGateway->setText(defaultText);
        ui->displayMAC->setText(defaultText);

        // set name tab
        ui->editName->setText(emptyString);

        // settings tab
        ui->editSettingsIP->setText(emptyString);
        ui->editSettingsNetmask->setText(emptyString);
        ui->editSettingsGateway->setText(emptyString);

        ui->checkBoxDHCP->setChecked(false);
        ui->checkBoxStatic->setChecked(false);
        // enable persistent config fields
        ui->editSettingsIP->setEnabled(true);
        ui->editSettingsNetmask->setEnabled(true);
        ui->editSettingsGateway->setEnabled(true);

        // firmware tab
        ui->labelVersion->setText(defaultText);

        blockUpload = false;
    }
    else
    {
        // Not the selected camera
        QList<QTreeWidgetItem*> list = ui->cameraList->findItems(
                    QString(camera->getSerialNumber().c_str()), Qt::MatchRecursive | Qt::MatchContains, coloumn.serial);
        if (list.size() == 1)
        {
            item = list.at(0);
        }
        else
        {
            return;
        }
    }

    // remove from camera tree
    QTreeWidgetItem* par = item->parent();
    par->removeChild(item);
}
<commit_msg>Cleanup<commit_after>///
/// @file MainWindow.cpp
///
/// @Copyright (C) 2013 The Imaging Source GmbH; Edgar Thier <edgarthier@gmail.com>
///

#include "MainWindow.h"
#include "ui_mainwindow.h"

#include "../Camera.h"
#include "../utils.h"

#include <memory>
#include <thread>
#include <future>

#include <QThread>
#include <QFileDialog>
#include <QTreeView>
#include <QApplication>

using namespace tis;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->tabWidget->setCurrentIndex(0); // assure we always start with overview tab

    // assure camera list is sorted after the serial numbers in alphabetical order
    ui->cameraList->sortByColumn(0,Qt::AscendingOrder);
    ui->cameraList->setSortingEnabled(true);

    // disable dropping of leaves as top level items
    ui->cameraList->invisibleRootItem()->setFlags( Qt::ItemIsSelectable |
                                                   Qt::ItemIsUserCheckable |
                                                   Qt::ItemIsEnabled );

    // allow passing of camera_list between threads
    qRegisterMetaType<camera_list> ("camera_list");
    qRegisterMetaType<std::shared_ptr<Camera>> ("std::shared_ptr<Camera>");

    // connect thread signal to out update method
    connect(&uh, SIGNAL(update(camera_list)), this, SLOT(updateCycle(camera_list)));
    connect(&uh, SIGNAL(deprecated(std::shared_ptr<Camera>)), this, SLOT(deprecatedCamera(std::shared_ptr<Camera>)));

    uh.start();

    // hide progressbar until it is needed
    ui->progressFirmwareUpload->setHidden(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::displayCamera()
{
    QList<QTreeWidgetItem*> selection = ui->cameraList->selectedItems();

    QTreeWidgetItem* item;
    if (!selection.empty())
    {
        item = selection.at(0);
    }
    else
    {
        return;
    }

    auto cam = getCameraFromList(cameras, item->text(coloumn.serial).toStdString());
    if (cam == NULL)
    {
        return;
    }

    selectedCamera = cam;
    blockUpload = false;

    // overview tab
    ui->displayModelName->setText(QString(cam->getModelName().c_str()));
    ui->displaySerialNumber->setText(QString(cam->getSerialNumber().c_str()));
    ui->displayVendor->setText(QString(cam->getVendorName().c_str()));

    ui->displayCurrentIP->setText(QString(cam->getCurrentIP().c_str()));
    ui->displayCurrentNetmask->setText(QString(cam->getCurrentSubnet().c_str()));
    ui->displayCurrentGateway->setText(QString(cam->getCurrentGateway().c_str()));
    ui->displayMAC->setText(QString(cam->getMAC().c_str()));

    // set name tab
    ui->editName->setText(QString(cam->getUserDefinedName().c_str()));

    // settings tab
    ui->editSettingsIP->setText(QString(cam->getPersistentIP().c_str()));
    ui->editSettingsNetmask->setText(QString(cam->getPersistentSubnet().c_str()));
    ui->editSettingsGateway->setText(QString(cam->getPersistentGateway().c_str()));

    if (cam->isDHCPactive())
    {
        ui->checkBoxDHCP->setChecked(true);
    }
    else
    {
        ui->checkBoxDHCP->setChecked(false);
    }

    if (cam->isStaticIPactive())
    {
        ui->checkBoxStatic->setChecked(true);
        // enable persistent config fields
        ui->editSettingsIP->setEnabled(true);
        ui->editSettingsNetmask->setEnabled(true);
        ui->editSettingsGateway->setEnabled(true);
    }
    else
    {
        ui->checkBoxStatic->setChecked(false);
        // disable persistent config fields
        ui->editSettingsIP->setEnabled(false);
        ui->editSettingsNetmask->setEnabled(false);
        ui->editSettingsGateway->setEnabled(false);
    }
     // firmware tab
    ui->labelVersion->setText(cam->getFirmwareVersion().c_str());
}

void MainWindow::addNetworkInterfacesToCameraList ()
{
    auto interfaces = detectNetworkInterfaces();

    for (const auto& interface : interfaces)
    {
        if ((ui->cameraList->findItems(QString(interface->getInterfaceName().c_str()), Qt::MatchContains).empty()))
        {
            QTreeWidgetItem* ifa = new QTreeWidgetItem();
            ifa->setText(0, QString(interface->getInterfaceName().c_str()));
            ifa->setFlags(Qt::ItemIsEnabled);
            ifa->setDisabled(false);
            ifa->sortChildren(0,Qt::AscendingOrder);

            ifa->setExpanded(true);

            ui->cameraList->addTopLevelItem(ifa);
        }
    }
}

void MainWindow::addCameraToCameraList (const std::shared_ptr<Camera> cam)
{
    QList<QTreeWidgetItem*> interface = ui->cameraList->findItems(QString(cam->getInterfaceName().c_str()), Qt::MatchContains);

    if (!interface.empty())
    {
        QTreeWidgetItem* new_cam = new QTreeWidgetItem();

        QString name = cam->getModelName().c_str();

        new_cam->setText(coloumn.model, name);
        new_cam->setText(coloumn.serial, QString(cam->getSerialNumber().c_str()));
        new_cam->setText(coloumn.name, QString(cam->getUserDefinedName().c_str()));
        new_cam->setText(coloumn.ip, QString(cam->getCurrentIP().c_str()));
        new_cam->setText(coloumn.netmask, QString(cam->getCurrentSubnet().c_str()));
        new_cam->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable
                          | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled);
        new_cam->setDisabled(false);
        interface.at(0)->addChild(new_cam);
    }
}

void MainWindow::updateCamera (QTreeWidgetItem& item, const std::shared_ptr<Camera> camera)
{
    item.setText(coloumn.name,   QString(camera->getUserDefinedName().c_str()));
    item.setText(coloumn.ip,     QString(camera->getCurrentIP().c_str()));
    item.setText(coloumn.netmask,QString(camera->getCurrentSubnet().c_str()));

    // if nothing is selected we are finished
    if (selectedCamera == NULL)
    {
        return;
    }

    if (camera->getSerialNumber().compare(selectedCamera->getSerialNumber()) == 0)
    {

        ui->displayModelName->setText(QString(camera->getModelName().c_str()));
        ui->displaySerialNumber->setText(QString(camera->getSerialNumber().c_str()));
        ui->displayVendor->setText(QString(camera->getVendorName().c_str()));

        ui->displayCurrentIP->setText(QString(camera->getCurrentIP().c_str()));
        ui->displayCurrentNetmask->setText(QString(camera->getCurrentSubnet().c_str()));
        ui->displayCurrentGateway->setText(QString(camera->getCurrentGateway().c_str()));
        ui->displayMAC->setText(QString(camera->getMAC().c_str()));

        // firmware tab
        ui->labelVersion->setText(camera->getFirmwareVersion().c_str());
    }
}

void MainWindow::updateCameraList ()
{
    QList<QTreeWidgetItem*> selection = ui->cameraList->selectedItems();

    QString s;
    if (!selection.empty())
    {
        s = selection.at(0)->text(0);
    }

    addNetworkInterfacesToCameraList();
    for (const auto& cam : cameras)
    {
        QList<QTreeWidgetItem*> list = ui->cameraList->findItems(
                    QString(cam->getSerialNumber().c_str()),Qt::MatchRecursive | Qt::MatchContains, coloumn.serial);
        if (list.size() != 1)
        {
            addCameraToCameraList(cam);
        }
        else
        {
            updateCamera(*list.at(0), cam);
        }
    }
}

void MainWindow::changeToSettings()
{
    int index = 1;

    for (int x = 0; x < ui->tabWidget->count(); ++x)
    {
        const QWidget* q = ui->tabWidget->widget(x);
        if (q->accessibleName().compare(QString("Settings")) == 0)
        {
            index = x;
            break;
        }
    }

    ui->tabWidget->setCurrentIndex(index);
}

void MainWindow::sendForceIP()
{
    std::string forceIP = ui->editForceIP->text().toStdString();
    std::string forceGateway = ui->editForceGateway->text().toStdString();
    std::string forceNetmask = ui->editForceNetmask->text().toStdString();

    std::string errorMessage;

    // check if input is valid
    if (!isValidIpAddress(forceIP))
    {
        errorMessage.append("Not a valid IP\n");
    }

    if (!isValidIpAddress(forceGateway))
    {
        errorMessage.append("Not a valid netmask\n");
    }
    if (!isValidIpAddress(forceNetmask))
    {
        errorMessage.append("Not a valid gateway");
    }

    if (!errorMessage.empty())
    {
        QString msg = errorMessage.c_str();
        box.showMessage(msg);
        return;
    }

    selectedCamera->forceIP(forceIP, forceNetmask, forceGateway);
}

void MainWindow::saveName()
{
    std::string name = ui->editName->text().toStdString();

    if (selectedCamera != NULL)
    {
        selectedCamera->setUserDefinedName(name);
    }

    ui->editName->setText("");
}

void MainWindow::saveSettings ()
{
    if (selectedCamera == NULL)
    {
        return;
    }

    // retrieve Settings

    bool activateDHCP = ui->checkBoxDHCP->isChecked();
    bool activateStatic = ui->checkBoxStatic->isChecked();

    std::string ip = ui->editSettingsIP->text().toStdString();
    std::string netmask = ui->editSettingsNetmask->text().toStdString();
    std::string gateway = ui->editSettingsGateway->text().toStdString();

    std::string errorMessage;

    // check if input is valid
    if (!isValidIpAddress(ip))
    {
        errorMessage.append("Not a valid IP\n");
    }

    if (!isValidIpAddress(netmask))
    {
        errorMessage.append("Not a valid netmask\n");
    }
    if (!isValidIpAddress(gateway))
    {
        errorMessage.append("Not a valid gateway");
    }

    if (!errorMessage.empty())
    {
        QString msg = errorMessage.c_str();
        box.showMessage(msg);
        return;
    }

    if (!selectedCamera->setPersistentIP(ip))
    {
        QString s = "Error setting Persistent IP.";
        box.showMessage(s);
        return;
    }
    if (!selectedCamera->setPersistentSubnet(netmask))
    {
        QString s = "Error setting Persistent Netmask.";
        box.showMessage(s);
        return;
    }
    if (!selectedCamera->setPersistentGateway(gateway))
    {
        QString s = "Error setting Persistent Gateway.";
        box.showMessage(s);
        return;
    }

    if (activateStatic)
    {
        selectedCamera->setStaticIPstate(true);
    }
    else
    {
        selectedCamera->setStaticIPstate(false);
    }

    if (activateDHCP)
    {
        selectedCamera->setDHCPstate(true);
    }
    else
    {
        selectedCamera->setDHCPstate(false);
    }
    selectedCamera->resetIP();
}

void MainWindow::allowPersistentConfig (bool allow)
{
    if (allow)
    {
        ui->editSettingsIP->setEnabled(true);
        ui->editSettingsNetmask->setEnabled(true);
        ui->editSettingsGateway->setEnabled(true);
    }
    else
    {
        ui->editSettingsIP->setEnabled(false);
        ui->editSettingsNetmask->setEnabled(false);
        ui->editSettingsGateway->setEnabled(false);
    }
}

void MainWindow::buttonFirmware_clicked ()
{
    // show file dialog and fill edit box with selected filepath
    QString fileName = QFileDialog::getOpenFileName(this,
                                                    tr("Open Firmware File"),
                                                    QDir::homePath(),
                                                    tr("Firmware Files (*.fwpack *.fw)"));
    ui->editFirmwarePath->setText(fileName);
}

void MainWindow::uploadFirmware ()
{

    if (blockUpload)
    {
        return;
    }

    std::string firmware_file = ui->editFirmwarePath->text().toStdString();
    if (firmware_file.empty())
    {
        return;
    }
    ui->progressFirmwareUpload->setVisible(true);

    auto func = [this] (int val)
    {

        ui->progressFirmwareUpload->setValue(val);
    };

    if (selectedCamera->uploadFirmware(firmware_file, func))
    {
        blockUpload = true;
        QString s = "Successfully uploaded Firmware. Please reconnect your camera for full funcionality.";
        box.showMessage(s);
    }
    else
    {
        QString s = "Error while uploading Firmware. Please try again.";
        box.showMessage(s);
    }
    ui->editFirmwarePath->setText("");
    ui->progressFirmwareUpload->setVisible(false);
}

void MainWindow::updateCycle (camera_list c)
{
    this->cameras = c;
    updateCameraList();
}

void MainWindow::deprecatedCamera (std::shared_ptr<Camera> camera)
{
    QTreeWidgetItem* item;

    QList<QTreeWidgetItem*> l = ui->cameraList->selectedItems();
    if (l.size() > 1)
    {
        // something is wrong; don't make it worse
        return;
    }

    // the lost camera is the selected one, therefore we have to clean up everything
    if (l.size() == 1 && camera->getSerialNumber().compare(l.at(0)->text(coloumn.serial).toStdString()) == 0)
    {
        item = l.at(0);
        QString defaultText = "<Select Device>";
        QString emptyString = "";
        ui->tabWidget->setCurrentIndex(0);

        ui->displayModelName->setText(defaultText);
        ui->displaySerialNumber->setText(defaultText);
        ui->displayVendor->setText(defaultText);

        ui->displayCurrentIP->setText(defaultText);
        ui->displayCurrentNetmask->setText(defaultText);
        ui->displayCurrentGateway->setText(defaultText);
        ui->displayMAC->setText(defaultText);

        // set name tab
        ui->editName->setText(emptyString);

        // settings tab
        ui->editSettingsIP->setText(emptyString);
        ui->editSettingsNetmask->setText(emptyString);
        ui->editSettingsGateway->setText(emptyString);

        ui->checkBoxDHCP->setChecked(false);
        ui->checkBoxStatic->setChecked(false);
        // enable persistent config fields
        ui->editSettingsIP->setEnabled(true);
        ui->editSettingsNetmask->setEnabled(true);
        ui->editSettingsGateway->setEnabled(true);

        // firmware tab
        ui->labelVersion->setText(defaultText);

        blockUpload = false;
    }
    else
    {
        // Not the selected camera
        QList<QTreeWidgetItem*> list = ui->cameraList->findItems(
                    QString(camera->getSerialNumber().c_str()), Qt::MatchRecursive | Qt::MatchContains, coloumn.serial);
        if (list.size() == 1)
        {
            item = list.at(0);
        }
        else
        {
            return;
        }
    }

    // remove from camera tree
    QTreeWidgetItem* par = item->parent();
    par->removeChild(item);
}
<|endoftext|>


<commit_before><commit_msg>Planning: faster approach to stop_sign<commit_after><|endoftext|>


<commit_before>//  (C) Copyright Gennadiy Rozental 2005-2014.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : defines exceptions and validation tools
// ***************************************************************************

#ifndef BOOST_RT_VALIDATION_HPP_062604GER
#define BOOST_RT_VALIDATION_HPP_062604GER

// Boost.Runtime.Parameter
#include <boost/test/utils/runtime/config.hpp>

// Boost.Test
#include <boost/test/utils/class_properties.hpp>

// Boost
#include <boost/shared_ptr.hpp>

// STL
#ifdef BOOST_RT_PARAM_EXCEPTION_INHERIT_STD
#include <stdexcept>
#endif

namespace boost {

namespace BOOST_RT_PARAM_NAMESPACE {

// ************************************************************************** //
// **************             runtime::logic_error             ************** //
// ************************************************************************** //

class logic_error
#ifdef BOOST_RT_PARAM_EXCEPTION_INHERIT_STD
: public std::exception
#endif
{
    typedef shared_ptr<dstring> dstring_ptr;
public:
    // Constructor // !! could we eliminate shared_ptr
    explicit    logic_error( cstring msg ) : m_msg( new dstring( msg.begin(), msg.size() ) ) {}
    ~logic_error() BOOST_TEST_NOEXCEPT_OR_THROW_VOID
    {}

    dstring const&   msg() const                    { return *m_msg; }
    virtual char_type const* what() const BOOST_TEST_NOEXCEPT_OR_THROW_VOID
    { return m_msg->c_str(); }

private:
    dstring_ptr m_msg;
};

// ************************************************************************** //
// **************          runtime::report_logic_error         ************** //
// ************************************************************************** //

inline void
report_logic_error( format_stream& msg )
{
    throw BOOST_RT_PARAM_NAMESPACE::logic_error( msg.str() );
}

//____________________________________________________________________________//

#define BOOST_RT_PARAM_REPORT_LOGIC_ERROR( msg ) \
    boost::BOOST_RT_PARAM_NAMESPACE::report_logic_error( format_stream().ref() << msg )

#define BOOST_RT_PARAM_VALIDATE_LOGIC( b, msg ) \
    if( b ) {} else BOOST_RT_PARAM_REPORT_LOGIC_ERROR( msg )

//____________________________________________________________________________//

} // namespace BOOST_RT_PARAM_NAMESPACE

} // namespace boost

#endif // BOOST_RT_VALIDATION_HPP_062604GER
<commit_msg>Using existing macros in boost.config to achieve the same result<commit_after>//  (C) Copyright Gennadiy Rozental 2005-2014.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : defines exceptions and validation tools
// ***************************************************************************

#ifndef BOOST_RT_VALIDATION_HPP_062604GER
#define BOOST_RT_VALIDATION_HPP_062604GER

// Boost.Runtime.Parameter
#include <boost/test/utils/runtime/config.hpp>

// Boost.Test
#include <boost/test/utils/class_properties.hpp>

// Boost
#include <boost/shared_ptr.hpp>

// STL
#ifdef BOOST_RT_PARAM_EXCEPTION_INHERIT_STD
#include <stdexcept>
#endif

namespace boost {

namespace BOOST_RT_PARAM_NAMESPACE {

// ************************************************************************** //
// **************             runtime::logic_error             ************** //
// ************************************************************************** //

class logic_error
#ifdef BOOST_RT_PARAM_EXCEPTION_INHERIT_STD
: public std::exception
#endif
{
    typedef shared_ptr<dstring> dstring_ptr;
public:
    // Constructor // !! could we eliminate shared_ptr
    explicit    logic_error( cstring msg ) : m_msg( new dstring( msg.begin(), msg.size() ) ) {}
    ~logic_error() BOOST_NOEXCEPT_OR_NOTHROW
    {}

    dstring const&   msg() const                    { return *m_msg; }
    virtual char_type const* what() const BOOST_NOEXCEPT_OR_NOTHROW
    { return m_msg->c_str(); }

private:
    dstring_ptr m_msg;
};

// ************************************************************************** //
// **************          runtime::report_logic_error         ************** //
// ************************************************************************** //

inline void
report_logic_error( format_stream& msg )
{
    throw BOOST_RT_PARAM_NAMESPACE::logic_error( msg.str() );
}

//____________________________________________________________________________//

#define BOOST_RT_PARAM_REPORT_LOGIC_ERROR( msg ) \
    boost::BOOST_RT_PARAM_NAMESPACE::report_logic_error( format_stream().ref() << msg )

#define BOOST_RT_PARAM_VALIDATE_LOGIC( b, msg ) \
    if( b ) {} else BOOST_RT_PARAM_REPORT_LOGIC_ERROR( msg )

//____________________________________________________________________________//

} // namespace BOOST_RT_PARAM_NAMESPACE

} // namespace boost

#endif // BOOST_RT_VALIDATION_HPP_062604GER
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	Arithmetic テンプレート @n
			※テキストの数式を展開して、計算結果を得る。@n
			演算式解析
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
#include "utils/bitset.hpp"
//#include "utils/order_map.hpp"

namespace utils {

	template <typename VTYPE, uint16_t NUM>
	class basic_symbol {

		const char* table_[NUM];
		VTYPE	value_[NUM];

		uint16_t find_(const char* name, uint8_t n) const {
			for(uint16_t i = 0; i < NUM; ++i) {
				if(n != 0) {
					if(std::strcmp(name, table_[i]) == 0) return i;
				} else {
					if(std::strncmp(name, table_[i], n) == 0) return i;
				}
			}
			return NUM;
		}
	public:
		basic_symbol() {
			for(uint16_t i = 0; i < NUM; ++i) {
				table_[i] = nullptr;
			}
		}

		bool insert(const char* name, VTYPE v) {
			for(uint16_t i = 0; i < NUM; ++i) {
				if(table_[i] == nullptr) {
					table_[i] = name;
					value_[i] = v;
					return true;
				}
			}
			return false;
		}

		bool erase(const char* name, uint8_t n = 0) {
			auto i = find_(name, n);
			if(i >= NUM) return false;
			table_[i] = nullptr;
			return true;
		}

		bool find(const char* name, uint8_t n = 0) const {
			return find_(name, n) < NUM;
		}

		bool set(const char*name, uint8_t n, VTYPE value) {
			auto i = find_(name, n);
			if(i >= NUM) return false;
			value_[i] = value;
			return true;
		}

		VTYPE get(const char* name, uint8_t n = 0) const {
			auto i = find_(name, n);
			if(i >= NUM) {
				return 0;
			}
			return value_[i];
		}
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	Arithmetic クラス
		@param[in]	VTYPE	基本型
		@param[in]	SYMBOL	シンボルクラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <typename VTYPE, class SYMBOL = basic_symbol<VTYPE, 16> >
	struct basic_arith {

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief	エラー・タイプ
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class error : uint8_t {
			fatal,				///< エラー
			number_fatal,		///< 数字の変換に関するエラー
			zero_divide,		///< ０除算エラー
			binary_fatal,		///< ２進データの変換に関するエラー
			octal_fatal,		///< ８進データの変換に関するエラー
			hexdecimal_fatal,	///< １６進データの変換に関するエラー
			num_fatal,			///< 数値の変換に関するエラー
			symbol_fatal,		///< シンボルデータの変換に関するエラー
		};

		typedef bitset<uint16_t, error> error_t;

	private:

		SYMBOL			symbol_;

		const char*		tx_;
		char			ch_;

		error_t		error_;

		VTYPE		value_;

		void skip_space_() {
			while(ch_ == ' ' || ch_ == '\t') {
				ch_ = *tx_++;
			}
		}

		VTYPE number_() {
			bool inv = false;
///			bool neg = false;
			bool point = false;
			uint32_t v = 0;
			uint32_t fp = 0;
			uint32_t fs = 1;

			skip_space_();

			// 符号、反転の判定
			if(ch_ == '-') {
				inv = true;
				ch_ = *tx_++;
			} else if(ch_ == '+') {
				ch_ = *tx_++;
//			} else if(ch_ == '!' || ch_ == '~') {
//				neg = true;
//				ch_ = *tx_++;
			}

			skip_space_();

			if(ch_ == '(') {
				v = factor_();
			} else {
				skip_space_();

				if((ch_ >= 'A' && ch_ <= 'Z') || (ch_ >= 'a' && ch_ <= 'z')) {
					const char* src = tx_ - 1;
					while(ch_ != 0) {
						ch_ = *tx_++;
						if((ch_ >= 'A' && ch_ <= 'Z') || (ch_ >= 'a' && ch_ <= 'z')) ;
						else if(ch_ >= '0' && ch_ <= '9') ;
						else if(ch_ == '_') ;
						else break;
					}
					if(!symbol_.find(src, tx_ - src)) {
						error_.set(error::symbol_fatal);
						return 0;
					}
					v = symbol_.get(src, tx_ - src);
				} else {
					while(ch_ != 0) {
						if(ch_ == '+') break;
						else if(ch_ == '-') break;
						else if(ch_ == '*') break;
						else if(ch_ == '/') break;
						else if(ch_ == '&') break;
						else if(ch_ == '^') break;
						else if(ch_ == '|') break;
						else if(ch_ == '%') break;
						else if(ch_ == ')') break;
						else if(ch_ == '<') break;
						else if(ch_ == '>') break;
						else if(ch_ == '!') break;
						else if(ch_ == '~') break;
						else if(ch_ == '.') {
							if(point) {
								error_.set(error::fatal);
								break;
							} else {
								point = true;
							}
						} else if(ch_ >= '0' && ch_ <= '9') {
							if(point) {
								fp *= 10;
								fp += ch_ - '0';
								fs *= 10;
							} else {
								v *= 10;
								v += ch_ - '0';
							}
						} else {
							error_.set(error::number_fatal);
							return 0;
						}
						ch_ = *tx_++;
					}
				}
			}

			if(inv) { v = -v; }
///			if(neg) { v = ~v; }
			if(point) {
				return static_cast<VTYPE>(v) + static_cast<VTYPE>(fp) / static_cast<VTYPE>(fs);
			} else {
				return static_cast<VTYPE>(v);
			}
		}

		VTYPE factor_() {
			VTYPE v = 0;
			if(ch_ == '(') {
				ch_ = *tx_++;
				v = expression_();
				if(ch_ == ')') {
					ch_ = *tx_++;
				} else {
					error_.set(error::fatal);
				}
			} else {
				v = number_();
			}
			return v;
		}

		VTYPE term_() {
			VTYPE v = factor_();
			VTYPE tmp;
			while(error_() == 0) {
				switch(ch_) {
				case ' ':
				case '\t':
					ch_ = *tx_++;
					break;
				case '*':
					ch_ = *tx_++;
					v *= factor_();
					break;
				case '%':
					ch_ = *tx_++;
					tmp = factor_();
					if(tmp == 0) {
						error_.set(error::zero_divide);
						break;
					}
					v /= tmp;
					break;
				case '/':
					ch_ = *tx_++;
					if(ch_ == '/') {
						ch_ = *tx_++;
						tmp = factor_();
						if(tmp == 0) {
							error_.set(error::zero_divide);
							break;
						}
						v %= tmp;
					} else {
						tmp = factor_();
						if(tmp == 0) {
							error_.set(error::zero_divide);
							break;
						}
						v /= tmp;
					}
					break;
				case '<':
					ch_ = *tx_++;
					if(ch_ == '<') {
						ch_ = *tx_++;
						v <<= factor_();
					} else {
						error_.set(error::fatal);
					}
					break;
				case '>':
					ch_ = *tx_++;
					if(ch_ == '>') {
						ch_ = *tx_++;
						v <<= factor_();
					} else {
						error_.set(error::fatal);
					}
					break;
				default:
					return v;
					break;
				}
			}
			return v;
		}

		VTYPE expression_() {
			VTYPE v = term_();
			while(error_() == 0) {
				switch(ch_) {
				case ' ':
				case '\t':
					ch_ = *tx_++;
					break;
				case '+':
					ch_ = *tx_++;
					v += term_();
					break;
				case '-':
					ch_ = *tx_++;
					v -= term_();
					break;
				case '&':
					ch_ = *tx_++;
					v &= term_();
					break;
				case '^':
					ch_ = *tx_++;
					v ^= term_();
					break;
				case '|':
					ch_ = *tx_++;
					v |= term_();
					break;
				default:
					return v;
					break;
				}
			}
			return v;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		basic_arith() : tx_(nullptr), ch_(0), error_(), value_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief	シンボルの設定
			@param[in]	name シンボル名
			@param[in]	value 値
			@return 成功なら「true」
		*/
		//-----------------------------------------------------------------//
		bool set_value(const char* name, VTYPE value) {
			return symbol_.insert(name, value);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	解析を開始
			@param[in]	text	解析テキスト
			@return	文法にエラーがあった場合、「false」
		*/
		//-----------------------------------------------------------------//
		bool analize(const char* text) {

			error_.clear();

			if(text == nullptr) {
				error_.set(error::fatal);
				return false;
			}
			tx_ = text;

			ch_ = *tx_++;
			if(ch_ != 0) {
				value_ = expression_();
			} else {
				error_.set(error::fatal);
			}

			if(error_() != 0) {
				return false;
			} else if(ch_ != 0) {
				error_.set(error::fatal);
				return false;
			}
			return true;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	エラーを受け取る
			@return エラー
		*/
		//-----------------------------------------------------------------//
		const error_t& get_error() const { return error_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	結果を取得
			@return	結果
		*/
		//-----------------------------------------------------------------//
		VTYPE get() const { return value_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	() で結果を取得
			@return	結果
		*/
		//-----------------------------------------------------------------//
		VTYPE operator() () const { return value_; }
	};
}
<commit_msg>update symbol api<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	Arithmetic テンプレート @n
			※テキストの数式を展開して、計算結果を得る。@n
			演算式解析
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
#include "utils/bitset.hpp"
//#include "utils/order_map.hpp"

namespace utils {

	template <typename VTYPE, uint16_t NUM>
	class basic_symbol {

		const char* table_[NUM];
		VTYPE	value_[NUM];

		uint16_t find_(const char* name, uint8_t n) const {
			for(uint16_t i = 0; i < NUM; ++i) {
				if(n != 0) {
					if(std::strcmp(name, table_[i]) == 0) return i;
				} else {
					if(std::strncmp(name, table_[i], n) == 0) return i;
				}
			}
			return NUM;
		}
	public:
		basic_symbol() {
			for(uint16_t i = 0; i < NUM; ++i) {
				table_[i] = nullptr;
			}
		}

		bool insert(const char* name, VTYPE v) {
			for(uint16_t i = 0; i < NUM; ++i) {
				if(table_[i] == nullptr) {
					table_[i] = name;
					value_[i] = v;
					return true;
				}
			}
			return false;
		}

		bool erase(const char* name, uint8_t n = 0) {
			auto i = find_(name, n);
			if(i >= NUM) return false;
			table_[i] = nullptr;
			return true;
		}

		bool find(const char* name, uint8_t n = 0) const {
			return find_(name, n) < NUM;
		}

		bool set(const char*name, uint8_t n, VTYPE value) {
			auto i = find_(name, n);
			if(i >= NUM) return false;
			value_[i] = value;
			return true;
		}

		VTYPE get(const char* name, uint8_t n = 0) const {
			auto i = find_(name, n);
			if(i >= NUM) {
				return 0;
			}
			return value_[i];
		}
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	Arithmetic クラス
		@param[in]	VTYPE	基本型
		@param[in]	SYMBOL	シンボルクラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <typename VTYPE, class SYMBOL = basic_symbol<VTYPE, 16> >
	struct basic_arith {

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief	エラー・タイプ
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class error : uint8_t {
			fatal,				///< エラー
			number_fatal,		///< 数字の変換に関するエラー
			zero_divide,		///< ０除算エラー
			binary_fatal,		///< ２進データの変換に関するエラー
			octal_fatal,		///< ８進データの変換に関するエラー
			hexdecimal_fatal,	///< １６進データの変換に関するエラー
			num_fatal,			///< 数値の変換に関するエラー
			symbol_fatal,		///< シンボルデータの変換に関するエラー
		};

		typedef bitset<uint16_t, error> error_t;

	private:

		SYMBOL			symbol_;

		const char*		tx_;
		char			ch_;

		error_t		error_;

		VTYPE		value_;

		void skip_space_() {
			while(ch_ == ' ' || ch_ == '\t') {
				ch_ = *tx_++;
			}
		}

		VTYPE number_() {
			bool inv = false;
///			bool neg = false;
			bool point = false;
			uint32_t v = 0;
			uint32_t fp = 0;
			uint32_t fs = 1;

			skip_space_();

			// 符号、反転の判定
			if(ch_ == '-') {
				inv = true;
				ch_ = *tx_++;
			} else if(ch_ == '+') {
				ch_ = *tx_++;
//			} else if(ch_ == '!' || ch_ == '~') {
//				neg = true;
//				ch_ = *tx_++;
			}

			skip_space_();

			if(ch_ == '(') {
				v = factor_();
			} else {
				skip_space_();

				if((ch_ >= 'A' && ch_ <= 'Z') || (ch_ >= 'a' && ch_ <= 'z')) {
					const char* src = tx_ - 1;
					while(ch_ != 0) {
						ch_ = *tx_++;
						if((ch_ >= 'A' && ch_ <= 'Z') || (ch_ >= 'a' && ch_ <= 'z')) ;
						else if(ch_ >= '0' && ch_ <= '9') ;
						else if(ch_ == '_') ;
						else break;
					}
					if(!symbol_.find(src, tx_ - src)) {
						error_.set(error::symbol_fatal);
						return 0;
					}
					v = symbol_.get(src, tx_ - src);
				} else {
					while(ch_ != 0) {
						if(ch_ == '+') break;
						else if(ch_ == '-') break;
						else if(ch_ == '*') break;
						else if(ch_ == '/') break;
						else if(ch_ == '&') break;
						else if(ch_ == '^') break;
						else if(ch_ == '|') break;
						else if(ch_ == '%') break;
						else if(ch_ == ')') break;
						else if(ch_ == '<') break;
						else if(ch_ == '>') break;
						else if(ch_ == '!') break;
						else if(ch_ == '~') break;
						else if(ch_ == '.') {
							if(point) {
								error_.set(error::fatal);
								break;
							} else {
								point = true;
							}
						} else if(ch_ >= '0' && ch_ <= '9') {
							if(point) {
								fp *= 10;
								fp += ch_ - '0';
								fs *= 10;
							} else {
								v *= 10;
								v += ch_ - '0';
							}
						} else {
							error_.set(error::number_fatal);
							return 0;
						}
						ch_ = *tx_++;
					}
				}
			}

			if(inv) { v = -v; }
///			if(neg) { v = ~v; }
			if(point) {
				return static_cast<VTYPE>(v) + static_cast<VTYPE>(fp) / static_cast<VTYPE>(fs);
			} else {
				return static_cast<VTYPE>(v);
			}
		}

		VTYPE factor_() {
			VTYPE v = 0;
			if(ch_ == '(') {
				ch_ = *tx_++;
				v = expression_();
				if(ch_ == ')') {
					ch_ = *tx_++;
				} else {
					error_.set(error::fatal);
				}
			} else {
				v = number_();
			}
			return v;
		}

		VTYPE term_() {
			VTYPE v = factor_();
			VTYPE tmp;
			while(error_() == 0) {
				switch(ch_) {
				case ' ':
				case '\t':
					ch_ = *tx_++;
					break;
				case '*':
					ch_ = *tx_++;
					v *= factor_();
					break;
				case '%':
					ch_ = *tx_++;
					tmp = factor_();
					if(tmp == 0) {
						error_.set(error::zero_divide);
						break;
					}
					v /= tmp;
					break;
				case '/':
					ch_ = *tx_++;
					if(ch_ == '/') {
						ch_ = *tx_++;
						tmp = factor_();
						if(tmp == 0) {
							error_.set(error::zero_divide);
							break;
						}
						v %= tmp;
					} else {
						tmp = factor_();
						if(tmp == 0) {
							error_.set(error::zero_divide);
							break;
						}
						v /= tmp;
					}
					break;
				case '<':
					ch_ = *tx_++;
					if(ch_ == '<') {
						ch_ = *tx_++;
						v <<= factor_();
					} else {
						error_.set(error::fatal);
					}
					break;
				case '>':
					ch_ = *tx_++;
					if(ch_ == '>') {
						ch_ = *tx_++;
						v <<= factor_();
					} else {
						error_.set(error::fatal);
					}
					break;
				default:
					return v;
					break;
				}
			}
			return v;
		}

		VTYPE expression_() {
			VTYPE v = term_();
			while(error_() == 0) {
				switch(ch_) {
				case ' ':
				case '\t':
					ch_ = *tx_++;
					break;
				case '+':
					ch_ = *tx_++;
					v += term_();
					break;
				case '-':
					ch_ = *tx_++;
					v -= term_();
					break;
				case '&':
					ch_ = *tx_++;
					v &= term_();
					break;
				case '^':
					ch_ = *tx_++;
					v ^= term_();
					break;
				case '|':
					ch_ = *tx_++;
					v |= term_();
					break;
				default:
					return v;
					break;
				}
			}
			return v;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		basic_arith() : tx_(nullptr), ch_(0), error_(), value_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief	シンボルの設定
			@param[in]	name シンボル名
			@param[in]	value 値
			@return 成功なら「true」
		*/
		//-----------------------------------------------------------------//
		bool set_value(const char* name, VTYPE value) {
			if(symbol_.find(name)) {
				return symbol_.set(name, 0, value);
			} else {
				return symbol_.insert(name, value);
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	解析を開始
			@param[in]	text	解析テキスト
			@return	文法にエラーがあった場合、「false」
		*/
		//-----------------------------------------------------------------//
		bool analize(const char* text) {

			error_.clear();

			if(text == nullptr) {
				error_.set(error::fatal);
				return false;
			}
			tx_ = text;

			ch_ = *tx_++;
			if(ch_ != 0) {
				value_ = expression_();
			} else {
				error_.set(error::fatal);
			}

			if(error_() != 0) {
				return false;
			} else if(ch_ != 0) {
				error_.set(error::fatal);
				return false;
			}
			return true;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	エラーを受け取る
			@return エラー
		*/
		//-----------------------------------------------------------------//
		const error_t& get_error() const { return error_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	結果を取得
			@return	結果
		*/
		//-----------------------------------------------------------------//
		VTYPE get() const { return value_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	() で結果を取得
			@return	結果
		*/
		//-----------------------------------------------------------------//
		VTYPE operator() () const { return value_; }
	};
}
<|endoftext|>


<commit_before>/*--------------------------------------------------------------------------
File   : spi_nrf5x.cpp

Author : Hoang Nguyen Hoan          Oct. 6, 2016

Desc   : SPI implementation on nRF5x series MCU

Copyright (c) 2016, I-SYST inc., all rights reserved

Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.

For info or contributing contact : hnhoan at i-syst dot com

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

----------------------------------------------------------------------------
Modified by         Date            Description

----------------------------------------------------------------------------*/
#include "spi_nrf52.h"
#include "nrf.h"

#include "iopinctrl.h"

#ifdef NRF52
	typedef NRF_SPIM_Type	NRF5X_SPI_REG;	// Register map
#else
	typedef NRF_SPI_Type	NRF5X_SPI_REG;	// Register map
#endif

#define NRF_SPI_REG_EVENTS_READY		0x108

typedef struct {
	int SpiNo;
	SPIDEV *pSpiDev;
	uint32_t Clk;
	NRF_SPIM_Type *pReg;	// Register map
	int CsPin;				// Chip select pin, Nordic SPI has manual SS pin
} NRF5X_SPIDEV;

#define NRF5X_SPI_MAXDEV		3

static NRF5X_SPIDEV s_nRF5xDev[NRF5X_SPI_MAXDEV] = {
	{
		0, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM0_BASE, -1
	},
	{
		1, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM1_BASE, -1
	},
	{
		2, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM2_BASE, -1
	},
};

bool nRF5xSPIWaitReady(NRF5X_SPIDEV *pDev, int32_t Timeout)
{
	uint32_t val = 0;

	do {
		val = *(uint32_t*)((uint32_t)pDev->pReg + NRF_SPI_REG_EVENTS_READY);
		if (val)
			return true;
	} while (Timeout-- > 0);

	return false;
}

bool nRF5xSPIWaitDMA(NRF5X_SPIDEV *pDev, uint32_t Timeout)
{
	uint32_t val = 0;

	do {
		if (pDev->pReg->EVENTS_END)
		{
			pDev->pReg->EVENTS_END = 0; // clear event
			return true;
		}
	} while (Timeout-- > 0);

	return false;
}

int nRF5xSPIGetRate(SERINTRFDEV *pDev)
{
	int rate = 0;

	if (pDev && pDev->pDevData)
		rate = ((NRF5X_SPIDEV*)pDev->pDevData)->pSpiDev->Cfg.Rate;

	return rate;
}

// Set data rate in bits/sec (Hz)
// return actual rate
int nRF5xSPISetRate(SERINTRFDEV *pDev, int DataRate)
{
	NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;

	if (DataRate < 250000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K125;
		dev->Clk = 125000;
	}
	else if (DataRate < 500000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K250;
		dev->Clk = 250000;
	}
	else if (DataRate < 1000000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K500;
		dev->Clk = 500000;
	}
	else if (DataRate < 2000000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M1;
		dev->Clk = 1000000;
	}
	else if (DataRate < 4000000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M2;
		dev->Clk = 2000000;
	}
	else if (DataRate < 8000000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M4;
		dev->Clk = 4000000;
	}
	else
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M8;
		dev->Clk = 8000000;
	}

	dev->pSpiDev->Cfg.Rate = dev->Clk;

	return dev->pSpiDev->Cfg.Rate;
}

void nRF5xSPIDisable(SERINTRFDEV *pDev)
{
	NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev->pDevData;

	dev->pReg->ENABLE = (SPIM_ENABLE_ENABLE_Disabled << SPIM_ENABLE_ENABLE_Pos);
}

void nRF5xSPIEnable(SERINTRFDEV *pDev)
{
	NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev->pDevData;

	dev->pReg->ENABLE = (SPIM_ENABLE_ENABLE_Enabled << SPIM_ENABLE_ENABLE_Pos);
}

// Initial receive
bool nRF5xSPIStartRx(SERINTRFDEV *pDev, int DevAddr)
{
	NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;

	IOPinClear(0, dev->CsPin);

	return true;
}

// Receive Data only, no Start/Stop condition
int nRF5xSPIRxData(SERINTRFDEV *pDev, uint8_t *pBuff, int BuffLen)
{
	NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;

	dev->pReg->RXD.PTR = (uint32_t)pBuff;
	dev->pReg->RXD.MAXCNT = BuffLen;
	dev->pReg->RXD.LIST = 0; // Scatter/Gather not supported
	dev->pReg->TXD.PTR = 0;
	dev->pReg->TXD.MAXCNT = 0;
	dev->pReg->TXD.LIST = 0; // Scatter/Gather not supported
	dev->pReg->EVENTS_END = 0;
	dev->pReg->TASKS_START = 1;

	nRF5xSPIWaitDMA(dev, 100000);

	return dev->pReg->RXD.AMOUNT;
}

// Stop receive
void nRF5xSPIStopRx(SERINTRFDEV *pDev)
{
	NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;

	IOPinSet(0, dev->CsPin);
}

// Initiate transmit
bool nRF5xSPIStartTx(SERINTRFDEV *pDev, int DevAddr)
{
	NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;

	IOPinClear(0, dev->CsPin);

	return true;
}

// Transmit Data only, no Start/Stop condition
int nRF5xSPITxData(SERINTRFDEV *pDev, uint8_t *pData, int DataLen)
{
	NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;

	dev->pReg->RXD.PTR = 0;
	dev->pReg->RXD.MAXCNT = 0;
	dev->pReg->RXD.LIST = 0; // Scatter/Gather not supported
	dev->pReg->TXD.PTR = (uint32_t)pData;
	dev->pReg->TXD.MAXCNT = DataLen;
	dev->pReg->TXD.LIST = 0; // Scatter/Gather not supported
	dev->pReg->EVENTS_END = 0;
	dev->pReg->TASKS_START = 1;

	nRF5xSPIWaitDMA(dev, 100000);

	return dev->pReg->TXD.AMOUNT;
}

// Stop transmit
void nRF5xSPIStopTx(SERINTRFDEV *pDev)
{
	NRF5X_SPIDEV *dev = (NRF5X_SPIDEV *)pDev-> pDevData;

	IOPinSet(0, dev->CsPin);
}

bool SPIInit(SPIDEV *pDev, const SPICFG *pCfgData)
{
	NRF5X_SPI_REG *reg;
	uint32_t err_code;
	uint32_t cfgreg = 0;

	if (pCfgData->DevNo < 0 || pCfgData->DevNo > 2)
		return false;

	// Get the correct register map
	reg = s_nRF5xDev[pCfgData->DevNo].pReg;

	// Configure I/O pins
	IOPinCfg(pCfgData->IOPinMap, SPI_MAX_NB_IOPIN);

	reg->PSEL.SCK = pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo;
	reg->PSEL.MISO = pCfgData->IOPinMap[SPI_MISO_IOPIN_IDX].PinNo;
	reg->PSEL.MOSI = pCfgData->IOPinMap[SPI_MOSI_IOPIN_IDX].PinNo;

	s_nRF5xDev[pCfgData->DevNo].CsPin = pCfgData->IOPinMap[SPI_SS_IOPIN_IDX].PinNo;
	IOPinSet(0, s_nRF5xDev[pCfgData->DevNo].CsPin);

	if (pCfgData->BitOrder == SPIDATABIT_LSB)
	{
		cfgreg |= SPIM_CONFIG_ORDER_LsbFirst;
	}
	else
	{
		cfgreg |= SPIM_CONFIG_ORDER_MsbFirst;
	}

	if (pCfgData->DataPhase == SPIDATAPHASE_SECOND_CLK)
	{
		cfgreg |= (SPIM_CONFIG_CPHA_Trailing   << SPIM_CONFIG_CPHA_Pos);
	}
	else
	{
		cfgreg |= (SPIM_CONFIG_CPHA_Leading    << SPIM_CONFIG_CPHA_Pos);
	}

	//config.irq_priority = APP_IRQ_PRIORITY_LOW;

	if (pCfgData->ClkPol == SPICLKPOL_LOW)
	{
		cfgreg |= (SPI_CONFIG_CPOL_ActiveLow  << SPI_CONFIG_CPOL_Pos);
		IOPinSet(0, pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo);
	}
	else
	{
		cfgreg |= (SPI_CONFIG_CPOL_ActiveHigh << SPI_CONFIG_CPOL_Pos);
		IOPinClear(0, pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo);
	}

	reg->CONFIG = cfgreg;

	reg->ORC = 0xFF;

	pDev->Cfg = *pCfgData;
	s_nRF5xDev[pCfgData->DevNo].pSpiDev  = pDev;
	pDev->SerIntrf.pDevData = (void*)&s_nRF5xDev[pCfgData->DevNo];

	nRF5xSPISetRate(&pDev->SerIntrf, pCfgData->Rate);

	pDev->SerIntrf.Disable = nRF5xSPIDisable;
	pDev->SerIntrf.Enable = nRF5xSPIEnable;
	pDev->SerIntrf.GetRate = nRF5xSPIGetRate;
	pDev->SerIntrf.SetRate = nRF5xSPISetRate;
	pDev->SerIntrf.StartRx = nRF5xSPIStartRx;
	pDev->SerIntrf.RxData = nRF5xSPIRxData;
	pDev->SerIntrf.StopRx = nRF5xSPIStopRx;
	pDev->SerIntrf.StartTx = nRF5xSPIStartTx;
	pDev->SerIntrf.TxData = nRF5xSPITxData;
	pDev->SerIntrf.StopTx = nRF5xSPIStopTx;
	pDev->SerIntrf.IntPrio = pCfgData->IntPrio;
	pDev->SerIntrf.EvtCB = pCfgData->EvtCB;

	reg->ENABLE = (SPIM_ENABLE_ENABLE_Enabled << SPIM_ENABLE_ENABLE_Pos);
}

<commit_msg>remove unsused code.  Function renaming<commit_after>/*--------------------------------------------------------------------------
File   : spi_nrf5x.cpp

Author : Hoang Nguyen Hoan          Oct. 6, 2016

Desc   : SPI implementation on nRF5x series MCU

Copyright (c) 2016, I-SYST inc., all rights reserved

Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.

For info or contributing contact : hnhoan at i-syst dot com

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

----------------------------------------------------------------------------
Modified by         Date            Description

----------------------------------------------------------------------------*/
#include "nrf.h"

#include "spi_nrf52.h"
#include "iopinctrl.h"

typedef struct {
	int DevNo;
	SPIDEV *pSpiDev;
	uint32_t Clk;
	NRF_SPIM_Type *pReg;	// Register map
	int CsPin;				// Chip select pin, Nordic SPI has manual SS pin
} NRF52_SPIDEV;

#define NRF52_SPI_MAXDEV		3

static NRF52_SPIDEV s_nRF52SPIDev[NRF52_SPI_MAXDEV] = {
	{
		0, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM0_BASE, -1
	},
	{
		1, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM1_BASE, -1
	},
	{
		2, NULL, 0, (NRF_SPIM_Type*)NRF_SPIM2_BASE, -1
	},
};

bool nRF52SPIWaitDMA(NRF52_SPIDEV *pDev, uint32_t Timeout)
{
	uint32_t val = 0;

	do {
		if (pDev->pReg->EVENTS_END)
		{
			pDev->pReg->EVENTS_END = 0; // clear event
			return true;
		}
	} while (Timeout-- > 0);

	return false;
}

int nRF52SPIGetRate(SERINTRFDEV *pDev)
{
	int rate = 0;

	if (pDev && pDev->pDevData)
		rate = ((NRF52_SPIDEV*)pDev->pDevData)->pSpiDev->Cfg.Rate;

	return rate;
}

// Set data rate in bits/sec (Hz)
// return actual rate
int nRF52SPISetRate(SERINTRFDEV *pDev, int DataRate)
{
	NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;

	if (DataRate < 250000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K125;
		dev->Clk = 125000;
	}
	else if (DataRate < 500000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K250;
		dev->Clk = 250000;
	}
	else if (DataRate < 1000000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_K500;
		dev->Clk = 500000;
	}
	else if (DataRate < 2000000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M1;
		dev->Clk = 1000000;
	}
	else if (DataRate < 4000000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M2;
		dev->Clk = 2000000;
	}
	else if (DataRate < 8000000)
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M4;
		dev->Clk = 4000000;
	}
	else
	{
		dev->pReg->FREQUENCY = SPIM_FREQUENCY_FREQUENCY_M8;
		dev->Clk = 8000000;
	}

	dev->pSpiDev->Cfg.Rate = dev->Clk;

	return dev->pSpiDev->Cfg.Rate;
}

void nRF52SPIDisable(SERINTRFDEV *pDev)
{
	NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev->pDevData;

	dev->pReg->ENABLE = (SPIM_ENABLE_ENABLE_Disabled << SPIM_ENABLE_ENABLE_Pos);
}

void nRF52SPIEnable(SERINTRFDEV *pDev)
{
	NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev->pDevData;

	dev->pReg->ENABLE = (SPIM_ENABLE_ENABLE_Enabled << SPIM_ENABLE_ENABLE_Pos);
}

// Initial receive
bool nRF52SPIStartRx(SERINTRFDEV *pDev, int DevAddr)
{
	NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;

	IOPinClear(0, dev->CsPin);

	return true;
}

// Receive Data only, no Start/Stop condition
int nRF52SPIRxData(SERINTRFDEV *pDev, uint8_t *pBuff, int BuffLen)
{
	NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;

	dev->pReg->RXD.PTR = (uint32_t)pBuff;
	dev->pReg->RXD.MAXCNT = BuffLen;
	dev->pReg->RXD.LIST = 0; // Scatter/Gather not supported
	dev->pReg->TXD.PTR = 0;
	dev->pReg->TXD.MAXCNT = 0;
	dev->pReg->TXD.LIST = 0; // Scatter/Gather not supported
	dev->pReg->EVENTS_END = 0;
	dev->pReg->TASKS_START = 1;

	nRF52SPIWaitDMA(dev, 100000);

	return dev->pReg->RXD.AMOUNT;
}

// Stop receive
void nRF52SPIStopRx(SERINTRFDEV *pDev)
{
	NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;

	IOPinSet(0, dev->CsPin);
}

// Initiate transmit
bool nRF52SPIStartTx(SERINTRFDEV *pDev, int DevAddr)
{
	NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;

	IOPinClear(0, dev->CsPin);

	return true;
}

// Transmit Data only, no Start/Stop condition
int nRF52SPITxData(SERINTRFDEV *pDev, uint8_t *pData, int DataLen)
{
	NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;

	dev->pReg->RXD.PTR = 0;
	dev->pReg->RXD.MAXCNT = 0;
	dev->pReg->RXD.LIST = 0; // Scatter/Gather not supported
	dev->pReg->TXD.PTR = (uint32_t)pData;
	dev->pReg->TXD.MAXCNT = DataLen;
	dev->pReg->TXD.LIST = 0; // Scatter/Gather not supported
	dev->pReg->EVENTS_END = 0;
	dev->pReg->TASKS_START = 1;

	nRF52SPIWaitDMA(dev, 100000);

	return dev->pReg->TXD.AMOUNT;
}

// Stop transmit
void nRF52SPIStopTx(SERINTRFDEV *pDev)
{
	NRF52_SPIDEV *dev = (NRF52_SPIDEV *)pDev-> pDevData;

	IOPinSet(0, dev->CsPin);
}

bool SPIInit(SPIDEV *pDev, const SPICFG *pCfgData)
{
	NRF_SPIM_Type *reg;
	uint32_t err_code;
	uint32_t cfgreg = 0;

	if (pCfgData->DevNo < 0 || pCfgData->DevNo >= NRF52_SPI_MAXDEV)
		return false;

	// Get the correct register map
	reg = s_nRF52SPIDev[pCfgData->DevNo].pReg;

	// Configure I/O pins
	IOPinCfg(pCfgData->IOPinMap, SPI_MAX_NB_IOPIN);

	reg->PSEL.SCK = pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo;
	reg->PSEL.MISO = pCfgData->IOPinMap[SPI_MISO_IOPIN_IDX].PinNo;
	reg->PSEL.MOSI = pCfgData->IOPinMap[SPI_MOSI_IOPIN_IDX].PinNo;

	s_nRF52SPIDev[pCfgData->DevNo].CsPin = pCfgData->IOPinMap[SPI_SS_IOPIN_IDX].PinNo;
	IOPinSet(0, s_nRF52SPIDev[pCfgData->DevNo].CsPin);

	if (pCfgData->BitOrder == SPIDATABIT_LSB)
	{
		cfgreg |= SPIM_CONFIG_ORDER_LsbFirst;
	}
	else
	{
		cfgreg |= SPIM_CONFIG_ORDER_MsbFirst;
	}

	if (pCfgData->DataPhase == SPIDATAPHASE_SECOND_CLK)
	{
		cfgreg |= (SPIM_CONFIG_CPHA_Trailing   << SPIM_CONFIG_CPHA_Pos);
	}
	else
	{
		cfgreg |= (SPIM_CONFIG_CPHA_Leading    << SPIM_CONFIG_CPHA_Pos);
	}

	//config.irq_priority = APP_IRQ_PRIORITY_LOW;

	if (pCfgData->ClkPol == SPICLKPOL_LOW)
	{
		cfgreg |= (SPI_CONFIG_CPOL_ActiveLow  << SPI_CONFIG_CPOL_Pos);
		IOPinSet(0, pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo);
	}
	else
	{
		cfgreg |= (SPI_CONFIG_CPOL_ActiveHigh << SPI_CONFIG_CPOL_Pos);
		IOPinClear(0, pCfgData->IOPinMap[SPI_SCK_IOPIN_IDX].PinNo);
	}

	reg->CONFIG = cfgreg;

	reg->ORC = 0xFF;

	pDev->Cfg = *pCfgData;
	s_nRF52SPIDev[pCfgData->DevNo].pSpiDev  = pDev;
	pDev->SerIntrf.pDevData = (void*)&s_nRF52SPIDev[pCfgData->DevNo];

	nRF52SPISetRate(&pDev->SerIntrf, pCfgData->Rate);

	pDev->SerIntrf.Disable = nRF52SPIDisable;
	pDev->SerIntrf.Enable = nRF52SPIEnable;
	pDev->SerIntrf.GetRate = nRF52SPIGetRate;
	pDev->SerIntrf.SetRate = nRF52SPISetRate;
	pDev->SerIntrf.StartRx = nRF52SPIStartRx;
	pDev->SerIntrf.RxData = nRF52SPIRxData;
	pDev->SerIntrf.StopRx = nRF52SPIStopRx;
	pDev->SerIntrf.StartTx = nRF52SPIStartTx;
	pDev->SerIntrf.TxData = nRF52SPITxData;
	pDev->SerIntrf.StopTx = nRF52SPIStopTx;
	pDev->SerIntrf.IntPrio = pCfgData->IntPrio;
	pDev->SerIntrf.EvtCB = pCfgData->EvtCB;

	reg->ENABLE = (SPIM_ENABLE_ENABLE_Enabled << SPIM_ENABLE_ENABLE_Pos);
}

<|endoftext|>


<commit_before><commit_msg>Forgot to remove debugging logging<commit_after><|endoftext|>


<commit_before><commit_msg>Improve gradient-descent algorithm to avoid tiny blocks.<commit_after><|endoftext|>