Blame view

src/clientpaho.cpp 46.8 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
24
25
26
  #include "clientpaho.h"
  
  #include "errorcode.h"
  #include "mqttutil.h"
  #include "lockguard.h"
9421324b   Peter M. Groen   First fix on conn...
27
  #include "log.h"
51becbde   Peter M. Groen   Committed the ent...
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
  #include "metaprogrammingdefs.h"
  #include "mqttstream.h"
  #include "scopeguard.h"
  #include "uriparser.h"
  
  // std::chrono
  #include "compat-chrono.h"
  
  // std
  #include <algorithm>
  #include <iterator>
  
  using namespace osdev::components::mqtt;
  
  namespace {
  
  #if defined(__clang__)
  #pragma GCC diagnostic push
  #pragma GCC diagnostic ignored "-Wunused-template"
  #endif
  
  OSDEV_COMPONENTS_HASMEMBER_TRAIT(onSuccess5)
  
  template <typename TRet>
  inline typename std::enable_if<!has_onSuccess5<TRet>::value, TRet>::type initializeMqttStruct(TRet*)
  {
      return MQTTAsync_disconnectOptions_initializer;
  }
  
  template <typename TRet>
  inline typename std::enable_if<has_onSuccess5<TRet>::value, TRet>::type initializeMqttStruct(TRet*)
  {
  // For some reason g++ on centos7 evaluates the function body even when it is discarded by SFINAE.
  // This leads to a compile error on an undefined symbol. We will use the old initializer macro, but this
  // method should not be chosen when the struct does not contain member onSuccess5!
  // On yocto warrior mqtt-paho-c 1.3.0 the macro MQTTAsync_disconnectOptions_initializer5 is not defined.
  // while the struct does have an onSuccess5 member. In that case we do need correct initializer code.
  // We fall back to the MQTTAsync_disconnectOptions_initializer macro and initialize
  // additional fields ourself (which unfortunately results in a pesky compiler warning about missing field initializers).
  #ifndef MQTTAsync_disconnectOptions_initializer5
  #pragma GCC diagnostic push
  #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
      TRet ret = MQTTAsync_disconnectOptions_initializer;
      ret.struct_version = 1;
      ret.onSuccess5 = nullptr;
      ret.onFailure5 = nullptr;
      return ret;
  #pragma GCC diagnostic pop
  #else
      return MQTTAsync_disconnectOptions_initializer5;
  #endif
  }
  
  template <typename TRet>
  struct Init
  {
      static TRet initialize()
      {
          return initializeMqttStruct<TRet>(static_cast<TRet*>(nullptr));
      }
  };
  #if defined(__clang__)
  #pragma GCC diagnostic pop
  #endif
  
  } // namespace
  
  std::atomic_int ClientPaho::s_numberOfInstances(0);
  
  ClientPaho::ClientPaho(const std::string& _endpoint,
      const std::string& _id,
      const std::function<void(const std::string&, ConnectionStatus)>& connectionStatusCallback,
      const std::function<void(const std::string& clientId, std::int32_t pubMsgToken)>& deliveryCompleteCallback)
      : m_mutex()
      , m_endpoint()
      , m_username()
      , m_password()
      , m_clientId(_id)
      , m_pendingOperations()
      , m_operationResult()
      , m_operationsCompleteCV()
      , m_subscriptions()
      , m_pendingSubscriptions()
      , m_subscribeTokenToTopic()
      , m_unsubscribeTokenToTopic()
      , m_pendingPublishes()
      , m_processPendingPublishes(false)
      , m_pendingPublishesReadyCV()
      , m_client()
      , m_connectionStatus(ConnectionStatus::Disconnected)
      , m_connectionStatusCallback(connectionStatusCallback)
      , m_deliveryCompleteCallback(deliveryCompleteCallback)
      , m_lastUnsubscribe(-1)
      , m_connectPromise()
      , m_disconnectPromise()
      , m_callbackEventQueue(m_clientId)
      , m_workerThread()
  {
76d01373   Peter M. Groen   Fix on connection
126
127
      if (0 == s_numberOfInstances++)
      {
51becbde   Peter M. Groen   Committed the ent...
128
129
          MQTTAsync_setTraceCallback(&ClientPaho::onLogPaho);
      }
76d01373   Peter M. Groen   Fix on connection
130
131
  
      LogDebug( "[ClientPaho::ClientPaho]", std::string( " " + m_clientId + " - ctor ClientPaho ") );
51becbde   Peter M. Groen   Committed the ent...
132
      parseEndpoint(_endpoint);
76d01373   Peter M. Groen   Fix on connection
133
  
51becbde   Peter M. Groen   Committed the ent...
134
135
136
137
      auto rc = MQTTAsync_create(&m_client, m_endpoint.c_str(), m_clientId.c_str(), MQTTCLIENT_PERSISTENCE_NONE, nullptr);
      if (MQTTASYNC_SUCCESS == rc)
      {
          MQTTAsync_setCallbacks(m_client, reinterpret_cast<void*>(this), ClientPaho::onConnectionLost, ClientPaho::onMessageArrived, ClientPaho::onDeliveryComplete);
51becbde   Peter M. Groen   Committed the ent...
138
139
140
141
          m_workerThread = std::thread(&ClientPaho::callbackEventHandler, this);
      }
      else
      {
76d01373   Peter M. Groen   Fix on connection
142
          LogError( "[ClientPaho::ClientPaho]", std::string( m_clientId + " - Failed to create client for endpoint " + m_endpoint + ", return code " + pahoAsyncErrorCodeToString( rc ) ) );
51becbde   Peter M. Groen   Committed the ent...
143
144
145
146
147
      }
  }
  
  ClientPaho::~ClientPaho()
  {
76d01373   Peter M. Groen   Fix on connection
148
      LogDebug( "[ClientPaho::~ClientPaho]", std::string( m_clientId + " - dtor ClientPao" ) );
51becbde   Peter M. Groen   Committed the ent...
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
      if( MQTTAsync_isConnected( m_client ) )
      {
          this->unsubscribeAll();
  
          this->waitForCompletion(std::chrono::milliseconds(2000), std::set<int32_t>{});
          this->disconnect(true, 5000);
      }
      else
      {
          // If the status was already disconnected this call does nothing
          setConnectionStatus(ConnectionStatus::Disconnected);
      }
  
      if (0 == --s_numberOfInstances)
      {
          // encountered a case where termination of the logging system within paho led to a segfault.
          // This was a paho thread that was cleaned while at the same time the logging system was terminated.
          // Removing the trace callback will not solve the underlying problem but hopefully will trigger it less
          // frequently.
          MQTTAsync_setTraceCallback(nullptr);
      }
  
      MQTTAsync_destroy(&m_client);
  
      m_callbackEventQueue.stop();
      if (m_workerThread.joinable())
      {
          m_workerThread.join();
      }
  }
  
  std::string ClientPaho::clientId() const
  {
      return m_clientId;
  }
  
  ConnectionStatus ClientPaho::connectionStatus() const
  {
      return m_connectionStatus;
  }
  
