#include "ChaletLoraDevice.h"
#include <QSerialPortInfo>
#include <QObject>

CChaletLoraDevice::CChaletLoraDevice()
{
    mMyLoraAddress = 5;
    mMyLoraChannel = 4;

    QByteArray Test;
    Test.resize(4);
    Test[0] = 0xDE;
    Test[1] = 0xAD;
    Test[2] = 0xBE;
    Test[3] = 0xEF;

    GetLoraFrame(4,4,Test);

    mLoraStatusRefreshTimer = new QTimer;
    mLoraStatusRefreshTimer->setInterval(1000);
    mLoraStatusRefreshTimer->setSingleShot(false);
    connect(mLoraStatusRefreshTimer,SIGNAL(timeout()),this,SLOT(LoraStatusRefreshTimerExpired()));

    mLoraStatusRefreshTimer->start();

}

CChaletLoraDevice::~CChaletLoraDevice()
{
    mLoraStatusRefreshTimer->stop();
    delete mLoraStatusRefreshTimer;
}

int CChaletLoraDevice::Init()
{
    QList<QSerialPortInfo> PortsList = QSerialPortInfo::availablePorts();

    for(int i = 0; i < PortsList.size(); i++)
    {
        qDebug("Port found: %s - %s",qPrintable(PortsList.at(i).portName()),qPrintable(PortsList.at(i).description()));

    }

    mLoraModuleSerialPort.setPortName("COM3");
    mLoraModuleSerialPort.setBaudRate(QSerialPort::Baud9600);
    mLoraModuleSerialPort.setDataBits(QSerialPort::Data8);
    mLoraModuleSerialPort.setParity(QSerialPort::NoParity);
    mLoraModuleSerialPort.setFlowControl(QSerialPort::NoFlowControl);
    if(mLoraModuleSerialPort.open(QIODevice::ReadWrite) == false)
    {
        qDebug("Could not open Chalet Lora serial port");
        return RET_ERROR;
    }

    QByteArray Test;
    Test.resize(5);
    Test[0] = 0xDE;
    Test[1] = 0xAD;
    Test[2] = 0xBE;
    Test[3] = 0xEF;
    Test[4] = '\r';

    GetLoraFrame(4,4,Test);

    mLoraModuleSerialPort.write(GetLoraFrame(4,4,Test));

    return RET_OK;
}

void CChaletLoraDevice::LoraStatusRefreshTimerExpired()
{
    QByteArray Test;
    Test.resize(4);
    Test[0] = 0xBA;
    Test[1] = 0xAD;
    Test[2] = 0xCA;
    Test[3] = 0xFE;
//    Test[4] = '\r';

    GetLoraFrame(4,4,Test);

    mLoraModuleSerialPort.write(GetLoraFrame(4,4,Test));
    return;
}
