Blame view

src/mqttclient.cpp 23.7 KB
b5d9e433   Peter M. Groen   Fixed License Hea...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  /* ****************************************************************************
   * Copyright 2019 Open Systems Development BV                                 *
   *                                                                            *
   * Permission is hereby granted, free of charge, to any person obtaining a    *
   * copy of this software and associated documentation files (the "Software"), *
   * to deal in the Software without restriction, including without limitation  *
   * the rights to use, copy, modify, merge, publish, distribute, sublicense,   *
   * and/or sell copies of the Software, and to permit persons to whom the      *
   * Software is furnished to do so, subject to the following conditions:       *
   *                                                                            *
   * The above copyright notice and this permission notice shall be included in *
   * all copies or substantial portions of the Software.                        *
   *                                                                            *
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   *
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    *
   * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    *
   * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        *
   * DEALINGS IN THE SOFTWARE.                                                  *
   * ***************************************************************************/
51becbde   Peter M. Groen   Committed the ent...
22
23
  #include "mqttclient.h"
  
51becbde   Peter M. Groen   Committed the ent...
24
25
26
27
28
  // osdev::components::mqtt
  #include "clientpaho.h"
  #include "mqttutil.h"
  #include "mqttidgenerator.h"
  #include "mqtttypeconverter.h"
51becbde   Peter M. Groen   Committed the ent...
29
30
31
32
33
34
  #include "lockguard.h"
  #include "uriparser.h"
  
  // std
  #include <numeric>
  #include <iostream>
199d7075   Peter M. Groen   implement logging...
35
  #include <string>
51becbde   Peter M. Groen   Committed the ent...
36
37
  
  using namespace osdev::components::mqtt;
199d7075   Peter M. Groen   implement logging...
38
  using namespace osdev::components::log;
51becbde   Peter M. Groen   Committed the ent...
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  
  namespace {
  /**
   * @brief Generate a unique client id so that a new client does not steal the connection from an existing client.
   * @param clientId The base client identifier.
   * @param clientNumber The next client that is derived from the base client identifier.
   * @return A unique client identifier string.
   */
  std::string generateUniqueClientId(const std::string& clientId, std::size_t clientNumber)
  {
      return clientId + "_" + std::to_string(clientNumber) + "_" + MqttTypeConverter::toStdString(MqttIdGenerator::generate());
  }
  
  } // namespace
  
  MqttClient::MqttClient(const std::string& _clientId, const std::function<void(const Token& token)>& deliveryCompleteCallback)
      : m_interfaceMutex()
      , m_internalMutex()
d557d523   Peter M. Groen   Fix deferred subs...
57
      , m_subscriptionMutex()
51becbde   Peter M. Groen   Committed the ent...
58
59
60
61
62
63
64
65
66
      , m_endpoint()
      , m_clientId(_clientId)
      , m_activeTokens()
      , m_activeTokensCV()
      , m_deliveryCompleteCallback(deliveryCompleteCallback)
      , m_serverState(this)
      , m_principalClient()
      , m_additionalClients()
      , m_eventQueue(_clientId)
84738f56   Peter M. Groen   Setting up the lo...
67
      , m_workerThread( std::thread( &MqttClient::eventHandler, this ) )
d557d523   Peter M. Groen   Fix deferred subs...
68
      , m_deferredSubscriptions()