31eece9b   Steven   added LWT ( last ...
190
  std::int32_t ClientPaho::connect( bool wait, const mqtt_LWT &lwt )
51becbde   Peter M. Groen   Committed the ent...
191
192
193
  {
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
2b967ea7   Steven   promise is not wo...
194
          if( ConnectionStatus::Disconnected != m_connectionStatus )
51becbde   Peter M. Groen   Committed the ent...
195
196
197
          {
              return -1;
          }
2b967ea7   Steven   promise is not wo...
198
          setConnectionStatus( ConnectionStatus::ConnectInProgress );
51becbde   Peter M. Groen   Committed the ent...
199
200
      }
  
76d01373   Peter M. Groen   Fix on connection
201
202
      LogInfo( "[ClientPaho::connect]", std::string( m_clientId + " - start connect to endpoint " + m_endpoint ) );
  
51becbde   Peter M. Groen   Committed the ent...
203
      MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
9421324b   Peter M. Groen   First fix on conn...
204
      conn_opts.keepAliveInterval = 5;
51becbde   Peter M. Groen   Committed the ent...
205
      conn_opts.cleansession = 1;
2c0c99a5   Peter M. Groen   Fix connect Callb...
206
      conn_opts.onSuccess = nullptr;
51becbde   Peter M. Groen   Committed the ent...
207
208
209
      conn_opts.onFailure = &ClientPaho::onConnectFailure;
      conn_opts.context = this;
      conn_opts.automaticReconnect = 1;
31eece9b   Steven   added LWT ( last ...
210
  
76d01373   Peter M. Groen   Fix on connection
211
212
213
214
215
216
217
218
219
220
221
222
      // Make sure we get a signal if the promise is fulfilled
      auto ccb = MQTTAsync_setConnected( m_client, reinterpret_cast<void*>(this), ClientPaho::onFirstConnect );
      if( MQTTASYNC_SUCCESS == ccb )
      {
          LogDebug( "[ClientPaho]", std::string( m_clientId + " - Setting the extra onConnected callback SUCCEEDED.") );
      }
      else
      {
          LogDebug( "[ClientPaho]", std::string( m_clientId + " - Setting the extra onConnected callback FAILED.") );
      }
  
      // Setup the last will and testament, if so desired.
31eece9b   Steven   added LWT ( last ...
223
224
225
226
227
228
229
      if( !lwt.topic().empty() )
      {
          MQTTAsync_willOptions will_opts = MQTTAsync_willOptions_initializer;
          will_opts.message = lwt.message().c_str();
          will_opts.topicName = lwt.topic().c_str();
  
          conn_opts.will = &will_opts;
76d01373   Peter M. Groen   Fix on connection
230
231
  
          LogDebug( "[ClientPaho::connect]", std::string( m_clientId + " - Set Last will and testament. Topic : " + lwt.topic() + " => Message : " + lwt.message() ) );
31eece9b   Steven   added LWT ( last ...
232
233
234
235
236
237
238
      }
      else
      {
          conn_opts.will = nullptr;
      }
  
  
2b967ea7   Steven   promise is not wo...
239
      if( !m_username.empty() )
51becbde   Peter M. Groen   Committed the ent...
240
241
242
243
      {
          conn_opts.username = m_username.c_str();
      }
  
2b967ea7   Steven   promise is not wo...
244
      if( !m_password.empty() )
51becbde   Peter M. Groen   Committed the ent...
245
246
247
248
249
250
251
      {
          conn_opts.password = m_password.c_str();
      }
  
      std::promise<void> waitForConnectPromise{};
      auto waitForConnect = waitForConnectPromise.get_future();
      m_connectPromise.reset();
2b967ea7   Steven   promise is not wo...
252
      if( wait )
51becbde   Peter M. Groen   Committed the ent...
253
      {
2b967ea7   Steven   promise is not wo...
254
          m_connectPromise = std::make_unique<std::promise<void>>( std::move( waitForConnectPromise ) );
51becbde   Peter M. Groen   Committed the ent...
255
256
257
      }
  
      {
2b967ea7   Steven   promise is not wo...
258
259
          OSDEV_COMPONENTS_LOCKGUARD( m_mutex );
          if( !m_pendingOperations.insert( -100 ).second )
51becbde   Peter M. Groen   Committed the ent...
260
261
262
          {
              // Write something
          }
2b967ea7   Steven   promise is not wo...
263
          m_operationResult.erase( -100 );
51becbde   Peter M. Groen   Committed the ent...
264
265
      }
  
2b967ea7   Steven   promise is not wo...
266
267
      int rc = MQTTAsync_connect( m_client, &conn_opts );
      if( MQTTASYNC_SUCCESS != rc )
51becbde   Peter M. Groen   Committed the ent...
268
      {
2b967ea7   Steven   promise is not wo...
269
270
          setConnectionStatus( ConnectionStatus::Disconnected );
          OSDEV_COMPONENTS_LOCKGUARD( m_mutex );
51becbde   Peter M. Groen   Committed the ent...
271
272
273
274
          m_operationResult[-100] = false;
          m_pendingOperations.erase(-100);
      }
  
2b967ea7   Steven   promise is not wo...
275
      if( wait )
51becbde   Peter M. Groen   Committed the ent...
276
277
278
279
280
281
282
      {
          waitForConnect.get();
          m_connectPromise.reset();
      }
      return -100;
  }
  
0c424e03   Steven   syntax fixes. WIP
283
  std::int32_t ClientPaho::disconnect( bool wait, int timeoutMs )
51becbde   Peter M. Groen   Committed the ent...
284
285
286
287
288
  {
      ConnectionStatus currentStatus = m_connectionStatus;
  
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
0c424e03   Steven   syntax fixes. WIP
289
290
          if( ConnectionStatus::Disconnected == m_connectionStatus || ConnectionStatus::DisconnectInProgress == m_connectionStatus )
          {
51becbde   Peter M. Groen   Committed the ent...
291
292
293
294
              return -1;
          }
  
          currentStatus = m_connectionStatus;
0c424e03   Steven   syntax fixes. WIP
295
          setConnectionStatus( ConnectionStatus::DisconnectInProgress );
51becbde   Peter M. Groen   Committed the ent...
296
297
298
299
300
301
302
303
304
305
306
      }
  
      MQTTAsync_disconnectOptions disconn_opts = Init<MQTTAsync_disconnectOptions>::initialize();
      disconn_opts.timeout = timeoutMs;
      disconn_opts.onSuccess = &ClientPaho::onDisconnectSuccess;
      disconn_opts.onFailure = &ClientPaho::onDisconnectFailure;
      disconn_opts.context = this;
  
      std::promise<void> waitForDisconnectPromise{};
      auto waitForDisconnect = waitForDisconnectPromise.get_future();
      m_disconnectPromise.reset();
0c424e03   Steven   syntax fixes. WIP
307
308
      if( wait )
      {
51becbde   Peter M. Groen   Committed the ent...
309
310
311
312
313
314
315
          m_disconnectPromise = std::make_unique<std::promise<void>>(std::move(waitForDisconnectPromise));
      }
  
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          if (!m_pendingOperations.insert(-200).second)
          {
0c424e03   Steven   syntax fixes. WIP
316
              //"ClientPaho", "%1 disconnect - token %2 already in use", m_clientId, -200)
51becbde   Peter M. Groen   Committed the ent...
317
318
319
320
321
          }
          m_operationResult.erase(-200);
      }
  
      int rc = MQTTAsync_disconnect(m_client, &disconn_opts);
0c424e03   Steven   syntax fixes. WIP
322
      if( MQTTASYNC_SUCCESS != rc )
76d01373   Peter M. Groen   Fix on connection
323
      {
0c424e03   Steven   syntax fixes. WIP
324
          if( MQTTASYNC_DISCONNECTED == rc )
76d01373   Peter M. Groen   Fix on connection
325
          {
51becbde   Peter M. Groen   Committed the ent...
326
327
328
              currentStatus = ConnectionStatus::Disconnected;
          }
  
0c424e03   Steven   syntax fixes. WIP
329
330
          setConnectionStatus( currentStatus );
          OSDEV_COMPONENTS_LOCKGUARD( m_mutex );
51becbde   Peter M. Groen   Committed the ent...
331
332
333
          m_operationResult[-200] = false;
          m_pendingOperations.erase(-200);
  
0c424e03   Steven   syntax fixes. WIP
334
          if( MQTTASYNC_DISCONNECTED == rc )
2b967ea7   Steven   promise is not wo...
335
          {
51becbde   Peter M. Groen   Committed the ent...
336
337
              return -1;
          }
0c424e03   Steven   syntax fixes. WIP
338
          // ("ClientPaho", std::string( "%1 - failed to disconnect, return code %2" ).arg( m_clientId ).arg( pahoAsyncErrorCodeToString(rc)) );
51becbde   Peter M. Groen   Committed the ent...
339
340
      }
  
2b967ea7   Steven   promise is not wo...
341
342
      if( wait )
      {
51becbde   Peter M. Groen   Committed the ent...
343
344
345
346
347
348
349
350
351
352
353
354
355
          if (std::future_status::timeout == waitForDisconnect.wait_for(std::chrono::milliseconds(timeoutMs + 100)))
          {
              // ("ClientPaho", "%1 - timeout occurred on disconnect", m_clientId);
  
          }
          waitForDisconnect.get();
          m_disconnectPromise.reset();
      }
      return -200;
  }
  
  std::int32_t ClientPaho::publish(const MqttMessage& message, int qos)
  {
0c424e03   Steven   syntax fixes. WIP
356
      if( ConnectionStatus::DisconnectInProgress == m_connectionStatus )
51becbde   Peter M. Groen   Committed the ent...
357
358
359
360
      {
          // ("ClientPaho", "%1 - disconnect in progress, ignoring publish with qos %2 on topic %3", m_clientId, qos, message.topic());
          return -1;
      }
0c424e03   Steven   syntax fixes. WIP
361
      else if( ConnectionStatus::Disconnected == m_connectionStatus )
51becbde   Peter M. Groen   Committed the ent...
362
363
      {
          // ("ClientPaho", "%1 - unable to publish, not connected", m_clientId);
2b967ea7   Steven   promise is not wo...
364
          connect( true );
51becbde   Peter M. Groen   Committed the ent...
365
366
      }
  
0c424e03   Steven   syntax fixes. WIP
367
      if( !isValidTopic(message.topic() ) )
51becbde   Peter M. Groen   Committed the ent...
368
369
370
371
      {
          // ("ClientPaho", "%1 - topic %2 is invalid", m_clientId, message.topic());
      }
  
0c424e03   Steven   syntax fixes. WIP
372
      if( qos > 2 )
51becbde   Peter M. Groen   Committed the ent...
373
374
375
      {
          qos = 2;
      }
0c424e03   Steven   syntax fixes. WIP
376
      else if( qos < 0 )
51becbde   Peter M. Groen   Committed the ent...
377
378
379
380
      {
          qos = 0;
      }
  
51becbde   Peter M. Groen   Committed the ent...
381
      std::unique_lock<std::mutex> lck(m_mutex);
a670240b   Peter M. Groen   Fix on connection
382
      if (ConnectionStatus::ReconnectInProgress == m_connectionStatus || m_processPendingPublishes)
a670240b   Peter M. Groen   Fix on connection
383
      {
51becbde   Peter M. Groen   Committed the ent...
384
          m_pendingPublishesReadyCV.wait(lck, [this]() { return !m_processPendingPublishes; });
a670240b   Peter M. Groen   Fix on connection
385
386
          if(ConnectionStatus::ReconnectInProgress == m_connectionStatus)
          {
0c424e03   Steven   syntax fixes. WIP
387
              LogDebug( "[ClientPaho::publish]", "Adding publish to pending queue." );
51becbde   Peter M. Groen   Committed the ent...
388
389
390
391
392
              m_pendingPublishes.push_front(Publish{ qos, message });
              return -1;
          }
      }
  
0c424e03   Steven   syntax fixes. WIP
393
      return publishInternal( message, qos );
51becbde   Peter M. Groen   Committed the ent...
394
395
396
397
398
399
  }
  
  void ClientPaho::publishPending()
  {
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
0c424e03   Steven   syntax fixes. WIP
400
          if( !m_processPendingPublishes )
2b967ea7   Steven   promise is not wo...
401
          {
51becbde   Peter M. Groen   Committed the ent...
402
403
404
405
              return;
          }
      }
  
0c424e03   Steven   syntax fixes. WIP
406
      if( ConnectionStatus::Connected != m_connectionStatus )
51becbde   Peter M. Groen   Committed the ent...
407
      {
a670240b   Peter M. Groen   Fix on connection
408
          LogInfo( "[ClientPaho::publishPending]", std::string( m_clientId + " - " ) )
51becbde   Peter M. Groen   Committed the ent...
409
410
      }
  
0c424e03   Steven   syntax fixes. WIP
411
      while( !m_pendingPublishes.empty() )
51becbde   Peter M. Groen   Committed the ent...
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
      {
          const auto& pub = m_pendingPublishes.back();
          publishInternal(pub.data, pub.qos);
          // else ("ClientPaho", "%1 - pending publish on topic %2 failed : %3", m_clientId, pub.data.topic(), e.what());
  
          m_pendingPublishes.pop_back();
      }
  
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          m_processPendingPublishes = false;
      }
      m_pendingPublishesReadyCV.notify_all();
  }
  
