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

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

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

#include "Seaio440driver.h"
#include "EngLog.h"

CSeaIO440Module::CSeaIO440Module(CSeaMaxLin *ModuleDriverPtr)
{
    mModuleDriverPtr = ModuleDriverPtr;
    mModuleType = EXT_IO_TYPE_440;
	mOutputBuffer = 0;
}

CSeaIO440Module::~CSeaIO440Module()
{
//	qDebug("clear outputs");
//	quint32 out = 0;
//	SetOutput(out);
}

unsigned int CSeaIO440Module::SetOutput(unsigned char *OutputBuffer)
{
    if(mModuleDriverPtr == 0)
        return RET_ERROR;

	if(OutputBuffer == 0)
        return RET_ERROR;

    mSeaIOModuleType = COILS;    //Output type
    mRegisterStart = 1;             //Start with input 1
    mRegisterRange = 32;            //Set all the 32 outputs

    int RET = mModuleDriverPtr->Write(mModuleAddress,mSeaIOModuleType,mRegisterStart,mRegisterRange,&OutputBuffer[0]);
    if(RET < 0)
    {
        CEngLog::instance()->AddLogString(QString("SeaIO440 Modbus write FAILED: %d").arg(RET));
    }

    return RET_OK;
}

unsigned int CSeaIO440Module::SetOutput(quint32 buffer)
{
	unsigned char buf[4];
	memcpy(&buf[0],&buffer,4);
	mOutputBuffer = buffer;

	SetOutput(buf);
    return RET_OK;
}

unsigned int CSeaIO440Module::SetOutputFlags(quint32 FlagMask)
{

	mOutputBuffer |= FlagMask;
	SetOutput(mOutputBuffer);

    return RET_OK;
}

unsigned int CSeaIO440Module::ClearOutputFlags(quint32 FlagMask)
{
	mOutputBuffer &= ~FlagMask;
	SetOutput(mOutputBuffer);

    return RET_OK;
}

unsigned int CSeaIO440Module::ToggleOutputFlags(quint32 FlagMask)
{
	mOutputBuffer ^= FlagMask;
	SetOutput(mOutputBuffer);

	return RET_OK;
}
