#include "LoraModuleInterface.h"

CLoraModuleInterface::CLoraModuleInterface()
{
    connect(&mLoraModuleIFSerialPort,SIGNAL(readyRead()),this,SLOT(NewLoraModuleIFDataReady()));

    mLoraModuleIFStatusTimer = new QTimer();
    mLoraModuleIFStatusTimer->setSingleShot(false);
    mLoraModuleIFStatusTimer->setInterval(1000);
    mLoraModuleIFStatusTimer->start();

    connect(mLoraModuleIFStatusTimer,SIGNAL(timeout()),this,SLOT(LoraModuleStatusTimerExpired()));
}

CLoraModuleInterface::~CLoraModuleInterface()
{
    delete mLoraModuleIFStatusTimer;
}


//This the handling of the Microcontroller (LoraModuleInterface)
int CLoraModuleInterface::NewFrameReceived(int DeviceID, int DeviceAddress, int MessageID, int DataSize, QByteArray Data)
{
    return RET_OK;
}

//This is to answer to CChaletDevice requests
int CLoraModuleInterface::SendNetworkMessage(int DeviceID, int DeviceAddress, int MessageID, int DataSize, QByteArray *Data)
{
    return RET_OK;
}



void CLoraModuleInterface::LoraModuleStatusTimerExpired()
{

}

int CLoraModuleInterface::SetLoraModuleInterfaceParameters(QString ComPort, qint32 BaudRate)
{
    mLoraModuleIFComPortName = ComPort;
    mLoraModuleIFComPortBaudRate = BaudRate;


    if(mLoraModuleIFSerialPort.isOpen())
    {
        mLoraModuleIFSerialPort.close();
    }

    mLoraModuleIFSerialPort.setPortName(mLoraModuleIFComPortName);
    if(mLoraModuleIFSerialPort.setBaudRate(mLoraModuleIFComPortBaudRate) == false)
    {
        qDebug("Invalid Lora Device serial port baud rate...");
    }

    //The other serial port parameters (parity, stop bits, data bits) are all set to mentally sane default values so no need to set them.
    if(mLoraModuleIFSerialPort.open(QIODevice::ReadWrite) == false)
    {
        qDebug("Could not open Lora device port");
        return RET_ERROR;
    }

    qDebug("Lora serial port opened");
    return RET_OK;



    return RET_OK;
}

void CLoraModuleInterface::NewLoraModuleIFDataReady()
{
    QByteArray NewData = mLoraModuleIFSerialPort.readAll();

    AnalyzeRxBuffer(NewData);
}