51becbde   Peter M. Groen   Committed the ent...
69
  {
199d7075   Peter M. Groen   implement logging...
70
71
      Log::init( "mqtt-library" );
      LogInfo( "MQTT Client started", "[MqttClient::MqttClient]");
51becbde   Peter M. Groen   Committed the ent...
72
73
74
75
  }
  
  MqttClient::~MqttClient()
  {
d1d79e6d   Peter M. Groen   Added PR and adap...
76
77
78
79
80
81
      LogDebug( "MqttClient", std::string( m_clientId + " - dtor stop queue" ) );
      m_eventQueue.stop();
      if (m_workerThread.joinable()) {
          m_workerThread.join();
      }
      
51becbde   Peter M. Groen   Committed the ent...
82
      {
8bf44a9d   Peter M. Groen   Sensible return v...
83
          // LogDebug( "MqttClient", std::string( m_clientId + " - disconnect" ) );
51becbde   Peter M. Groen   Committed the ent...
84
85
86
87
          this->disconnect();
          decltype(m_principalClient) principalClient{};
  
          OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
199d7075   Peter M. Groen   implement logging...
88
          LogDebug( "MqttClient", std::string( m_clientId + " - cleanup principal client" ) );
51becbde   Peter M. Groen   Committed the ent...
89
90
          m_principalClient.swap(principalClient);
      }
84738f56   Peter M. Groen   Setting up the lo...
91
  
199d7075   Peter M. Groen   implement logging...
92
      LogDebug( "MqttClient", std::string( m_clientId + " - dtor ready" ) );
51becbde   Peter M. Groen   Committed the ent...
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
  }
  
  std::string MqttClient::clientId() const
  {
      return m_clientId;
  }
  
  StateChangeCallbackHandle MqttClient::registerStateChangeCallback(const SlotStateChange& cb)
  {
      OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
      OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
      return m_serverState.registerStateChangeCallback(cb);
  }
  
  void MqttClient::unregisterStateChangeCallback(StateChangeCallbackHandle handle)
  {
      OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
      OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
      m_serverState.unregisterStateChangeCallback(handle);
  }
  
  void MqttClient::clearAllStateChangeCallbacks()
  {
      OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
      OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
      m_serverState.clearAllStateChangeCallbacks();
  }
  
  StateEnum MqttClient::state() const
  {
      OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
      OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
      return m_serverState.state();
  }
  
1a77e1b5   Steven   added logging str...
128
  void MqttClient::connect(const std::string& host, int port, const Credentials &credentials, const mqtt_LWT &lwt, bool blocking, const LogSettings &log_settings )