0c424e03   Steven   syntax fixes. WIP
427
  std::int32_t ClientPaho::subscribe( const std::string& topic, int qos, const std::function<void(MqttMessage msg)>& cb )
51becbde   Peter M. Groen   Committed the ent...
428
  {
0c424e03   Steven   syntax fixes. WIP
429
      if( ConnectionStatus::Connected != m_connectionStatus )
51becbde   Peter M. Groen   Committed the ent...
430
431
432
433
      {
          // MqttException, "Not connected"
      }
  
0c424e03   Steven   syntax fixes. WIP
434
      if( !isValidTopic( topic ) )
51becbde   Peter M. Groen   Committed the ent...
435
436
437
438
      {
          // ("ClientPaho", "%1 - topic %2 is invalid", m_clientId, topic);
      }
  
0c424e03   Steven   syntax fixes. WIP
439
      if( qos > 2 )
51becbde   Peter M. Groen   Committed the ent...
440
441
442
      {
          qos = 2;
      }
0c424e03   Steven   syntax fixes. WIP
443
      else if( qos < 0 )
51becbde   Peter M. Groen   Committed the ent...
444
445
446
447
448
449
450
451
      {
          qos = 0;
      }
  
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
  
          auto itExisting = m_subscriptions.find(topic);
0c424e03   Steven   syntax fixes. WIP
452
453
454
455
          if( m_subscriptions.end() != itExisting )
          {
              if( itExisting->second.qos == qos )
              {
51becbde   Peter M. Groen   Committed the ent...
456
457
458
459
460
461
                  return -1;
              }
              // (OverlappingTopicException, "existing subscription with same topic, but different qos", topic);
          }
  
          auto itPending = m_pendingSubscriptions.find(topic);
0c424e03   Steven   syntax fixes. WIP
462
463
464
465
466
467
468
          if( m_pendingSubscriptions.end() != itPending )
          {
              if( itPending->second.qos == qos )
              {
                  auto itToken = std::find_if( m_subscribeTokenToTopic.begin(), m_subscribeTokenToTopic.end(), [&topic](const std::pair<MQTTAsync_token, std::string>& item) { return topic == item.second; } );
                  if( m_subscribeTokenToTopic.end() != itToken )
                  {
51becbde   Peter M. Groen   Committed the ent...
469
470
                      return itToken->first;
                  }
0c424e03   Steven   syntax fixes. WIP
471
472
                  else
                  {
51becbde   Peter M. Groen   Committed the ent...
473
474
475
476
477
478
479
                      return -1;
                  }
              }
              // (OverlappingTopicException, "pending subscription with same topic, but different qos", topic);
          }
  
          std::string existingTopic{};
0c424e03   Steven   syntax fixes. WIP
480
          if( isOverlappingInternal( topic, existingTopic ) )
51becbde   Peter M. Groen   Committed the ent...
481
482
483
484
485
          {
              // (OverlappingTopicException, "overlapping topic", existingTopic, topic);
          }
  
          // ("ClientPaho", "%1 - adding subscription on topic %2 to the pending subscriptions", m_clientId, topic);
0c424e03   Steven   syntax fixes. WIP
486
          m_pendingSubscriptions.emplace( std::make_pair( topic, Subscription{ qos, boost::regex(convertTopicToRegex(topic)), cb } ) );
51becbde   Peter M. Groen   Committed the ent...
487
      }
0c424e03   Steven   syntax fixes. WIP
488
      return subscribeInternal( topic, qos );
