// errortestthread.cpp: Implementierung der Klasse ErrorTestThread.
//
//////////////////////////////////////////////////////////////////////

#include "errortestthread.h"
#include "motorthreaddialog.h"
#include "threadevent.h"
#include "amcdefs.h"
#include "amcframegrabber.h"
#include "amcmirrorpanel.h"
#include "amcmotor.h"
#include "amcserialport.h"
#include "amcerror.h"
#include "amcerrors.h"
#include "videospot.h"
#include <qmessagebox.h>
#include <qevent.h>
#include <qthread.h>
#include <qstring.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MAX(a,b) ((a>b) ? a : b )

extern AMCSerialPort* g_pPort[];
extern AMCFrameGrabber* g_pFG;

//////////////////////////////////////////////////////////////////////
// Konstruktion/Destruktion
//////////////////////////////////////////////////////////////////////

ErrorTestThread::ErrorTestThread( QObject* p_pReceiver )
	: m_pPanel( NULL ), m_pReceiver( p_pReceiver ), m_zOn( false )
{
}

ErrorTestThread::~ErrorTestThread()
{
}

void ErrorTestThread::run()
{
	QString qsMsg;
	qsMsg.sprintf( "Panel (%d,%d) at Port: %d, Box:%d, Driver:%d",
			           m_pPanel->i(), m_pPanel->j(),
                 m_pPanel->port(), m_pPanel->box(), m_pPanel->driver() );
	QThread::postEvent( m_pReceiver, new ThreadEvent( qsMsg ) );

	QTime t;
	t.start();                          // start clock

	// We use only one motor instance and reuse it for each panel
	AMCSerialPort* pPort = g_pPort[ m_pPanel->port()-1 ];
	AMCMotor* pMotor = new AMCMotor( pPort );
  pMotor->setPortNum( m_pPanel->port() );

  int iTemp, iHum, iPowerI, iPowerV, iSecondV, iLogicV;
	try
	{
		pMotor->unselectBox();
		pMotor->selectBox( m_pPanel->box() );
		pMotor->getInfo( &iTemp, &iHum, &iPowerI, &iPowerV, &iSecondV, &iLogicV );
		pMotor->selectDriver( m_pPanel->driver() );
		pMotor->getFrequency();
		pMotor->switchLaser( true );
		m_pPanel->setLaserOn( true );
		pMotor->switchLaser( false );
		m_pPanel->setLaserOn( false );
	}
	catch( AMCError& e )
  {
    e.setPanel( m_pPanel->i(), m_pPanel->j() );
		qsMsg.sprintf( "AMCError: Panel (%d,%d) Port: %d, Box:%d, Driver:%d -- ",
			       				m_pPanel->i(), m_pPanel->j(),
										m_pPanel->port(), m_pPanel->box(), m_pPanel->driver() );
		QThread::postEvent( m_pReceiver, new ThreadErrorEvent( qsMsg, e ) );

    try
		{
			pMotor->resetBox();
			pMotor->unselectBox();
			pMotor->selectBox( m_pPanel->box() );
			pMotor->selectDriver( m_pPanel->driver() );
			pMotor->switchLaser( false );
			m_pPanel->setLaserOn( false );
		}
    catch( AMCError& e2 ){}
	}
	delete pMotor;


//	qsMsg.sprintf( "Time: %dms", t.elapsed() );
//	QThread::postEvent( m_pReceiver, new ThreadEvent( qsMsg ) );
}

void ErrorTestThread::setPanel(AMCMirrorPanel* p_pPanel)
{
	m_pPanel = p_pPanel;
}