51becbde   Peter M. Groen   Committed the ent...
129
  {
51becbde   Peter M. Groen   Committed the ent...
130
131
132
133
134
135
136
      osdev::components::mqtt::ParsedUri _endpoint = {
          { "scheme", "tcp" },
          { "user", credentials.username() },
          { "password", credentials.password() },
          { "host", host },
          { "port", std::to_string(port) }
      };
31eece9b   Steven   added LWT ( last ...
137
  
1a77e1b5   Steven   added logging str...
138
      this->connect( UriParser::toString( _endpoint ), lwt, blocking, log_settings );
51becbde   Peter M. Groen   Committed the ent...
139
140
  }
  
1a77e1b5   Steven   added logging str...
141
  void MqttClient::connect( const std::string &_endpoint, const mqtt_LWT &lwt, bool blocking, const LogSettings &log_settings )
51becbde   Peter M. Groen   Committed the ent...
142
  {
1a77e1b5   Steven   added logging str...
143
144
145
      Log::setLogLevel( log_settings.level );
      Log::setMask( log_settings.mask );
  
199d7075   Peter M. Groen   implement logging...
146
      LogInfo( "MqttClient", std::string( m_clientId + " - Request connect" ) );
84738f56   Peter M. Groen   Setting up the lo...
147
  
51becbde   Peter M. Groen   Committed the ent...
148
149
150
151
152
153
154
155
156
157
158
159
      OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
      IMqttClientImpl* client(nullptr);
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
          if (m_principalClient && m_principalClient->connectionStatus() != ConnectionStatus::Disconnected) {
              if (_endpoint == m_endpoint)
              {
                  // idempotent
                  return;
              }
              else
              {
199d7075   Peter M. Groen   implement logging...
160
                  LogError( "MqttClient", std::string( m_clientId + " - Cannot connect to different endpoint. Disconnect first." ) );
84738f56   Peter M. Groen   Setting up the lo...
161
                  return;
51becbde   Peter M. Groen   Committed the ent...
162
163
164
              }
          }
          m_endpoint = _endpoint;
31eece9b   Steven   added LWT ( last ...
165
166
          if (!m_principalClient)
          {
51becbde   Peter M. Groen   Committed the ent...
167
168
169
170
171
172
173
174
175
              std::string derivedClientId(generateUniqueClientId(m_clientId, 1));
              m_principalClient = std::make_unique<ClientPaho>(
                  m_endpoint,
                  derivedClientId,
                  [this](const std::string& id, ConnectionStatus cs) { this->connectionStatusChanged(id, cs); },
                  [this](std::string clientId, std::int32_t token) { this->deliveryComplete(clientId, token); });
          }
          client = m_principalClient.get();
      }
31eece9b   Steven   added LWT ( last ...
176
  
9421324b   Peter M. Groen   First fix on conn...
177
      client->connect( blocking, lwt );
51becbde   Peter M. Groen   Committed the ent...
178
179
180
181
  }
  
  void MqttClient::disconnect()
  {
199d7075   Peter M. Groen   implement logging...
182
      LogInfo( "MqttClient", std::string( m_clientId + " - Request disconnect" ) );
51becbde   Peter M. Groen   Committed the ent...
183
184
185
186
187
188
      OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
  
      decltype(m_additionalClients) additionalClients{};
      std::vector<IMqttClientImpl*> clients{};
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
84738f56   Peter M. Groen   Setting up the lo...
189
190
          if (!m_principalClient || m_principalClient->connectionStatus() == ConnectionStatus::Disconnected || m_principalClient->connectionStatus() == ConnectionStatus::DisconnectInProgress)
          {
199d7075   Peter M. Groen   implement logging...
191
              LogDebug( "MqttClient", std::string( m_clientId + " - Principal client not connected" ) );
51becbde   Peter M. Groen   Committed the ent...
192
193
              return;
          }
84738f56   Peter M. Groen   Setting up the lo...
194
          m_additionalClients.swap( additionalClients );
51becbde   Peter M. Groen   Committed the ent...
195
  
84738f56   Peter M. Groen   Setting up the lo...
196
197
198
          for (const auto& c : additionalClients)
          {
              clients.push_back( c.get() );
51becbde   Peter M. Groen   Committed the ent...
199
          }
84738f56   Peter M. Groen   Setting up the lo...
200
          clients.push_back( m_principalClient.get() );
51becbde   Peter M. Groen   Committed the ent...
201
202
      }
  
84738f56   Peter M. Groen   Setting up the lo...
203
  
199d7075   Peter M. Groen   implement logging...
204
      LogDebug( "MqttClient", std::string( m_clientId +  " - Unsubscribe and disconnect clients" ) );
84738f56   Peter M. Groen   Setting up the lo...
205
206
      for ( auto& cl : clients )
      {
51becbde   Peter M. Groen   Committed the ent...
207
208
209
210
211
212
213
214
215
216
217
218
          cl->unsubscribeAll();
      }
      this->waitForCompletionInternal(clients, std::chrono::milliseconds(2000), std::set<Token>{});
  
      for (auto& cl : clients) {
          cl->disconnect(false, 2000);
      }
      this->waitForCompletionInternal(clients, std::chrono::milliseconds(3000), std::set<Token>{});
  }
  
  Token MqttClient::publish(const MqttMessage& message, int qos)
  {
60ac1cde   Peter M. Groen   [Fix] Bugfix in h...
219
220
221
      if (hasWildcard(message.topic()))
      {
          LogDebug("[MqttClient::publish]","Topic has wildcard : " + message.topic());
51becbde   Peter M. Groen   Committed the ent...
222
223
          return Token(m_clientId, -1);
      }
60ac1cde   Peter M. Groen   [Fix] Bugfix in h...
224
225
226
227
228
229
      else if(!isValidTopic(message.topic()))
      {
          LogDebug("[MqttClient::publish]","Topic is invalid : " + message.topic());
          return Token(m_clientId, -1);
      }
  
51becbde   Peter M. Groen   Committed the ent...
230
231
232
233
234
235
236
237
      OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
      IMqttClientImpl* client(nullptr);
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
          if (!m_principalClient || m_principalClient->connectionStatus() == ConnectionStatus::Disconnected)
          {
              if( !m_principalClient )
              {
199d7075   Peter M. Groen   implement logging...
238
                  LogInfo( "[MqttClient::publish]", std::string( "Principal client not initialized") );
51becbde   Peter M. Groen   Committed the ent...
239
240
241
242
243
244
              }
  
              if( m_principalClient->connectionStatus() == ConnectionStatus::Disconnected )
              {
                  std::cout << "Unable to publish, not connected.." << std::endl;
              }
199d7075   Peter M. Groen   implement logging...
245
246
              LogError("MqttClient", std::string( m_clientId + " - Unable to publish, not connected" ) );
  
8bf44a9d   Peter M. Groen   Sensible return v...
247
              return Token(m_clientId, -1);
51becbde   Peter M. Groen   Committed the ent...
248
249
250
          }
          client = m_principalClient.get();
      }
60ac1cde   Peter M. Groen   [Fix] Bugfix in h...
251
252
253
254
255
256
257
  
      if(!client)
      {
          LogDebug("[MqttClient::publish]", "Invalid pointer to IMqttClient retrieved.");
          return Token(m_clientId, -1);
      }
  
51becbde   Peter M. Groen   Committed the ent...
258
259
260
261
262
      return Token(client->clientId(), client->publish(message, qos));
  }
  
  Token MqttClient::subscribe(const std::string& topic, int qos, const std::function<void(MqttMessage)>& cb)
  {
199d7075   Peter M. Groen   implement logging...
263
      LogDebug( "[MqttClient::subscribe]", std::string( m_clientId + " - Subscribe to topic " + topic ) );
51becbde   Peter M. Groen   Committed the ent...
264
265
266
267
268
      // OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
      bool clientFound = false;
      IMqttClientImpl* client(nullptr);
      {
          // OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
d557d523   Peter M. Groen   Fix deferred subs...
269
          if (!m_principalClient || m_principalClient->connectionStatus() != ConnectionStatus::Connected)
51becbde   Peter M. Groen   Committed the ent...
270
          {
199d7075   Peter M. Groen   implement logging...
271
              LogError("MqttClient", std::string( m_clientId + " - Unable to subscribe, not connected" ) );
d557d523   Peter M. Groen   Fix deferred subs...
272
273
274
              // Store the subscription in the buffer for later processing.
              {
                  OSDEV_COMPONENTS_LOCKGUARD(m_subscriptionMutex);
ef28d9ce   Peter M. Groen   Fixed pass by ref...
275
                  m_deferredSubscriptions.emplace_back( topic, qos, cb );
d557d523   Peter M. Groen   Fix deferred subs...
276
277
              }
  
8bf44a9d   Peter M. Groen   Sensible return v...
278
              return Token(m_clientId, -1);
51becbde   Peter M. Groen   Committed the ent...
279
          }
d557d523   Peter M. Groen   Fix deferred subs...
280
  
9421324b   Peter M. Groen   First fix on conn...
281
282
          if (!m_principalClient->isOverlapping(topic))
          {
51becbde   Peter M. Groen   Committed the ent...
283
284
285
              client = m_principalClient.get();
              clientFound = true;
          }
9421324b   Peter M. Groen   First fix on conn...
286
287
288
289
          else
          {
              for (const auto& c : m_additionalClients)
              {
ef28d9ce   Peter M. Groen   Fixed pass by ref...
290
291
                  if (!c->isOverlapping(topic))
                  {
51becbde   Peter M. Groen   Committed the ent...
292
293
294
295
296
297
                      client = c.get();
                      clientFound = true;
                      break;
                  }
              }
          }
d557d523   Peter M. Groen   Fix deferred subs...
298
  
9421324b   Peter M. Groen   First fix on conn...
299
300
          if (!clientFound)
          {
199d7075   Peter M. Groen   implement logging...
301
              LogDebug("[MqttClient::subscribe]", std::string( m_clientId + " - Creating new ClientPaho instance for subscription on topic " + topic ) );
51becbde   Peter M. Groen   Committed the ent...
302
303
304
305
306
307
308
309
310
              std::string derivedClientId(generateUniqueClientId(m_clientId, m_additionalClients.size() + 2)); // principal client is nr 1.
              m_additionalClients.emplace_back(std::make_unique<ClientPaho>(
                  m_endpoint,
                  derivedClientId,
                  [this](const std::string& id, ConnectionStatus cs) { this->connectionStatusChanged(id, cs); },
                  std::function<void(const std::string&, std::int32_t)>{}));
              client = m_additionalClients.back().get();
          }
      }
d557d523   Peter M. Groen   Fix deferred subs...
311
  
9421324b   Peter M. Groen   First fix on conn...
312
313
      if (!clientFound)
      {
d557d523   Peter M. Groen   Fix deferred subs...
314
          client->connect( true );
51becbde   Peter M. Groen   Committed the ent...
315
316
317
318
319
320
      }
      return Token{ client->clientId(), client->subscribe(topic, qos, cb) };
  }
  
  std::set<Token> MqttClient::unsubscribe(const std::string& topic, int qos)
  {
199d7075   Peter M. Groen   implement logging...
321
      LogDebug("[MqttClient::unsubscribe]", std::string( m_clientId + " - Unsubscribe from topic " + topic ) );
51becbde   Peter M. Groen   Committed the ent...
322
323
324
325
      OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
      std::vector<IMqttClientImpl*> clients{};
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
ef28d9ce   Peter M. Groen   Fixed pass by ref...
326
327
          if (!m_principalClient || m_principalClient->connectionStatus() == ConnectionStatus::Disconnected)
          {
199d7075   Peter M. Groen   implement logging...
328
              LogError("[MqttClient::unsubscribe]", std::string( m_clientId + " - Unable to unsubscribe, not connected" ) );
51becbde   Peter M. Groen   Committed the ent...
329
              // Throw (MqttException, "Not connected");
8bf44a9d   Peter M. Groen   Sensible return v...
330
              return std::set<Token>();
51becbde   Peter M. Groen   Committed the ent...
331
          }
2569446f   Peter M. Groen   Added extra subsc...
332
  
51becbde   Peter M. Groen   Committed the ent...
333
          clients.push_back(m_principalClient.get());
ef28d9ce   Peter M. Groen   Fixed pass by ref...
334
335
          for (const auto& c : m_additionalClients)
          {
51becbde   Peter M. Groen   Committed the ent...
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
              clients.push_back(c.get());
          }
      }
      std::set<Token> tokens{};
      for (auto* c : clients) {
          auto token = c->unsubscribe(topic, qos);
          if (-1 != token) {
              tokens.emplace(Token{ c->clientId(), token });
          }
      }
      return tokens;
  }
  
  bool MqttClient::waitForCompletion(std::chrono::milliseconds waitFor) const
  {
      return this->waitForCompletion(waitFor, std::set<Token>{});
  }
  
  bool MqttClient::waitForCompletion(std::chrono::milliseconds waitFor, const Token& token) const
  {
      if (-1 == token.token()) {
          return false;
      }
      return this->waitForCompletion(waitFor, std::set<Token>{ token });
  }
  
  bool MqttClient::waitForCompletion(std::chrono::milliseconds waitFor, const std::set<Token>& tokens) const
  {
      OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
      std::vector<IMqttClientImpl*> clients{};
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
          if (m_principalClient) {
              clients.push_back(m_principalClient.get());
          }
          for (const auto& c : m_additionalClients) {
              clients.push_back(c.get());
          }
      }
      return waitForCompletionInternal(clients, waitFor, tokens);
  }
  
  boost::optional<bool> MqttClient::commandResult(const Token& token) const
  {
      OSDEV_COMPONENTS_LOCKGUARD(m_interfaceMutex);
      std::vector<IMqttClientImpl*> clients{};
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
          if (m_principalClient) {
              clients.push_back(m_principalClient.get());
          }
          for (const auto& c : m_additionalClients) {
              clients.push_back(c.get());
          }
      }
      for (auto* c : clients) {
          if (token.clientId() == c->clientId()) {
              return c->operationResult(token.token());
          }
      }
      return boost::optional<bool>{};
  }
  
  std::string MqttClient::endpoint() const
  {
      auto ep = UriParser::parse(m_endpoint);
      if (ep.find("user") != ep.end()) {
          ep["user"].clear();
      }
      if (ep.find("password") != ep.end()) {
          ep["password"].clear();
      }
      return UriParser::toString(ep);
  }
  
  void MqttClient::connectionStatusChanged(const std::string& id, ConnectionStatus cs)
  {
199d7075   Peter M. Groen   implement logging...
413
      LogDebug("[MqttClient::connectionStatusChanged]", std::string( m_clientId + " - connection status of wrapped client " + id + " changed to " + std::to_string( static_cast<int>(cs) ) ) );
51becbde   Peter M. Groen   Committed the ent...
414
415
416
417
418
      IMqttClientImpl* principalClient{ nullptr };
      std::vector<IMqttClientImpl*> clients{};
      std::vector<ConnectionStatus> connectionStates{};
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
d557d523   Peter M. Groen   Fix deferred subs...
419
420
421
  
          if (m_principalClient)
          {
51becbde   Peter M. Groen   Committed the ent...
422
423
424
425
              principalClient = m_principalClient.get();
              clients.push_back(principalClient);
              connectionStates.push_back(m_principalClient->connectionStatus());
          }
d557d523   Peter M. Groen   Fix deferred subs...
426
427
428
  
          for (const auto& c : m_additionalClients)
          {
51becbde   Peter M. Groen   Committed the ent...
429
430
431
432
              clients.push_back(c.get());
              connectionStates.push_back(c->connectionStatus());
          }
      }