51becbde   Peter M. Groen   Committed the ent...
489
490
491
492
493
494
495
496
497
498
  }
  
  void ClientPaho::resubscribe()
  {
      decltype(m_pendingSubscriptions) pendingSubscriptions{};
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          std::copy(m_pendingSubscriptions.begin(), m_pendingSubscriptions.end(), std::inserter(pendingSubscriptions, pendingSubscriptions.end()));
      }
  
0c424e03   Steven   syntax fixes. WIP
499
      for( const auto& s : pendingSubscriptions )
51becbde   Peter M. Groen   Committed the ent...
500
      {
0c424e03   Steven   syntax fixes. WIP
501
          subscribeInternal( s.first, s.second.qos );
51becbde   Peter M. Groen   Committed the ent...
502
503
504
      }
  }
  
31eece9b   Steven   added LWT ( last ...
505
  std::int32_t ClientPaho::unsubscribe( const std::string& topic, int qos )
51becbde   Peter M. Groen   Committed the ent...
506
507
  {
      {
0c424e03   Steven   syntax fixes. WIP
508
          OSDEV_COMPONENTS_LOCKGUARD( m_mutex );
51becbde   Peter M. Groen   Committed the ent...
509
          bool found = false;
0c424e03   Steven   syntax fixes. WIP
510
          for( const auto& s : m_subscriptions )
51becbde   Peter M. Groen   Committed the ent...
511
          {
0c424e03   Steven   syntax fixes. WIP
512
              if( topic == s.first && qos == s.second.qos )
51becbde   Peter M. Groen   Committed the ent...
513
514
515
516
517
              {
                  found = true;
                  break;
              }
          }
0c424e03   Steven   syntax fixes. WIP
518
          if( !found )
51becbde   Peter M. Groen   Committed the ent...
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
          {
              return -1;
          }
      }
  
      MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
      opts.onSuccess = &ClientPaho::onUnsubscribeSuccess;
      opts.onFailure = &ClientPaho::onUnsubscribeFailure;
      opts.context = this;
  
      {
          // Need to lock the mutex because it is possible that the callback is faster than
          // the insertion of the token into the pending operations.
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          auto rc = MQTTAsync_unsubscribe(m_client, topic.c_str(), &opts);
0c424e03   Steven   syntax fixes. WIP
534
          if( MQTTASYNC_SUCCESS != rc )
51becbde   Peter M. Groen   Committed the ent...
535
536
537
538
          {
              // ("ClientPaho", "%1 - unsubscribe on topic %2 failed with code %3", m_clientId, topic, pahoAsyncErrorCodeToString(rc));
          }
  
0c424e03   Steven   syntax fixes. WIP
539
          if( !m_pendingOperations.insert( opts.token ).second )
51becbde   Peter M. Groen   Committed the ent...
540
541
542
543
          {
              // ("ClientPaho", "%1 unsubscribe - token %2 already in use", m_clientId, opts.token);
          }
  
0c424e03   Steven   syntax fixes. WIP
544
545
          m_operationResult.erase( opts.token );
          if( m_unsubscribeTokenToTopic.count( opts.token ) > 0 )
51becbde   Peter M. Groen   Committed the ent...
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
          {
              // ("ClientPaho", "%1 - token already in use, replacing unsubscribe from topic %2 with topic %3", m_clientId, m_unsubscribeTokenToTopic[opts.token], topic);
          }
          m_lastUnsubscribe = opts.token; // centos7 workaround
          m_unsubscribeTokenToTopic[opts.token] = topic;
      }
  
      // Because of a bug in paho-c on centos7 the unsubscribes need to be sequential (best effort).
      this->waitForCompletion(std::chrono::seconds(1), std::set<int32_t>{ opts.token });
  
      return opts.token;
  }
  
  void ClientPaho::unsubscribeAll()
  {
0c424e03   Steven   syntax fixes. WIP
561
      decltype( m_subscriptions ) subscriptions{};
51becbde   Peter M. Groen   Committed the ent...
562
563
564
565
566
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          subscriptions = m_subscriptions;
      }
  
0c424e03   Steven   syntax fixes. WIP
567
568
      for( const auto& s : subscriptions )
      {
51becbde   Peter M. Groen   Committed the ent...
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
          this->unsubscribe(s.first, s.second.qos);
      }
  }
  
  std::chrono::milliseconds ClientPaho::waitForCompletion(std::chrono::milliseconds waitFor, const std::set<std::int32_t>& tokens) const
  {
      if (waitFor <= std::chrono::milliseconds(0)) {
          return std::chrono::milliseconds(0);
      }
      std::chrono::milliseconds timeElapsed{};
      {
          osdev::components::mqtt::measurement::TimeMeasurement msr("waitForCompletion", [&timeElapsed](const std::string&, std::chrono::steady_clock::time_point, std::chrono::microseconds sinceStart, std::chrono::microseconds)
          {
              timeElapsed = std::chrono::ceil<std::chrono::milliseconds>(sinceStart);
          });
          std::unique_lock<std::mutex> lck(m_mutex);
          // ("ClientPaho", "%1 waitForCompletion - pending operations : %2", m_clientId, m_pendingOperations);
          m_operationsCompleteCV.wait_for(lck, waitFor, [this, &tokens]()
          {
              if (tokens.empty())
              { // wait for all operations to end
                  return m_pendingOperations.empty();
              }
              else if (tokens.size() == 1)
              {
                  return m_pendingOperations.find(*tokens.cbegin()) == m_pendingOperations.end();
              }
              std::vector<std::int32_t> intersect{};
              std::set_intersection(m_pendingOperations.begin(), m_pendingOperations.end(), tokens.begin(), tokens.end(), std::back_inserter(intersect));
              return intersect.empty();
          } );
      }
      return timeElapsed;
  }
  
  bool ClientPaho::isOverlapping(const std::string& topic) const
  {
      std::string existingTopic{};
      return isOverlapping(topic, existingTopic);
  }
  
  bool ClientPaho::isOverlapping(const std::string& topic, std::string& existingTopic) const
  {
      OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
      return isOverlappingInternal(topic, existingTopic);
  }
  
  std::vector<std::int32_t> ClientPaho::pendingOperations() const
  {
      OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
      std::vector<std::int32_t> retval{};
      retval.resize(m_pendingOperations.size());
      std::copy(m_pendingOperations.begin(), m_pendingOperations.end(), retval.begin());
      return retval;
  }
  
  bool ClientPaho::hasPendingSubscriptions() const
  {
      OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
      return !m_pendingSubscriptions.empty();
  }
  
  boost::optional<bool> ClientPaho::operationResult(std::int32_t token) const
  {
      OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
      boost::optional<bool> ret{};
      auto cit = m_operationResult.find(token);
      if (m_operationResult.end() != cit)
      {
          ret = cit->second;
      }
      return ret;
  }
  
  void ClientPaho::parseEndpoint(const std::string& _endpoint)
  {
      auto ep = UriParser::parse(_endpoint);
      if (ep.find("user") != ep.end())
      {
          m_username = ep["user"];
          ep["user"].clear();
      }
  
      if (ep.find("password") != ep.end())
      {
          m_password = ep["password"];
          ep["password"].clear();
      }
      m_endpoint = UriParser::toString(ep);
  }
  
  std::int32_t ClientPaho::publishInternal(const MqttMessage& message, int qos)
  {
      MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
      opts.onSuccess = &ClientPaho::onPublishSuccess;
      opts.onFailure = &ClientPaho::onPublishFailure;
      opts.context = this;
      auto msg = message.toAsyncMessage();
      msg.qos = qos;
  
      // Need to lock the mutex because it is possible that the callback is faster than
      // the insertion of the token into the pending operations.
  
      // OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
      auto rc = MQTTAsync_sendMessage(m_client, message.topic().c_str(), &msg, &opts);
      if (MQTTASYNC_SUCCESS != rc)
      {
          // ("ClientPaho", "%1 - publish on topic %2 failed with code %3", m_clientId, message.topic(), pahoAsyncErrorCodeToString(rc));
      }
  
      if (!m_pendingOperations.insert(opts.token).second)
      {
          // ("ClientPaho", "%1 publishInternal - token %2 already in use", m_clientId, opts.token);
      }
      m_operationResult.erase(opts.token);
      return opts.token;
  }
  
  std::int32_t ClientPaho::subscribeInternal(const std::string& topic, int qos)
  {
      MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
      opts.onSuccess = &ClientPaho::onSubscribeSuccess;
      opts.onFailure = &ClientPaho::onSubscribeFailure;
      opts.context = this;
  
      // Need to lock the mutex because it is possible that the callback is faster than
      // the insertion of the token into the pending operations.
      OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
      auto rc = MQTTAsync_subscribe(m_client, topic.c_str(), qos, &opts);
      if (MQTTASYNC_SUCCESS != rc)
      {
          m_pendingSubscriptions.erase(topic);
          // ("ClientPaho", "%1 - subscription on topic %2 failed with code %3", m_clientId, topic, pahoAsyncErrorCodeToString(rc));
          // (MqttException, "Subscription failed");
      }
  
      if (!m_pendingOperations.insert(opts.token).second)
      {
          // ("ClientPaho", "%1 subscribe - token %2 already in use", m_clientId, opts.token);
      }
      m_operationResult.erase(opts.token);
      if (m_subscribeTokenToTopic.count(opts.token) > 0)
      {
          // ("ClientPaho", "%1 - overwriting pending subscription on topic %2 with topic %3", m_clientId, m_subscribeTokenToTopic[opts.token], topic);
      }
      m_subscribeTokenToTopic[opts.token] = topic;
      return opts.token;
  }
  
