summaryrefslogtreecommitdiffstats
path: root/protocol.cpp
blob: 19d6c3d0248aedf138f5107e71094707375cb285 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "protocol.h"
#include <QDebug>

Protocol::Protocol(QObject *parent)
    : QObject(parent)
    , mState(Start)
{
}

Protocol::~Protocol()
{
}

void Protocol::reset()
{
    mState = Start;
    mFields.clear();
    mField.clear();
}

void Protocol::write(const QByteArray &data)
{
    QByteArray buffer(data);

    while (!buffer.isEmpty()) {
        unsigned int remove = 0;

        if (buffer[0] == '@') {
            if (buffer.size() > 1) {
                if (buffer[1] == '@' && mState != Start) {
                    mField += '@';
                    remove += 2;
                } else if (buffer[1] == '\n' || buffer[1] == '\r') {
                    remove += 2;
                    if (mState != Field) {
                        reset();
                        qDebug() << "End unexpected";
                    } else {
                        mFields += mField;
                        emit commandReceived(mFields);
                        reset();
                    }
                } else {
                    ++remove;
                    if (mState != Start) {
                       qDebug() << "Start unexpected";
                    } else {
                        mState = Field;
                        mField.clear();
                        mFields.clear();
                    }
                }
            }
        } else if (buffer[0] == ':') {
            if (buffer.size() > 1) {
                if (buffer[1] == ':') {
                    mField += ':';
                    remove += 2;
                } else {
                    ++remove;
                    mFields += mField;
                    mField.clear();
                }
            }
        } else {
            ++remove;
            mField += buffer[0];
        }

        buffer.remove(0, remove);
    }
}

QString Protocol::sendToClient(const QStringList &data)
{
    bool first = true;
    QString rc("@");
    foreach (QString s, data) {
        s.replace(":", "::");
        s.replace("@", "@@");
        if (!first)
            rc += ":";
        else
            first = false;

        rc += s;
    }
    rc += "@\n";
    return rc;
}