d557d523   Peter M. Groen   Fix deferred subs...
433
  
51becbde   Peter M. Groen   Committed the ent...
434
      auto newState = determineState(connectionStates);
f1384b55   Peter M. Groen   Fix publishing
435
436
      LogDebug( "[MqttClient::connectionStatusChanged]", std::string("Old state : " + std::to_string(static_cast<int>(m_serverState.state()))));
      LogDebug( "[MqttClient::connectionStatusChanged]", std::string("New state : " + std::to_string(static_cast<int>(newState))));
3fef3f83   Peter M. Groen   Active Resubscrib...
437
438
      bool resubscribe = (StateEnum::ConnectionFailure == m_serverState.state() && StateEnum::Good == newState);
      // First activate pending subscriptions
11fe0b09   Peter M. Groen   Rework for subscr...
439
      {
3fef3f83   Peter M. Groen   Active Resubscrib...
440
441
442
          OSDEV_COMPONENTS_LOCKGUARD(m_subscriptionMutex);
          LogDebug( "[MqttClient::connectionsStatusChanged]", std::string( m_clientId + " - Number of pending subscriptions : " + std::to_string(m_deferredSubscriptions.size() ) ) );
          while( m_deferredSubscriptions.size() > 0 )
8ae7f1fe   Peter M. Groen   Fix deferred subs...
443
          {
3fef3f83   Peter M. Groen   Active Resubscrib...
444
445
446
              auto subscription = m_deferredSubscriptions.at( 0 );
              this->subscribe( subscription.getTopic(), subscription.getQoS(), subscription.getCallBack() );
              m_deferredSubscriptions.erase( m_deferredSubscriptions.begin() );
8ae7f1fe   Peter M. Groen   Fix deferred subs...
447
          }
3fef3f83   Peter M. Groen   Active Resubscrib...
448
      }