0c424e03   Steven   syntax fixes. WIP
718
  void ClientPaho::setConnectionStatus( ConnectionStatus status )
51becbde   Peter M. Groen   Committed the ent...
719
720
721
  {
      ConnectionStatus curStatus = m_connectionStatus;
      m_connectionStatus = status;
0c424e03   Steven   syntax fixes. WIP
722
      if( status != curStatus && m_connectionStatusCallback )
51becbde   Peter M. Groen   Committed the ent...
723
      {
0c424e03   Steven   syntax fixes. WIP
724
          m_connectionStatusCallback( m_clientId, status );
51becbde   Peter M. Groen   Committed the ent...
725
726
727
      }
  }
  
0c424e03   Steven   syntax fixes. WIP
728
  bool ClientPaho::isOverlappingInternal( const std::string& topic, std::string& existingTopic ) const
51becbde   Peter M. Groen   Committed the ent...
729
730
  {
      existingTopic.clear();
0c424e03   Steven   syntax fixes. WIP
731
      for( const auto& s : m_pendingSubscriptions )
51becbde   Peter M. Groen   Committed the ent...
732
      {
0c424e03   Steven   syntax fixes. WIP
733
          if( testForOverlap( s.first, topic ) )
51becbde   Peter M. Groen   Committed the ent...
734
735
736
737
738
739
          {
              existingTopic = s.first;
              return true;
          }
      }
  
0c424e03   Steven   syntax fixes. WIP
740
      for( const auto& s : m_subscriptions )
51becbde   Peter M. Groen   Committed the ent...
741
      {
0c424e03   Steven   syntax fixes. WIP
742
          if( testForOverlap(s.first, topic ) )
51becbde   Peter M. Groen   Committed the ent...
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
          {
              existingTopic = s.first;
              return true;
          }
      }
      return false;
  }
  
  void ClientPaho::pushIncomingEvent(std::function<void()> ev)
  {
      m_callbackEventQueue.push(ev);
  }
  
  void ClientPaho::callbackEventHandler()
  {
0c424e03   Steven   syntax fixes. WIP
758
759
760
      LogDebug( "[ClientPaho::callbackEventHandler]", std::string( m_clientId + " - starting callback event handler") );
      for( ;; )
      {
51becbde   Peter M. Groen   Committed the ent...
761
          std::vector<std::function<void()>> events;
0c424e03   Steven   syntax fixes. WIP
762
          if( !m_callbackEventQueue.pop(events) )
51becbde   Peter M. Groen   Committed the ent...
763
764
765
766
          {
              break;
          }
  
0c424e03   Steven   syntax fixes. WIP
767
          for( const auto& ev : events )
51becbde   Peter M. Groen   Committed the ent...
768
769
          {
              ev();
51becbde   Peter M. Groen   Committed the ent...
770
771
772
773
          }
      }
      // ("ClientPaho", "%1 - leaving callback event handler", m_clientId);
  }
0c424e03   Steven   syntax fixes. WIP
774
  void ClientPaho::onConnectOnInstance( const std::string& cause )
51becbde   Peter M. Groen   Committed the ent...
775
776
  {
      (void)cause;
51becbde   Peter M. Groen   Committed the ent...
777
778
779
780
781
782
783
784
785
786
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          std::copy(m_subscriptions.begin(), m_subscriptions.end(), std::inserter(m_pendingSubscriptions, m_pendingSubscriptions.end()));
          m_subscriptions.clear();
          m_processPendingPublishes = true; // all publishes are on hold until publishPending is called.
      }
  
      setConnectionStatus(ConnectionStatus::Connected);
  }
  
2c0c99a5   Peter M. Groen   Fix connect Callb...
787
  void ClientPaho::onConnectSuccessOnInstance()
51becbde   Peter M. Groen   Committed the ent...
788
  {
51becbde   Peter M. Groen   Committed the ent...
789
790
791
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          // Register the connect callback that is used in reconnect scenarios.
0c424e03   Steven   syntax fixes. WIP
792
793
          auto rc = MQTTAsync_setConnected( m_client, this, &ClientPaho::onConnect );
          if( MQTTASYNC_SUCCESS != rc )
51becbde   Peter M. Groen   Committed the ent...
794
          {
0c424e03   Steven   syntax fixes. WIP
795
              LogError( "[ClientPaho::onConnectSuccessOnInstance]", std::string( "onConnectSuccesOnInstance " + m_clientId + " - registering the connected callback failed with code : " + pahoAsyncErrorCodeToString(rc) ) );
51becbde   Peter M. Groen   Committed the ent...
796
          }
2c0c99a5   Peter M. Groen   Fix connect Callb...
797
  
51becbde   Peter M. Groen   Committed the ent...
798
799
800
801
802
803
          // For MQTTV5
          //rc = MQTTAsync_setDisconnected(m_client, this, &ClientPaho::onDisconnect);
          //if (MQTTASYNC_SUCCESS != rc) {
          //    // ("ClientPaho", "onConnectSuccessOnInstance %1 - registering the disconnected callback failed with code %2", m_clientId, pahoAsyncErrorCodeToString(rc));
          //}
          // ("ClientPaho", "onConnectSuccessOnInstance %1 - pending operations : %2, removing operation -100", m_clientId, m_pendingOperations);
2c0c99a5   Peter M. Groen   Fix connect Callb...
804
  
51becbde   Peter M. Groen   Committed the ent...
805
806
807
          m_operationResult[-100] = true;
          m_pendingOperations.erase(-100);
      }
9421324b   Peter M. Groen   First fix on conn...
808
  
0c424e03   Steven   syntax fixes. WIP
809
810
      setConnectionStatus( ConnectionStatus::Connected );
      if( m_connectPromise )
51becbde   Peter M. Groen   Committed the ent...
811
      {
0c424e03   Steven   syntax fixes. WIP
812
          LogDebug( "[ClientPaho::onConnectSuccessOnInstance]", std::string("connectPromise still present. Resetting!") );
51becbde   Peter M. Groen   Committed the ent...
813
814
815
816
817
          m_connectPromise->set_value();
      }
      m_operationsCompleteCV.notify_all();
  }
  
0c424e03   Steven   syntax fixes. WIP
818
  void ClientPaho::onConnectFailureOnInstance( const MqttFailure& response )
