#include "ModbusSlave.h"


CModbusSlave::CModbusSlave(CModbusRepository *Repo) :
    CModbusBackend(Repo)
{
     mModbusServer = new QTcpServer();
    connect(mModbusServer,SIGNAL(newConnection()),this,SLOT(NewModbusConnection()));
    mModbusMode = MODBUS_SLAVE_MODE;
    mServerPort = -1;
}

CModbusSlave::~CModbusSlave()
{
    delete mModbusServer;
}

int CModbusSlave::SetServerPort(int port)
{
    mServerPort = port;
    return 1;
}

bool CModbusSlave::IsSlaveServerOpened()
{
    return mModbusServer->isListening();
}

int CModbusSlave::StartSlaveServer(int port)
{
    mServerPort = port;
    mModbusServer->listen(QHostAddress::Any,port);
    qDebug("Slave server started on port %d",port);
    return 1;
}

int CModbusSlave::ToggleServerState()
{

    if(mModbusServer->isListening())
    {
        StopSlaveServer();
    }
    else
    {
        if(mServerPort < 0)
        {
            qDebug("Error, trying to toggle SEI server on invalid port");
            return 0;
        }

        StartSlaveServer(mServerPort);
    }
    return 1;
}

int CModbusSlave::StopSlaveServer()
{
    if(mModbusTCPSocketHandle != 0)
    {
        mModbusTCPSocketHandle->disconnectFromHost();
    }

    mModbusServer->close();
    return 1;
}

void CModbusSlave::NewModbusConnection()
{
    mModbusTCPSocketHandle = mModbusServer->nextPendingConnection();
    if(mModbusTCPSocketHandle != 0)
    {
        mDataLinkValid = true;
        connect(mModbusTCPSocketHandle,SIGNAL(readyRead()),this,SLOT(ModbusDataReady()));
        connect(mModbusTCPSocketHandle,SIGNAL(disconnected()),this,SLOT(ModbusSocketDisconnected()));
        emit ModbusSlaveConnected(this);
        qDebug("Slave: Connection with Master established");
    }
}

void CModbusSlave::ModbusSocketDisconnected()
{
    qDebug("Modbus link disconnected");
    mDataLinkValid = false;
    emit ModbusSlaveDisconnected(this);
}

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

//    qDebug("SEI Database updated with ZT data...");
    emit ModbusSlaveRepoUpdated();


}

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

}
