#include "LazerProbeSimulator.h"
#include <QTextCodec>
#include <QtGlobal>


CLazerProbeSimulator::CLazerProbeSimulator()
{
//    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    mLaserProbeSerialPort = new QextSerialPort("COM1", QextSerialPort::EventDriven);
    if(mLaserProbeSerialPort == NULL)
    {
        qDebug("Impossible de créer le port %s","COM1");
        return;
    }

   // connect(mSRDFSerialPort, SIGNAL(readyRead()), this, SLOT(SRDFDataAvailable()));

    mLaserProbeSerialPort->setBaudRate(BAUD38400);
    mLaserProbeSerialPort->setFlowControl(FLOW_OFF);
    mLaserProbeSerialPort->setParity(PAR_NONE);
    mLaserProbeSerialPort->setDataBits(DATA_8);
    mLaserProbeSerialPort->setStopBits(STOP_2);
    mLaserProbeSerialPort->setTimeout(0);

    if(mLaserProbeSerialPort->open(QIODevice::WriteOnly | QIODevice::Unbuffered))
    {
      //  connect(mSRDFSerialPort, SIGNAL(readyRead()), this, SLOT(SRDFDataAvailable()));
        qDebug("Port série ouvert avec succès");
    }
    else
    {
        qDebug("Impossible d'ouvrir le port série COM1");
    }

    mHeader = 0x54;
    mValue = 0;
    mTxBuf[0] = 0;
    mTxBuf[1] = 0;
    mTxBuf[2] = 0;

    mTxTimer = new QTimer();
    mTxTimer->setInterval(1);
    mTxTimer->setSingleShot(false);
    mTxTimer->stop();
    connect(mTxTimer,SIGNAL(timeout()),this, SLOT(ProbeTxTimerExpired()));
}

CLazerProbeSimulator::~CLazerProbeSimulator()
{
    qDebug("Closing serial port");
    mLaserProbeSerialPort->close();
    delete mLaserProbeSerialPort;
    delete mTxTimer;
}

bool CLazerProbeSimulator::EnableProbe(bool Enable)
{
    if(Enable)
    {
        qDebug("Probe enabled");
        mTxTimer->start();
    }
    else
    {
        qDebug("Probe disabled");
        mTxTimer->stop();
    }
    return true;
}

bool CLazerProbeSimulator::SetProbeCurRange(int Range)
{

    mValue = Range;

    qDebug(qPrintable(QString("%1").arg(mValue)));

    return true;
}

void CLazerProbeSimulator::ProbeTxTimerExpired()
{
    int Temp = mValue;
    mHeader = (~mHeader) & LAZER_PROBE_HEADER_MASK;
    mHeader |= ((char)Temp & LAZER_PROBE_DATA_NIBBLE_MASK);
    mTxBuf[0] = mHeader;

    Temp >>= 2;
    mTxBuf[1] = (char)Temp & 0xFF;

    Temp >>= 8;
    mTxBuf[2] = (char)Temp & 0xFF;

    QByteArray Buf;
    Buf.append(mTxBuf[0]);
    Buf.append(mTxBuf[1]);
    Buf.append(mTxBuf[2]);

    mLaserProbeSerialPort->write(Buf);

    qDebug(qPrintable(QString().sprintf("[0x%x][0x%x][0x%x]",mTxBuf[0],mTxBuf[1], mTxBuf[2])));
}
