#include "pqrtuhelper.h"

namespace PQ {

RTUHelper::RTUHelper():
    readType(SubAddress),toReadlen(0),_checkSubAddress(false)
{

}

RTUHelper::~RTUHelper(){}

void RTUHelper::readed(const QByteArray &data)
{
    int index = 0;
    while (index < data.length())
    {
        const char ch = data.at(index);
        switch (readType)
        {
        case SubAddress:
        {
            ++ index;
            if (!_checkSubAddress || _subAddress.contains(ch))
            {
                if(!buffer.isEmpty()) buffer.clear();
                buffer.append(ch);
                readType = GetType;
            }
            continue;
        }
        case GetType:
        {
            buffer.append(ch);
            ++ index;
            readType = NumLength;
            continue;
        }
        case NumLength: //需要读数据
        {
            ++ index;
            toReadlen = static_cast<uchar>(ch);
            buffer.append(ch);
            readType = ReadData;
            continue;
        }
        case ReadData: //需要读数据
        {
            const int canread = data.length() - index;
            if (canread >= toReadlen)
            {
                buffer.append(data.mid(index, toReadlen));
                index += toReadlen;
                toReadlen = 0;
                readType = CRCUL;
            }
            else
            {
                buffer.append(data.mid(index, canread));
                index += canread;
                toReadlen -= canread;
            }
            continue;
        }
        case CRCUL: //需要读数据
        {
            buffer.append(ch);
            index ++;
            readType = CRCUH;
            continue;
        }
        case CRCUH: //需要读数据
        {
            buffer.append(ch);
            index ++;
            readType = SubAddress;
            doHandle(this->buffer);
            buffer.clear();
        }
            break;
        default:
        {
            readType = SubAddress;
            continue;
        }
        }
    }
}
}
