#include "PIHistorianSession.h"
#include "ZTLog.h"

CPIHistorianSession::CPIHistorianSession(CModbusRepository *Repo, int DevID) :
    CModbusBackend(Repo)
{
    mDeviceID = DevID;
    mModbusMode = MODBUS_SLAVE_MODE;
}

CPIHistorianSession::~CPIHistorianSession()
{

}

int CPIHistorianSession::OpenSession(QTcpSocket *ModbusSocket)
{
    mModbusTCPSocketHandle = ModbusSocket;
    connect(mModbusTCPSocketHandle,SIGNAL(readyRead()),this,SLOT(ModbusDataReady()));
    connect(mModbusTCPSocketHandle,SIGNAL(disconnected()),this,SLOT(HistorianConnectionLost()));

    CZTLog::instance()->AddLogString(QString("Session avec Historien PI établie. IP locale [%1] -  IP HPC [%2]").arg(mModbusTCPSocketHandle->localAddress().toString()).arg(mModbusTCPSocketHandle->peerAddress().toString()),true);

    return RET_OK;
}

int CPIHistorianSession::CloseSession()
{
    disconnect(mModbusTCPSocketHandle,SIGNAL(readyRead()),this,SLOT(ModbusDataReady()));
    CZTLog::instance()->AddLogString(QString("Session avec Historien PI fermée IP locale [%1] -  IP HPC [%2]").arg(mModbusTCPSocketHandle->localAddress().toString()).arg(mModbusTCPSocketHandle->peerAddress().toString()),true);

    mModbusTCPSocketHandle->close();

    return RET_OK;
}

void CPIHistorianSession::RegistersDatabaseUpdated(quint16 StartAddress, quint16 Length)
{

}

void CPIHistorianSession::ModbusRequestException(quint8 ExceptionCode, quint8 FctCode)
{

}

void CPIHistorianSession::HistorianConnectionLost()
{
    CZTLog::instance()->AddLogString(QString("Session avec Historien PI fermée (connexion perdue)."));
    emit PIHistorianSessionClosed(this);
}

