/*******************************************************************************
*                                                                              *
* Société de Transports de Montréal.                                    	   *
* 2012                                                                         *
*                                                                              *
* Projet Zones Tests                                                           *
*                                                                              *
*                                                                              *
*                                                                              *
*******************************************************************************/
/*
    Description:
    Pilote d'interface avec un module d'entrées discrètes SEAIO430
	Hérite de CInputModule et réimplémente les fonctions virtuelles d'accès aux
	données du module d'entrées externes.
    
*/

/* ************************************************************************** */
/* Revision:
### 20121213 JFM
    Verision d'origine.
    
### YYYYMMDD Description du besoin ou du bug
    Description du changement.
 */

/* ************************************************************************** */

#include "Seaio430driver.h"
#include <string.h>
#include <QDebug>
#include "EngLog.h"

CSeaIO430Module::CSeaIO430Module(CSeaMaxLin *ModuleDriverPtr)
{
    mModuleDriverPtr = ModuleDriverPtr;
    mModuleType = EXT_IO_TYPE_430;
}

unsigned int CSeaIO430Module::GetInputs(unsigned char *DataBuf)
{
    if(DataBuf == 0)
        return RET_ERROR;

    if(ReadInputs() == RET_ERROR)
        return RET_ERROR;

	memcpy(DataBuf,mInputBuffer,4/*sizeof(mInputBuffer)*/);
    return RET_OK;
}

unsigned int CSeaIO430Module::GetInputs()
{
	unsigned int Buf;

	mMutex.lock();
	ReadInputs();
	memcpy(&Buf,mInputBuffer,sizeof(mInputBuffer));
	mMutex.unlock();
	return Buf;
}

unsigned int CSeaIO430Module::GetInputBuf()
{
	unsigned int Buf;

	mMutex.lock();
	ReadInputs();
	memcpy(&Buf,mInputBuffer,sizeof(mInputBuffer));
	mMutex.unlock();
	return Buf;
}

//unsigned char * CSeaIO430Module::GetInputs()
//{
//    return &mInputBuffer[0];
//}

unsigned int CSeaIO430Module::ReadInputs()
{
    if(mModuleDriverPtr == 0)
        return RET_ERROR;

    mSeaIOModuleType = D_INPUTS;    //Input type
    mRegisterStart = 1;             //Start with input 1
    mRegisterRange = 32;            //Read all the 32 inputs

    int RET = mModuleDriverPtr->Read(mModuleAddress,mSeaIOModuleType,mRegisterStart,mRegisterRange,&mInputBuffer[0]);
    if(RET < 0)
    {
        CEngLog::instance()->AddLogString(QString("SeaIO430 module read FAILED: %d").arg(RET));
    }

    return RET_OK;

}
unsigned int CSeaIO430Module::ReadAndGetInputs(unsigned char *DataBuf)
{
    if(ReadInputs() == 0)
        return RET_ERROR;

    memcpy(DataBuf,mInputBuffer,sizeof(mInputBuffer));
    return RET_OK;
}
