1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
4#include "qmqttcontrolpacket_p.h"
5
6#include <QtCore/QtEndian>
7#include <QtCore/QLoggingCategory>
8
9QT_BEGIN_NAMESPACE
10
11Q_DECLARE_LOGGING_CATEGORY(lcMqttClient)
12
13QMqttControlPacket::QMqttControlPacket()
14{
15
16}
17
18QMqttControlPacket::QMqttControlPacket(quint8 header)
19 : m_header(header)
20{
21
22}
23
24QMqttControlPacket::QMqttControlPacket(quint8 header, const QByteArray &pay)
25 : m_header(header)
26 , m_payload(pay)
27{
28
29}
30
31void QMqttControlPacket::clear()
32{
33 m_header = 0;
34 m_payload.clear();
35}
36
37void QMqttControlPacket::setHeader(quint8 h)
38{
39 if (h < QMqttControlPacket::CONNECT || h > DISCONNECT || h & 0x0F)
40 m_header = QMqttControlPacket::UNKNOWN;
41 else
42 m_header = h;
43}
44
45void QMqttControlPacket::append(char value)
46{
47 m_payload.append(c: value);
48}
49
50void QMqttControlPacket::append(quint16 value)
51{
52 const quint16 msb = qToBigEndian<quint16>(source: value);
53 const char * msb_c = reinterpret_cast<const char*>(&msb);
54 m_payload.append(s: msb_c, len: 2);
55}
56
57void QMqttControlPacket::append(quint32 value)
58{
59 const quint32 msb = qToBigEndian<quint32>(source: value);
60 const char * msb_c = reinterpret_cast<const char*>(&msb);
61 m_payload.append(s: msb_c, len: 4);
62}
63
64void QMqttControlPacket::append(const QByteArray &data)
65{
66 append(value: static_cast<quint16>(data.size()));
67 m_payload.append(a: data);
68}
69
70void QMqttControlPacket::appendRaw(const QByteArray &data)
71{
72 m_payload.append(a: data);
73}
74
75void QMqttControlPacket::appendRawVariableInteger(quint32 value)
76{
77 QByteArray data;
78 // Add length
79 if (value > 268435455)
80 qCDebug(lcMqttClient) << "Attempting to write variable integer overflow.";
81 do {
82 quint8 b = value % 128;
83 value /= 128;
84 if (value > 0)
85 b |= 0x80;
86 data.append(c: char(b));
87 } while (value > 0);
88 appendRaw(data);
89}
90
91QByteArray QMqttControlPacket::serialize() const
92{
93 // Create ByteArray
94 QByteArray data;
95 // Add Header
96 data.append(c: char(m_header));
97 data.append(a: serializePayload());
98
99 return data;
100}
101
102QByteArray QMqttControlPacket::serializePayload() const
103{
104 QByteArray data;
105 // Add length
106 quint32 msgSize = quint32(m_payload.size());
107 if (msgSize > 268435455)
108 qCDebug(lcMqttClient) << "Publishing a message bigger than maximum size.";
109 do {
110 quint8 b = msgSize % 128;
111 msgSize /= 128;
112 if (msgSize > 0)
113 b |= 0x80;
114 data.append(c: char(b));
115 } while (msgSize > 0);
116 // Add payload
117 data.append(a: m_payload);
118 return data;
119}
120
121QT_END_NAMESPACE
122
123

source code of qtmqtt/src/mqtt/qmqttcontrolpacket.cpp