#include "ModbusZTMaster.h"
#include <QTcpSocket>
#include "ProtocolDefs.h"

CModbusZTMaster::CModbusZTMaster(CModbusRepository *Repo):
    CModbusBackend(Repo)
{
   // connect(mModbusTCPSocketHandle,SIGNAL(readyRead()),this,SLOT(ModbusDataReady()));
    mModbusMode = MODBUS_MASTER_MODE;

    mModbusTCPSocketHandle = new QTcpSocket();
    connect(mModbusTCPSocketHandle,SIGNAL(readyRead()),this,SLOT(ModbusDataReady()));
    connect(mModbusTCPSocketHandle,SIGNAL(disconnected()),this,SLOT(SocketDisconnected()));
    connect(mModbusTCPSocketHandle,SIGNAL(connected()),this,SLOT(SocketConnected()));

}

CModbusZTMaster::~CModbusZTMaster()
{
    if(mModbusTCPSocketHandle->state() != QAbstractSocket::UnconnectedState)
    {
        mModbusTCPSocketHandle->disconnectFromHost();
        mModbusTCPSocketHandle->waitForDisconnected(1000);
    }
    delete mModbusTCPSocketHandle;
}

int CModbusZTMaster::ConnectToSlave(QString SlaveIP, int SlavePort)
{
    if(mModbusTCPSocketHandle->state() != QAbstractSocket::UnconnectedState)
    {
        return RET_ERROR;
    }

    mModbusTCPSocketHandle->connectToHost(SlaveIP,SlavePort);

    return RET_OK;
}

int CModbusZTMaster::DisconnectFromSlave()
{
    if(mModbusTCPSocketHandle->state() != QAbstractSocket::ConnectedState)
    {
        qDebug("Trying to disconnect a non connected socket");
        mModbusTCPSocketHandle->disconnectFromHost();
        return 0;
    }

    qDebug("Requesting Disconnection...");
    mModbusTCPSocketHandle->disconnectFromHost();
    return 1;
}

void CModbusZTMaster::SocketConnected()
{
    emit ModbusMasterConnected(this);
    qDebug("Master: Connection established with slave");
}

void CModbusZTMaster::SocketDisconnected()
{
    ModbusLinkDisconnected();
    emit ModbusMasterDisconnected(this);
    mModbusTCPSocketHandle->flush();
}

int CModbusZTMaster::ReadModbusRegisters()
{
    return SendReadHoldingRegistersRequest(SEI_MODBUS_SEI_DATA_BASE_REG,SEI_MODBUS_SEI_TABLE_DATA_SIZE);    //Read all registers from ZT (2037 - 2038)
}

int CModbusZTMaster::SendModbusRegisters()
{
    return SendWriteHoldingRegistersRequest(SEI_MODBUS_ZT_DATA_BASE_REG,SEI_MODBUS_ZT_TABLE_DATA_SIZE);
}

void CModbusZTMaster::RegistersDatabaseUpdated(quint16 StartAddress, quint16 Length)
{
    emit ModbusMasterRepositoryUpdated();
//    qDebug("Database updated with ZT data...");
}

void CModbusZTMaster::ModbusResponseException(quint8 ExceptionCode, quint8 FctCode)
{
    qDebug("Modbus MASTER exception: code:%d  Fct:%d",ExceptionCode,FctCode);
}

