flashmqtestclient.cpp
7.2 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#include "flashmqtestclient.h"
#include <sys/epoll.h>
#include <cstring>
#include "errno.h"
#include "functional"
#include "threadloop.h"
#include "utils.h"
#include "client.h"
#define TEST_CLIENT_MAX_EVENTS 25
int FlashMQTestClient::clientCount = 0;
FlashMQTestClient::FlashMQTestClient() :
settings(std::make_shared<Settings>()),
testServerWorkerThreadData(std::make_shared<ThreadData>(0, settings)),
dummyThreadData(std::make_shared<ThreadData>(666, settings))
{
}
/**
* @brief FlashMQTestClient::~FlashMQTestClient properly quits the threads when exiting.
*
* This prevents accidental crashes on calling terminate(), and Qt Macro's prematurely end the method, skipping explicit waits after the tests.
*/
FlashMQTestClient::~FlashMQTestClient()
{
waitForQuit();
}
void FlashMQTestClient::waitForCondition(std::function<bool()> f)
{
int n = 0;
while(n++ < 100)
{
usleep(10000);
std::lock_guard<std::mutex> locker(receivedListMutex);
if (f())
break;
}
std::lock_guard<std::mutex> locker(receivedListMutex);
if (!f())
{
throw std::runtime_error("Wait condition failed.");
}
}
void FlashMQTestClient::clearReceivedLists()
{
std::lock_guard<std::mutex> locker(receivedListMutex);
receivedPackets.clear();
receivedPublishes.clear();
}
void FlashMQTestClient::start()
{
testServerWorkerThreadData->start(&do_thread_work);
}
void FlashMQTestClient::connectClient(ProtocolVersion protocolVersion)
{
int sockfd = check<std::runtime_error>(socket(AF_INET, SOCK_STREAM, 0));
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
const std::string hostname = "127.0.0.1";
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(hostname.c_str());
servaddr.sin_port = htons(1883);
int flags = fcntl(sockfd, F_GETFL);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
int rc = connect(sockfd, reinterpret_cast<struct sockaddr*>(&servaddr), sizeof (servaddr));
if (rc < 0 && errno != EINPROGRESS)
{
throw std::runtime_error(strerror(errno));
}
const std::string clientid = formatString("testclient_%d", clientCount++);
this->client = std::make_shared<Client>(sockfd, testServerWorkerThreadData, nullptr, false, reinterpret_cast<struct sockaddr*>(&servaddr), settings.get());
this->client->setClientProperties(protocolVersion, clientid, "user", false, 60);
testServerWorkerThreadData->giveClient(this->client);
// This gets called in the test client's worker thread, but the STL container's minimal thread safety should be enough: only list manipulation is
// mutexed, elements within are not.
client->onPacketReceived = [&](MqttPacket &pack)
{
std::lock_guard<std::mutex> locker(receivedListMutex);
if (pack.packetType == PacketType::PUBLISH)
{
pack.parsePublishData();
MqttPacket copyPacket = pack;
this->receivedPublishes.push_back(copyPacket);
if (pack.getPublishData().qos > 0)
{
PubResponse pubAck(this->client->getProtocolVersion(), PacketType::PUBACK, ReasonCodes::Success, pack.getPacketId());
this->client->writeMqttPacketAndBlameThisClient(pubAck);
}
}
else if (pack.packetType == PacketType::PUBREL)
{
pack.parsePubRelData();
PubResponse pubComp(this->client->getProtocolVersion(), PacketType::PUBCOMP, ReasonCodes::Success, pack.getPacketId());
this->client->writeMqttPacketAndBlameThisClient(pubComp);
}
else if (pack.packetType == PacketType::PUBREC)
{
pack.parsePubRecData();
PubResponse pubRel(this->client->getProtocolVersion(), PacketType::PUBREL, ReasonCodes::Success, pack.getPacketId());
this->client->writeMqttPacketAndBlameThisClient(pubRel);
}
this->receivedPackets.push_back(std::move(pack));
};
Connect connect(protocolVersion, client->getClientId());
MqttPacket connectPack(connect);
this->client->writeMqttPacketAndBlameThisClient(connectPack);
waitForConnack();
}
void FlashMQTestClient::subscribe(const std::string topic, char qos)
{
clearReceivedLists();
const uint16_t packet_id = 66;
Subscribe sub(client->getProtocolVersion(), packet_id, topic, qos);
MqttPacket subPack(sub);
client->writeMqttPacketAndBlameThisClient(subPack);
waitForCondition([&]() {
return !this->receivedPackets.empty() && this->receivedPackets.front().packetType == PacketType::SUBACK;
});
MqttPacket &subAck = this->receivedPackets.front();
SubAckData data = subAck.parseSubAckData();
if (data.packet_id != packet_id)
throw std::runtime_error("Incorrect packet id in suback");
if (!std::all_of(data.subAckCodes.begin(), data.subAckCodes.end(), [&](uint8_t x) { return x <= qos ;}))
{
throw std::runtime_error("Suback indicates error.");
}
}
void FlashMQTestClient::publish(const std::string &topic, const std::string &payload, char qos)
{
clearReceivedLists();
const uint16_t packet_id = 77;
Publish pub(topic, payload, qos);
MqttPacket pubPack(client->getProtocolVersion(), pub);
if (qos > 0)
pubPack.setPacketId(packet_id);
client->writeMqttPacketAndBlameThisClient(pubPack);
if (qos == 1)
{
waitForCondition([&]() {
return this->receivedPackets.size() == 1;
});
MqttPacket &pubAckPack = this->receivedPackets.front();
pubAckPack.parsePubAckData();
if (pubAckPack.packetType != PacketType::PUBACK)
throw std::runtime_error("First packet received from server is not a PUBACK.");
if (pubAckPack.getPacketId() != packet_id || this->receivedPackets.size() != 1)
throw std::runtime_error("Packet ID mismatch on QoS 1 publish or packet count wrong.");
}
else if (qos == 2)
{
waitForCondition([&]() {
return this->receivedPackets.size() >= 2;
});
MqttPacket &pubRecPack = this->receivedPackets.front();
pubRecPack.parsePubRecData();
MqttPacket &pubCompPack = this->receivedPackets.back();
pubCompPack.parsePubComp();
if (pubRecPack.packetType != PacketType::PUBREC)
throw std::runtime_error("First packet received from server is not a PUBREC.");
if (pubCompPack.packetType != PacketType::PUBCOMP)
throw std::runtime_error("Last packet received from server is not a PUBCOMP.");
if (pubRecPack.getPacketId() != packet_id || pubCompPack.getPacketId() != packet_id)
throw std::runtime_error("Packet ID mismatch on QoS 2 publish.");
}
}
void FlashMQTestClient::waitForQuit()
{
testServerWorkerThreadData->queueQuit();
testServerWorkerThreadData->waitForQuit();
}
void FlashMQTestClient::waitForConnack()
{
waitForCondition([&]() {
return std::any_of(this->receivedPackets.begin(), this->receivedPackets.end(), [](const MqttPacket &p) {
return p.packetType == PacketType::CONNACK;
});
});
}
void FlashMQTestClient::waitForMessageCount(const size_t count)
{
waitForCondition([&]() {
return this->receivedPublishes.size() >= count;
});
}