51becbde   Peter M. Groen   Committed the ent...
819
  {
0c424e03   Steven   syntax fixes. WIP
820
821
      (void) response;
      LogDebug( "[ClientPaho::onConnectFailureOnInstance]", std::string( "onConnectFailureOnInstance" + m_clientId + " - connection failed with code " + response.codeToString() + " (" + response.message() + ")"));
51becbde   Peter M. Groen   Committed the ent...
822
823
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
51becbde   Peter M. Groen   Committed the ent...
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
          // ("ClientPaho", "onConnectFailureOnInstance %1 - pending operations : %2, removing operation -100", m_clientId, m_pendingOperations);
          m_operationResult[-100] = false;
          m_pendingOperations.erase(-100);
      }
      if (ConnectionStatus::ConnectInProgress == m_connectionStatus)
      {
          setConnectionStatus(ConnectionStatus::Disconnected);
      }
      m_operationsCompleteCV.notify_all();
  }
  
  //void ClientPaho::onDisconnectOnInstance(enum MQTTReasonCodes reasonCode)
  //{
  //    MLOGIC_COMMON_INFO("ClientPaho", "onDisconnectOnInstance %1 - disconnect (reason %2)", MQTTReasonCode_toString(reasonCode));
  //}
  
  void ClientPaho::onDisconnectSuccessOnInstance(const MqttSuccess&)
  {
      // ("ClientPaho", "onDisconnectSuccessOnInstance %1 - disconnected from endpoint %2", m_clientId, m_endpoint);
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          m_subscriptions.clear();
          m_pendingSubscriptions.clear();
          m_subscribeTokenToTopic.clear();
          m_unsubscribeTokenToTopic.clear();
  
          // ("ClientPaho", "onDisconnectSuccessOnInstance %1 - pending operations : %2, removing all operations", m_clientId, m_pendingOperations);
          m_operationResult[-200] = true;
          m_pendingOperations.clear();
      }
  
0c424e03   Steven   syntax fixes. WIP
855
      setConnectionStatus( ConnectionStatus::Disconnected );
51becbde   Peter M. Groen   Committed the ent...
856
  
0c424e03   Steven   syntax fixes. WIP
857
858
      if( m_disconnectPromise )
      {
51becbde   Peter M. Groen   Committed the ent...
859
860
861
862
863
          m_disconnectPromise->set_value();
      }
      m_operationsCompleteCV.notify_all();
  }
  
0c424e03   Steven   syntax fixes. WIP
864
  void ClientPaho::onDisconnectFailureOnInstance( const MqttFailure& response )
51becbde   Peter M. Groen   Committed the ent...
865
  {
0c424e03   Steven   syntax fixes. WIP
866
      (void) response;
51becbde   Peter M. Groen   Committed the ent...
867
868
869
870
871
872
873
874
      // ("ClientPaho", "onDisconnectFailureOnInstance %1 - disconnect failed with code %2 (%3)", m_clientId, response.codeToString(), response.message());
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          // ("ClientPaho", "onDisconnectFailureOnInstance %1 - pending operations : %2, removing operation -200", m_clientId, m_pendingOperations);
          m_operationResult[-200] = false;
          m_pendingOperations.erase(-200);
      }
  
0c424e03   Steven   syntax fixes. WIP
875
      if( MQTTAsync_isConnected( m_client ) )
51becbde   Peter M. Groen   Committed the ent...
876
      {
0c424e03   Steven   syntax fixes. WIP
877
          setConnectionStatus( ConnectionStatus::Connected );
51becbde   Peter M. Groen   Committed the ent...
878
879
880
      }
      else
      {
0c424e03   Steven   syntax fixes. WIP
881
          setConnectionStatus( ConnectionStatus::Disconnected );
51becbde   Peter M. Groen   Committed the ent...
882
883
      }
  
0c424e03   Steven   syntax fixes. WIP
884
      if( m_disconnectPromise )
51becbde   Peter M. Groen   Committed the ent...
885
886
887
888
889
890
      {
          m_disconnectPromise->set_value();
      }
      m_operationsCompleteCV.notify_all();
  }
  
0c424e03   Steven   syntax fixes. WIP
891
  void ClientPaho::onPublishSuccessOnInstance( const MqttSuccess& response )
51becbde   Peter M. Groen   Committed the ent...
892
893
894
895
896
897
898
899
900
901
902
903
  {
      auto pd = response.publishData();
      // ("ClientPaho", "onPublishSuccessOnInstance %1 - publish with token %2 succeeded (message was %3)", m_clientId, response.token(), pd.payload());
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          // ("ClientPaho", "onPublishSuccessOnInstance %1 - pending operations : %2, removing operation %3", m_clientId, m_pendingOperations, response.token());
          m_operationResult[response.token()] = true;
          m_pendingOperations.erase(response.token());
      }
      m_operationsCompleteCV.notify_all();
  }
  
0c424e03   Steven   syntax fixes. WIP
904
  void ClientPaho::onPublishFailureOnInstance( const MqttFailure& response )
51becbde   Peter M. Groen   Committed the ent...
905
906
907
908
909
910
911
912
913
914
915
  {
      // ("ClientPaho", "onPublishFailureOnInstance %1 - publish with token %2 failed with code %3 (%4)", m_clientId, response.token(), response.codeToString(), response.message());
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          // ("ClientPaho", "onPublishFailureOnInstance %1 - pending operations : %2, removing operation %3", m_clientId, m_pendingOperations, response.token());
          m_operationResult[response.token()] = false;
          m_pendingOperations.erase(response.token());
      }
      m_operationsCompleteCV.notify_all();
  }
  
0c424e03   Steven   syntax fixes. WIP
916
  void ClientPaho::onSubscribeSuccessOnInstance( const MqttSuccess& response )
