#include "ModbusMaster.h"
#include <QTcpSocket>
#include "ModbusCCDefs.h"

CModbusMaster::CModbusMaster(CModbusRepository *Repo, int ModbusPort, int DevID):
    CModbusBackend(Repo)
{
   // connect(mModbusTCPSocketHandle,SIGNAL(readyRead()),this,SLOT(ModbusDataReady()));
    mModbusMode = MODBUS_MASTER_MODE;
    mModbusPort = ModbusPort;
    mDeviceID = DevID;

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

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

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

    mModbusTCPSocketHandle->connectToHost(SlaveIP,SlavePort);

    return RET_OK;
}

int CModbusMaster::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 CModbusMaster::SocketConnected()
{
    emit ModbusMasterConnected(this);
    qDebug("Master: Connection established with slave");
}

void CModbusMaster::SocketDisconnected()
{
    ModbusLinkDisconnected();
    emit ModbusMasterDisconnected(this);
}

int CModbusMaster::ReadModbusRegisters()
{
    //return SendReadHoldingRegistersRequest(ZT_DATA_BASE_REGISTER_ADDRESS,4);    //Read all 3 registers from ZT (2000 - 2003)
    return RET_OK;
}


void CModbusMaster::RegistersDatabaseUpdated(quint16 StartAddress, quint16 Length)
{
    Q_UNUSED(StartAddress)
    Q_UNUSED(Length)

    emit ModbusMasterRepositoryUpdated();
    qDebug("Database updated with ZT data...");
}

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

int CModbusMaster::SendAN1ToZT()
{
    //return SendWriteHoldingRegistersRequest(CC_AN1_REGISTER_ADDRESS,1);
    //return SendWriteSingleRegisterRequest(CC_AN1_REGISTER_ADDRESS);
    return RET_OK;
}

int CModbusMaster::SendAN2ToZT()
{
    //return SendWriteHoldingRegistersRequest(CC_AN2_REGISTER_ADDRESS,1);
    //return SendWriteSingleRegisterRequest(CC_AN2_REGISTER_ADDRESS);
    return RET_OK;
}