8ae7f1fe   Peter M. Groen   Fix deferred subs...
449
  
3fef3f83   Peter M. Groen   Active Resubscrib...
450
451
452
453
454
455
      LogDebug( "[MqttClient::connectionStatusChanged]",
                  std::string( m_clientId + " - Resubscribing..." ) );
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
          m_activeTokens.clear();
      }
d557d523   Peter M. Groen   Fix deferred subs...
456
  
3fef3f83   Peter M. Groen   Active Resubscrib...
457
458
      if (resubscribe)
      {
d557d523   Peter M. Groen   Fix deferred subs...
459
460
461
462
463
          for (auto* cl : clients)
          {
              try
              {
                  LogDebug( "[MqttClient::connectionStatusChanged]", std::string( m_clientId + " - Client " + cl->clientId() + " has " + std::string( cl->hasPendingSubscriptions() ? "" : "no" ) + " pending subscriptions" ) );
51becbde   Peter M. Groen   Committed the ent...
464
465
                  cl->resubscribe();
              }
d557d523   Peter M. Groen   Fix deferred subs...
466
467
              catch (const std::exception& e)
              {
199d7075   Peter M. Groen   implement logging...
468
                  LogError("[MqttClient::connectionStatusChanged]", std::string( m_clientId + " - resubscribe on wrapped client " + cl->clientId() + " in context of connection status change in wrapped client : " + id + " => FAILED : " + e.what() ) );
51becbde   Peter M. Groen   Committed the ent...
469
470
471
472
473
474
475
              }
          }
          m_activeTokensCV.notify_all();
      }
  
      // The server state change and a possible resubscription are done in the context of the MqttClient worker thread
      // The wrapper is free to pick up new work such as the acknowledment of the just recreated subscriptions.