51becbde   Peter M. Groen   Committed the ent...
917
918
919
920
921
922
923
924
925
926
927
928
  {
      // ("ClientPaho", "onSubscribeSuccessOnInstance %1 - subscribe with token %2 succeeded", m_clientId, response.token());
      OSDEV_COMPONENTS_SCOPEGUARD(m_operationsCompleteCV, [this]() { m_operationsCompleteCV.notify_all(); });
      OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
      bool operationOk = false;
      OSDEV_COMPONENTS_SCOPEGUARD(m_pendingOperations, [this, &response, &operationOk]()
      {
          // ("ClientPaho", "onSubscribeSuccessOnInstance %1 - pending operations : %2, removing operation %3", m_clientId, m_pendingOperations, response.token());
          m_operationResult[response.token()] = operationOk;
          m_pendingOperations.erase(response.token());
      });
      auto it = m_subscribeTokenToTopic.find(response.token());
0c424e03   Steven   syntax fixes. WIP
929
930
      if (m_subscribeTokenToTopic.end() == it)
      {
51becbde   Peter M. Groen   Committed the ent...
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
          // ("ClientPaho", "onSubscribeSuccessOnInstance %1 - unknown token %2", m_clientId, response.token());
          return;
      }
      auto topic = it->second;
      m_subscribeTokenToTopic.erase(it);
  
      auto pendingIt = m_pendingSubscriptions.find(topic);
      if (m_pendingSubscriptions.end() == pendingIt)
      {
          // ("ClientPaho", "onSubscribeSuccessOnInstance %1 - cannot find pending subscription for token %2", m_clientId, response.token());
          return;
      }
      if (response.qos() != pendingIt->second.qos)
      {
          // ("ClientPaho", "onSubscribeSuccessOnInstance %1 - subscription requested qos %2, endpoint assigned qos %3", m_clientId, pendingIt->second.qos, response.qos());
      }
      // ("ClientPaho", "onSubscribeSuccessOnInstance %1 - move pending subscription on topic %2 to the registered subscriptions", m_clientId, topic);
      m_subscriptions.emplace(std::make_pair(pendingIt->first, std::move(pendingIt->second)));
      m_pendingSubscriptions.erase(pendingIt);
      operationOk = true;
  }
  
  void ClientPaho::onSubscribeFailureOnInstance(const MqttFailure& response)
  {
      // ("ClientPaho", "onSubscribeFailureOnInstance %1 - subscription failed with code %2 (%3)", m_clientId, response.codeToString(), response.message());
      OSDEV_COMPONENTS_SCOPEGUARD(m_operationsCompleteCV, [this]() { m_operationsCompleteCV.notify_all(); });
      OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
      OSDEV_COMPONENTS_SCOPEGUARD(m_pendingOperations, [this, &response]()
      {
          // MLOGIC_COMMON_DEBUG("ClientPaho", "onSubscribeFailureOnInstance %1 - pending operations : %2, removing operation %3", m_clientId, m_pendingOperations, response.token());
          m_operationResult[response.token()] = false;
          m_pendingOperations.erase(response.token());
      });
  
      auto it = m_subscribeTokenToTopic.find(response.token());
      if (m_subscribeTokenToTopic.end() == it)
      {
          // ("ClientPaho", "onSubscribeFailureOnInstance %1 - unknown token %2", m_clientId, response.token());
          return;
      }
      auto topic = it->second;
      m_subscribeTokenToTopic.erase(it);
  
      auto pendingIt = m_pendingSubscriptions.find(topic);
      if (m_pendingSubscriptions.end() == pendingIt)
      {
          // ("ClientPaho", "onSubscribeFailureOnInstance %1 - cannot find pending subscription for token %2", m_clientId, response.token());
          return;
      }
      // ("ClientPaho", "onSubscribeFailureOnInstance %1 - remove pending subscription on topic %2", m_clientId, topic);
      m_pendingSubscriptions.erase(pendingIt);
  }
  
  void ClientPaho::onUnsubscribeSuccessOnInstance(const MqttSuccess& response)
  {
      // ("ClientPaho", "onUnsubscribeSuccessOnInstance %1 - unsubscribe with token %2 succeeded", m_clientId, response.token());
  
      OSDEV_COMPONENTS_SCOPEGUARD(m_operationsCompleteCV, [this]() { m_operationsCompleteCV.notify_all(); });
      OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
  
      // On centos7 the unsubscribe response is a nullptr, so we do not have a valid token.
      // As a workaround the last unsubscribe token is stored and is used when no valid token is available.
      // This is by no means bullet proof because rapid unsubscribes in succession will overwrite this member
      // before the callback on the earlier unsubscribe has arrived. On centos7 the unsubscribes have to be handled
      // sequentially (see ClientPaho::unsubscribe)!
      auto token = response.token();
      if (-1 == token)
      {
          token = m_lastUnsubscribe;
          m_lastUnsubscribe = -1;
      }
  
      bool operationOk = false;
      OSDEV_COMPONENTS_SCOPEGUARD(m_pendingOperations, [this, token, &operationOk]()
      {
          // ("ClientPaho", "onUnsubscribeSuccessOnInstance %1 - pending operations : %2, removing operation %3", m_clientId, m_pendingOperations, token);
          m_operationResult[token] = operationOk;
          m_pendingOperations.erase(token);
      });
  
      auto it = m_unsubscribeTokenToTopic.find(token);
      if (m_unsubscribeTokenToTopic.end() == it)
      {
          // ("ClientPaho", "onUnsubscribeSuccessOnInstance %1 - unknown token %2", m_clientId, token);
          return;
      }
      auto topic = it->second;
      m_unsubscribeTokenToTopic.erase(it);
  
      auto registeredIt = m_subscriptions.find(topic);
      if (m_subscriptions.end() == registeredIt) {
          // ("ClientPaho", "onUnsubscribeSuccessOnInstance %1 - cannot find subscription for token %2", m_clientId, response.token());
          return;
      }
      // ("ClientPaho", "onUnsubscribeSuccessOnInstance %1 - remove subscription on topic %2 from the registered subscriptions", m_clientId, topic);
      m_subscriptions.erase(registeredIt);
      operationOk = true;
  }
  
  void ClientPaho::onUnsubscribeFailureOnInstance(const MqttFailure& response)
  {
      // ("ClientPaho", "onUnsubscribeFailureOnInstance %1 - subscription failed with code %2 (%3)", m_clientId, response.codeToString(), response.message());
      OSDEV_COMPONENTS_SCOPEGUARD(m_operationsCompleteCV, [this]() { m_operationsCompleteCV.notify_all(); });
      OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
      OSDEV_COMPONENTS_SCOPEGUARD(m_pendingOperations, [this, &response]()
      {
          // ("ClientPaho", "onUnsubscribeFailureOnInstance %1 - pending operations : %2, removing operation %3", m_clientId, m_pendingOperations, response.token());
          m_operationResult[response.token()] = false;
          m_pendingOperations.erase(response.token());
      });
  
      auto it = m_unsubscribeTokenToTopic.find(response.token());
      if (m_unsubscribeTokenToTopic.end() == it)
      {
          // ("ClientPaho", "onUnsubscribeFailureOnInstance %1 - unknown token %2", m_clientId, response.token());
          return;
      }
      auto topic = it->second;
      m_unsubscribeTokenToTopic.erase(it);
  }
  
  int ClientPaho::onMessageArrivedOnInstance(const MqttMessage& message)
  {
      // ("ClientPaho", "onMessageArrivedOnInstance %1 - received message on topic %2, retained : %3, dup : %4", m_clientId, message.topic(), message.retained(), message.duplicate());
  
      std::function<void(MqttMessage)> cb;
  
      {
          OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
          for (const auto& s : m_subscriptions)
          {
              if (boost::regex_match(message.topic(), s.second.topicRegex))
              {
                  cb = s.second.callback;
              }
          }
      }
  
      if (cb)
      {
          cb(message);
      }
      else
      {
          // ("ClientPaho", "onMessageArrivedOnInstance %1 - no topic filter found for message received on topic %2", m_clientId, message.topic());
      }
      return 1;
  }
  
  void ClientPaho::onDeliveryCompleteOnInstance(MQTTAsync_token token)
  {
      // ("ClientPaho", "onDeliveryCompleteOnInstance %1 - message with token %2 is delivered", m_clientId, token);
      if (m_deliveryCompleteCallback)
      {
          m_deliveryCompleteCallback(m_clientId, static_cast<std::int32_t>(token));
      }
  }
  
  void ClientPaho::onConnectionLostOnInstance(const std::string& cause)
  {
      (void)cause;
      // ("ClientPaho", "onConnectionLostOnInstance %1 - connection lost (%2)", m_clientId, cause);
      setConnectionStatus(ConnectionStatus::ReconnectInProgress);
  
      OSDEV_COMPONENTS_LOCKGUARD(m_mutex);
      // Remove all tokens related to subscriptions from the active operations.
      for (const auto& p : m_subscribeTokenToTopic)
      {
          // ("ClientPaho", "onConnectionLostOnInstance %1 - pending operations : %2, removing operation %3", m_clientId, m_pendingOperations, p.first);
          m_pendingOperations.erase(p.first);
      }
  
      for (const auto& p : m_unsubscribeTokenToTopic)
      {
          // ("ClientPaho", "onConnectionLostOnInstance %1 - pending operations : %2, removing operation %3", m_clientId, m_pendingOperations, p.first);
          m_pendingOperations.erase(p.first);
      }
      // Clear the administration used in the subscribe process.
      m_subscribeTokenToTopic.clear();
      m_unsubscribeTokenToTopic.clear();
  }
  
  // static
9421324b   Peter M. Groen   First fix on conn...
1114
1115
1116
1117
1118
1119
1120
  void ClientPaho::onFirstConnect(void* context, char* cause)
  {
      LogInfo( "[ClientPaho::onFirstConnect]", "onFirstConnect triggered.." );
      if(context)
      {
          auto *cl = reinterpret_cast<ClientPaho*>(context);
          std::string reason(nullptr == cause ? "Unknown cause" : cause);
2c0c99a5   Peter M. Groen   Fix connect Callb...
1121
          cl->pushIncomingEvent([cl, reason]() { cl->onConnectSuccessOnInstance(); });
9421324b   Peter M. Groen   First fix on conn...
1122
1123
1124
      }
  }
  
