#include "unitmonitor.h"
#include "xlru_message_def.h"

#include <QDebug>

static char last_fcs;
static char last_unit;

UnitMonitor::UnitMonitor(QObject *parent) : QObject(parent)
{
    //
}

int UnitMonitor::checkMessage(const QByteArray& data, int *index)
{
    int start_index=index ? *index : 0;
    const char* p=data.constData();
    int n=data.size();

    int unit=0;
    int i=0;
    for(i=start_index; i<n; ++i)
    {
        if (p[i]==SOM)
        {
            accumulator.clear();
            continue;
        }
        if (p[i]==SOM_REPLY)
        {
            accumulator.clear();
        }
        accumulator.append(p[i]);
        if (p[i]=='\r')
        {
            if (accumulator.size()>4)
            {
                const char* m=accumulator.constData();
                if (m[0]==SOM_REPLY)
                {
                    ++i;
                    char u=m[1];
                    unit=u-'0';
                    if ((unit<0) || (unit>3))
                            unit=0;
                    last_fcs=m[2];
                    last_unit=u;

                    pendingMessage=accumulator;

                    accumulator.clear();
                    break;
                }
            }
            accumulator.clear();
        }
    }
    if (accumulator.size()>512)
        accumulator.clear();
    if (index)
        *index=i;
    return unit;
}