f1384b55   Peter M. Groen   Fix publishing
476
477
478
479
      this->pushEvent([this, resubscribe, clients, principalClient, newState]() 
      {
          // if (resubscribe)
          // {
51becbde   Peter M. Groen   Committed the ent...
480
481
482
              // Just wait for the subscription commands to complete. We do not use waitForCompletionInternal because that call will always timeout when there are active tokens.
              // Active tokens are removed typically by work done on the worker thread. The wait action is also performed on the worker thread.
              auto waitFor = std::chrono::milliseconds(1000);
d557d523   Peter M. Groen   Fix deferred subs...
483
484
485
486
487
488
489
490
491
492
              if (!waitForCompletionInternalClients(clients, waitFor, std::set<Token>{}))
              {
                  if (std::accumulate(clients.begin(),
                                      clients.end(),
                                      false,
                                      [](bool hasPending, IMqttClientImpl* client)
                                      {
                                          return hasPending || client->hasPendingSubscriptions();
                                      }))
                  {
199d7075   Peter M. Groen   implement logging...
493
                      LogWarning("[MqttClient::connectionStatusChanged]", std::string( m_clientId + " - subscriptions are not recovered within timeout." ) );
51becbde   Peter M. Groen   Committed the ent...
494
495
                  }
              }
d557d523   Peter M. Groen   Fix deferred subs...
496
497
498
499
              if (principalClient)
              {
                  try
                  {
51becbde   Peter M. Groen   Committed the ent...
500
501
                      principalClient->publishPending();
                  }
d557d523   Peter M. Groen   Fix deferred subs...
502
503
                  catch (const std::exception& e)
                  {
199d7075   Peter M. Groen   implement logging...
504
                      LogError( "[MqttClient::connectionStatusChanged]", std::string( m_clientId + " - publishPending on wrapped client " + principalClient->clientId() + " => FAILED " + e.what() ) );
51becbde   Peter M. Groen   Committed the ent...
505
506
                  }
              }
f1384b55   Peter M. Groen   Fix publishing
507
          // }
51becbde   Peter M. Groen   Committed the ent...
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
          m_serverState.emitStateChanged(newState);
      });
  }
  
  void MqttClient::deliveryComplete(const std::string& _clientId, std::int32_t token)
  {
      if (!m_deliveryCompleteCallback) {
          return;
      }
  
      Token t(_clientId, token);
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
          if (!m_activeTokens.insert(t).second) {
              // This should not happen. This means that some callback on the wrapper never came.
199d7075   Peter M. Groen   implement logging...
523
              LogDebug("[MqttClient::deliveryComplete]", std::string( m_clientId + " - deliveryComplete, token is already active" ) );
51becbde   Peter M. Groen   Committed the ent...
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
          }
      }
      this->pushEvent([this, t]() {
          OSDEV_COMPONENTS_SCOPEGUARD(m_activeTokens, [this, &t]() {
              {
                  OSDEV_COMPONENTS_LOCKGUARD(m_internalMutex);
                  m_activeTokens.erase(t);
              }
              m_activeTokensCV.notify_all();
          });
          m_deliveryCompleteCallback(t);
      });
  }
  
  bool MqttClient::waitForCompletionInternal(const std::vector<IMqttClientImpl*>& clients, std::chrono::milliseconds waitFor, const std::set<Token>& tokens) const
  {
      if (!waitForCompletionInternalClients(clients, waitFor, tokens)) {
          return false;
      }
      std::unique_lock<std::mutex> lck(m_internalMutex);
      return m_activeTokensCV.wait_for(lck, waitFor, [this, &tokens]() {
          if (tokens.empty()) { // wait for all operations to end
              return m_activeTokens.empty();
          }
          else if (tokens.size() == 1) {
              return m_activeTokens.find(*tokens.cbegin()) == m_activeTokens.end();
          }
          std::vector<Token> intersect{};
          std::set_intersection(m_activeTokens.begin(), m_activeTokens.end(), tokens.begin(), tokens.end(), std::back_inserter(intersect));
          return intersect.empty(); });
  }
  
  bool MqttClient::waitForCompletionInternalClients(const std::vector<IMqttClientImpl*>& clients, std::chrono::milliseconds& waitFor, const std::set<Token>& tokens) const
  {
      for (auto* c : clients) {
          std::set<std::int32_t> clientTokens{};
          for (const auto& token : tokens) {
              if (c->clientId() == token.clientId()) {
                  clientTokens.insert(token.token());
              }
          }
          if (tokens.empty() || !clientTokens.empty()) {
              waitFor -= c->waitForCompletion(waitFor, clientTokens);
          }
      }
      if (waitFor > std::chrono::milliseconds(0)) {
          return true;
      }
      waitFor = std::chrono::milliseconds(0);
      return false;
  }
  
  StateEnum MqttClient::determineState(const std::vector<ConnectionStatus>& connectionStates)
  {
      std::size_t unknownStates = 0;
      std::size_t goodStates = 0;
      std::size_t reconnectStates = 0;
      for (auto cst : connectionStates) {
          switch (cst) {
              case ConnectionStatus::Disconnected:
                  ++unknownStates;
                  break;
              case ConnectionStatus::DisconnectInProgress: // count as unknown because we don't want resubscribes to trigger when a wrapper is in this state.
                  ++unknownStates;
                  break;
              case ConnectionStatus::ConnectInProgress: // count as unknown because the wrapper is not connected yet.
                  ++unknownStates;
                  break;
              case ConnectionStatus::ReconnectInProgress:
                  ++reconnectStates;
                  break;
              case ConnectionStatus::Connected:
                  ++goodStates;
                  break;
          }
      }
      auto newState = StateEnum::Unknown;
      if (reconnectStates > 0) {
          newState = StateEnum::ConnectionFailure;
      }
      else if (unknownStates > 0) {
          newState = StateEnum::Unknown;
      }
      else if (connectionStates.size() == goodStates) {
          newState = StateEnum::Good;
      }
      return newState;
  }
  
  void MqttClient::pushEvent(std::function<void()> ev)
  {
      m_eventQueue.push(ev);
  }
  
  void MqttClient::eventHandler()
  {
199d7075   Peter M. Groen   implement logging...
620
621
622
      LogInfo("[MqttClient::eventHandler]", std::string( m_clientId + " - starting event handler." ) );
      for (;;)
      {
51becbde   Peter M. Groen   Committed the ent...
623
624
625
626
627
628
629
630
631
632
          std::vector<std::function<void()>> events;
          if (!m_eventQueue.pop(events))
          {
              break;
          }
          for (const auto& ev : events)
          {
              ev();
          }
      }
199d7075   Peter M. Groen   implement logging...
633
      LogInfo("[MqttClient::eventHandler]", std::string( m_clientId + " - leaving event handler." ) );
51becbde   Peter M. Groen   Committed the ent...
634
  }
7771e50f   Steven   moved log.h to in...
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
  
  void MqttClient::setMask(log::LogMask logMask )
  {
      Log::setMask( logMask );
  }
  
  void MqttClient::setLogLevel(log::LogLevel logLevel)
  {
      Log::setLogLevel( logLevel );
  }
  
  void MqttClient::setContext(std::string context)
  {
      Log::setContext( context );
  }