51becbde   Peter M. Groen   Committed the ent...
1125
1126
  void ClientPaho::onConnect(void* context, char* cause)
  {
9421324b   Peter M. Groen   First fix on conn...
1127
      LogInfo( "[ClientPaho::onConnect]", "onConnect triggered.." );
51becbde   Peter M. Groen   Committed the ent...
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          std::string reason(nullptr == cause ? "unknown cause" : cause);
          cl->pushIncomingEvent([cl, reason]() { cl->onConnectOnInstance(reason); });
      }
  }
  
  // static
  void ClientPaho::onConnectSuccess(void* context, MQTTAsync_successData* response)
  {
2c0c99a5   Peter M. Groen   Fix connect Callb...
1139
      LogInfo( "[ClientPaho::onConnectSuccess]", "onConnectSuccess triggered.." );
51becbde   Peter M. Groen   Committed the ent...
1140
1141
1142
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
76d01373   Peter M. Groen   Fix on connection
1143
1144
          if (!response)
          {
51becbde   Peter M. Groen   Committed the ent...
1145
              // connect should always have a valid response struct.
76d01373   Peter M. Groen   Fix on connection
1146
              LogError( "[ClientPaho]", "onConnectSuccess - no response data");
2c0c99a5   Peter M. Groen   Fix connect Callb...
1147
              return;
51becbde   Peter M. Groen   Committed the ent...
1148
          }
2c0c99a5   Peter M. Groen   Fix connect Callb...
1149
1150
          // MqttSuccess resp(response->token, ConnectionData(response->alt.connect.serverURI, response->alt.connect.MQTTVersion, response->alt.connect.sessionPresent));
          cl->pushIncomingEvent([cl]() { cl->onConnectSuccessOnInstance(); });
51becbde   Peter M. Groen   Committed the ent...
1151
1152
1153
1154
1155
1156
      }
  }
  
  // static
  void ClientPaho::onConnectFailure(void* context, MQTTAsync_failureData* response)
  {
2c0c99a5   Peter M. Groen   Fix connect Callb...
1157
      LogDebug("[ClientPaho::onConnectFailure]", std::string( "Connection Failure?" ));
51becbde   Peter M. Groen   Committed the ent...
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          MqttFailure resp(response);
          cl->pushIncomingEvent([cl, resp]() { cl->onConnectFailureOnInstance(resp); });
      }
  }
  
  //// static
  //void ClientPaho::onDisconnect(void* context, MQTTProperties* properties, enum MQTTReasonCodes reasonCode)
  //{
  //    apply_unused_parameters(properties);
  //    try {
  //        if (context) {
  //            auto* cl = reinterpret_cast<ClientPaho*>(context);
  //            cl->pushIncomingEvent([cl, reasonCode]() { cl->onDisconnectOnInstance(reasonCode); });
  //        }
  //    }
  //    catch (...) {
  //    }
  //    catch (const std::exception& e) {
  //        MLOGIC_COMMON_ERROR("ClientPaho", "onDisconnect - exception : %1", e.what());
  //    }
  //    catch (...) {
  //        MLOGIC_COMMON_ERROR("ClientPaho", "onDisconnect - unknown exception");
  //    }
  //}
  
  // static
  void ClientPaho::onDisconnectSuccess(void* context, MQTTAsync_successData* response)
  {
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          MqttSuccess resp(response ? response->token : 0);
          cl->pushIncomingEvent([cl, resp]() { cl->onDisconnectSuccessOnInstance(resp); });
      }
  }
  
  // static
  void ClientPaho::onDisconnectFailure(void* context, MQTTAsync_failureData* response)
  {
9421324b   Peter M. Groen   First fix on conn...
1200
      LogInfo( "[ClientPaho::onDisconnectFailure]", "onDisconnectFailure triggered.." );
51becbde   Peter M. Groen   Committed the ent...
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          MqttFailure resp(response);
          cl->pushIncomingEvent([cl, resp]() { cl->onDisconnectFailureOnInstance(resp); });
      }
  }
  
  // static
  void ClientPaho::onPublishSuccess(void* context, MQTTAsync_successData* response)
  {
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          if (!response)
          {
              // publish should always have a valid response struct.
              // toLogFile ("ClientPaho", "onPublishSuccess - no response data");
          }
          MqttSuccess resp(response->token, MqttMessage(response->alt.pub.destinationName == nullptr ? "null" : response->alt.pub.destinationName, response->alt.pub.message));
          cl->pushIncomingEvent([cl, resp]() { cl->onPublishSuccessOnInstance(resp); });
      }
  }
  
  // static
  void ClientPaho::onPublishFailure(void* context, MQTTAsync_failureData* response)
  {
      (void)response;
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          MqttFailure resp(response);
          cl->pushIncomingEvent([cl, resp]() { cl->onPublishFailureOnInstance(resp); });
      }
  }
  
  // static
  void ClientPaho::onSubscribeSuccess(void* context, MQTTAsync_successData* response)
  {
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          if (!response)
          {
              // subscribe should always have a valid response struct.
              // MLOGIC_COMMON_FATAL("ClientPaho", "onSubscribeSuccess - no response data");
          }
          MqttSuccess resp(response->token, response->alt.qos);
          cl->pushIncomingEvent([cl, resp]() { cl->onSubscribeSuccessOnInstance(resp); });
      }
  }
  
  // static
  void ClientPaho::onSubscribeFailure(void* context, MQTTAsync_failureData* response)
  {
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          MqttFailure resp(response);
          cl->pushIncomingEvent([cl, resp]() { cl->onSubscribeFailureOnInstance(resp); });
      }
  }
  
  // static
  void ClientPaho::onUnsubscribeSuccess(void* context, MQTTAsync_successData* response)
  {
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          MqttSuccess resp(response ? response->token : -1);
          cl->pushIncomingEvent([cl, resp]() { cl->onUnsubscribeSuccessOnInstance(resp); });
      }
  }
  
  // static
  void ClientPaho::onUnsubscribeFailure(void* context, MQTTAsync_failureData* response)
  {
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          MqttFailure resp(response);
          cl->pushIncomingEvent([cl, resp]() { cl->onUnsubscribeFailureOnInstance(resp); });
      }
  }
  
  // static
  int ClientPaho::onMessageArrived(void* context, char* topicName, int, MQTTAsync_message* message)
  {
  
      OSDEV_COMPONENTS_SCOPEGUARD(freeMessage, [&topicName, &message]()
      {
          MQTTAsync_freeMessage(&message);
          MQTTAsync_free(topicName);
      });
  
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          MqttMessage msg(topicName, *message);
          cl->pushIncomingEvent([cl, msg]() { cl->onMessageArrivedOnInstance(msg); });
      }
  
      return 1; // always return true. Otherwise this callback is triggered again.
  }
  
  // static
  void ClientPaho::onDeliveryComplete(void* context, MQTTAsync_token token)
  {
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          cl->pushIncomingEvent([cl, token]() { cl->onDeliveryCompleteOnInstance(token); });
      }
  }
  
  // static
  void ClientPaho::onConnectionLost(void* context, char* cause)
  {
      OSDEV_COMPONENTS_SCOPEGUARD(freeCause, [&cause]()
      {
          if (cause)
          {
              MQTTAsync_free(cause);
          }
      });
  
      if (context)
      {
          auto* cl = reinterpret_cast<ClientPaho*>(context);
          std::string msg(nullptr == cause ? "cause unknown" : cause);
          cl->pushIncomingEvent([cl, msg]() { cl->onConnectionLostOnInstance(msg); });
      }
  }
  
  // static
  void ClientPaho::onLogPaho(enum MQTTASYNC_TRACE_LEVELS level, char* message)
  {
      (void)message;
      switch (level)
      {
          case MQTTASYNC_TRACE_MAXIMUM:
          case MQTTASYNC_TRACE_MEDIUM:
          case MQTTASYNC_TRACE_MINIMUM: {
              // ("ClientPaho", "paho - %1", message)
              break;
          }
          case MQTTASYNC_TRACE_PROTOCOL: {
              // ("ClientPaho", "paho - %1", message)
              break;
          }
          case MQTTASYNC_TRACE_ERROR:
          case MQTTASYNC_TRACE_SEVERE:
          case MQTTASYNC_TRACE_FATAL: {
              // ("ClientPaho", "paho - %1", message)
              break;
          }
      }
  }