token.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /////////////////////////////////////////////////////////////////////////////
  2. /// @file token.h
  3. /// Declaration of MQTT token class
  4. /// @date May 1, 2013
  5. /// @author Frank Pagliughi
  6. /////////////////////////////////////////////////////////////////////////////
  7. /*******************************************************************************
  8. * Copyright (c) 2013-2019 Frank Pagliughi <fpagliughi@mindspring.com>
  9. *
  10. * All rights reserved. This program and the accompanying materials
  11. * are made available under the terms of the Eclipse Public License v2.0
  12. * and Eclipse Distribution License v1.0 which accompany this distribution.
  13. *
  14. * The Eclipse Public License is available at
  15. * http://www.eclipse.org/legal/epl-v20.html
  16. * and the Eclipse Distribution License is available at
  17. * http://www.eclipse.org/org/documents/edl-v10.php.
  18. *
  19. * Contributors:
  20. * Frank Pagliughi - initial implementation and documentation
  21. * Frank Pagliughi - MQTT v5 support & server responses
  22. *******************************************************************************/
  23. #ifndef __mqtt_token_h
  24. #define __mqtt_token_h
  25. #include <chrono>
  26. #include <condition_variable>
  27. #include <mutex>
  28. #include <thread>
  29. #include <vector>
  30. #include "MQTTAsync.h"
  31. #include "mqtt/buffer_ref.h"
  32. #include "mqtt/exception.h"
  33. #include "mqtt/iaction_listener.h"
  34. #include "mqtt/properties.h"
  35. #include "mqtt/server_response.h"
  36. #include "mqtt/string_collection.h"
  37. #include "mqtt/types.h"
  38. namespace mqtt {
  39. class iasync_client;
  40. /////////////////////////////////////////////////////////////////////////////
  41. /**
  42. * Provides a mechanism for tracking the completion of an asynchronous
  43. * action.
  44. */
  45. class token
  46. {
  47. public:
  48. /** Smart/shared pointer to an object of this class */
  49. using ptr_t = std::shared_ptr<token>;
  50. /** Smart/shared pointer to an object of this class */
  51. using const_ptr_t = std::shared_ptr<const token>;
  52. /** Weak pointer to an object of this class */
  53. using weak_ptr_t = std::weak_ptr<token>;
  54. /** The type of request that the token is tracking */
  55. enum Type { CONNECT, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, DISCONNECT };
  56. private:
  57. /** Lock guard type for this class. */
  58. using guard = std::lock_guard<std::mutex>;
  59. /** Unique type for this class. */
  60. using unique_lock = std::unique_lock<std::mutex>;
  61. /** Object monitor mutex. */
  62. mutable std::mutex lock_;
  63. /** Condition variable signals when the action completes */
  64. mutable std::condition_variable cond_;
  65. /** The type of request that the token is tracking */
  66. Type type_;
  67. /** The MQTT client that is processing this action */
  68. iasync_client* cli_;
  69. /** The action success/failure code */
  70. int rc_{0};
  71. /** MQTT v5 reason code */
  72. ReasonCode reasonCode_{ReasonCode::SUCCESS};
  73. /** Error message from the C lib (if any) */
  74. string errMsg_;
  75. /** The underlying C token. Note that this is just an integer */
  76. MQTTAsync_token msgId_;
  77. /** The topic string(s) for the action being tracked by this token */
  78. const_string_collection_ptr topics_;
  79. /** User supplied context */
  80. void* userContext_;
  81. /**
  82. * User supplied listener.
  83. * Note that the user listener fires after the action is marked
  84. * complete, but before the token is signaled.
  85. */
  86. iaction_listener* listener_;
  87. /** The number of expected responses */
  88. size_t nExpected_;
  89. /** Whether the action has yet to complete */
  90. bool complete_;
  91. /** Connection response (null if not available) */
  92. std::unique_ptr<connect_response> connRsp_;
  93. /** Subscribe response (null if not available) */
  94. std::unique_ptr<subscribe_response> subRsp_;
  95. /** Unsubscribe response (null if not available) */
  96. std::unique_ptr<unsubscribe_response> unsubRsp_;
  97. /** Client and token-related options have special access */
  98. friend class async_client;
  99. friend class mock_async_client;
  100. friend class connect_options;
  101. friend class response_options;
  102. friend class delivery_response_options;
  103. friend class disconnect_options;
  104. /**
  105. * Resets the token back to a non-signaled state.
  106. */
  107. void reset();
  108. /**
  109. * Sets the ID for the message.
  110. * This is a guaranteed atomic operation.
  111. * @param msgId The ID of the message.
  112. */
  113. void set_message_id(MQTTAsync_token msgId) {
  114. guard g(lock_);
  115. msgId_ = msgId;
  116. }
  117. /**
  118. * C-style callback for success.
  119. * This simply passes the call on to the proper token object for
  120. * processing.
  121. * @param tokObj The token object to process the call. Note that this is
  122. * @em not the user-supplied context pointer. That is
  123. * kept in the object itself.
  124. * @param rsp The success response.
  125. */
  126. static void on_success(void* tokObj, MQTTAsync_successData* rsp);
  127. static void on_success5(void* tokObj, MQTTAsync_successData5* rsp);
  128. /**
  129. * C-style callback for failure.
  130. * This simply passes the call on to the proper token object for
  131. * processing.
  132. * @param tokObj The token object to process the call. Note that this is
  133. * @em not the user-supplied context pointer. That is
  134. * kept in the object itself.
  135. * @param rsp The failure response.
  136. */
  137. static void on_failure(void* tokObj, MQTTAsync_failureData* rsp);
  138. static void on_failure5(void* tokObj, MQTTAsync_failureData5* rsp);
  139. /**
  140. * C-style callback for client (re)connection.
  141. * This is normally only used to process a reconnect completion message.
  142. * The initial connect() is processed via on_success/failure.
  143. * @param tokObj Pointer to the token object used to process the call.
  144. */
  145. static void on_connected(void* tokObj, char* /*cause*/);
  146. /**
  147. * Internal handler for the success callback.
  148. * @param rsp The success response.
  149. */
  150. void on_success(MQTTAsync_successData* rsp);
  151. void on_success5(MQTTAsync_successData5* rsp);
  152. /**
  153. * Internal handler for the failure callback.
  154. * @param rsp The failure response.
  155. */
  156. void on_failure(MQTTAsync_failureData* rsp);
  157. void on_failure5(MQTTAsync_failureData5* rsp);
  158. /**
  159. * Check the current return code and throw an exception if it is not a
  160. * success code.
  161. */
  162. void check_ret() const {
  163. if (rc_ != MQTTASYNC_SUCCESS || reasonCode_ >= 0x80)
  164. throw exception(rc_, reasonCode_, errMsg_);
  165. }
  166. public:
  167. /**
  168. * Constructs a token object.
  169. * @param typ The type of request that the token is tracking.
  170. * @param cli The client that created the token.
  171. */
  172. token(Type typ, iasync_client& cli) : token{typ, cli, MQTTAsync_token(0)} {}
  173. /**
  174. * Constructs a token object.
  175. * @param typ The type of request that the token is tracking.
  176. * @param cli The client that created the token.
  177. * @param userContext optional object used to pass context to the
  178. * callback. Use @em nullptr if not required.
  179. * @param cb callback listener that will be notified when subscribe has
  180. * completed
  181. */
  182. token(Type typ, iasync_client& cli, void* userContext, iaction_listener& cb)
  183. : token{typ, cli, const_string_collection_ptr(), userContext, cb} {}
  184. /**
  185. * Constructs a token object.
  186. * @param typ The type of request that the token is tracking.
  187. * @param cli The client that created the token.
  188. * @param topic The topic associated with the token
  189. */
  190. token(Type typ, iasync_client& cli, const string& topic)
  191. : token{typ, cli, string_collection::create(topic)} {}
  192. /**
  193. * Constructs a token object.
  194. * @param typ The type of request that the token is tracking.
  195. * @param cli The client that created the token.
  196. * @param topic The topic associated with the token
  197. * @param userContext optional object used to pass context to the
  198. * callback. Use @em nullptr if not required.
  199. * @param cb callback listener that will be notified when subscribe has
  200. * completed
  201. */
  202. token(
  203. Type typ, iasync_client& cli, const string& topic, void* userContext,
  204. iaction_listener& cb
  205. )
  206. : token{typ, cli, string_collection::create(topic), userContext, cb} {}
  207. /**
  208. * Constructs a token object.
  209. * @param typ The type of request that the token is tracking.
  210. * @param cli The client that created the token.
  211. * @param topics The topics associated with the token
  212. */
  213. token(Type typ, iasync_client& cli, const_string_collection_ptr topics);
  214. /**
  215. * Constructs a token object.
  216. * @param typ The type of request that the token is tracking.
  217. * @param cli The client that created the token.
  218. * @param topics The topics associated with the token
  219. * @param userContext optional object used to pass context to the
  220. * callback. Use @em nullptr if not required.
  221. * @param cb callback listener that will be notified when subscribe has
  222. * completed
  223. */
  224. token(
  225. Type typ, iasync_client& cli, const_string_collection_ptr topics, void* userContext,
  226. iaction_listener& cb
  227. );
  228. /**
  229. * Constructs a token object.
  230. * @param typ The type of request that the token is tracking.
  231. * @param cli The client that created the token.
  232. * @param tok The message ID
  233. */
  234. token(Type typ, iasync_client& cli, MQTTAsync_token tok);
  235. /**
  236. * Virtual destructor.
  237. */
  238. virtual ~token() {}
  239. /**
  240. * Constructs a token object.
  241. * @param typ The type of request that the token is tracking.
  242. * @param cli The client that created the token.
  243. * @return A smart/shared pointer to a token.
  244. */
  245. static ptr_t create(Type typ, iasync_client& cli) {
  246. return std::make_shared<token>(typ, cli);
  247. }
  248. /**
  249. * Constructs a token object.
  250. * @param typ The type of request that the token is tracking.
  251. * @param cli The client that created the token.
  252. * @param userContext optional object used to pass context to the
  253. * callback. Use @em nullptr if not required.
  254. * @param cb callback listener that will be notified when subscribe has
  255. * completed
  256. */
  257. static ptr_t create(
  258. Type typ, iasync_client& cli, void* userContext, iaction_listener& cb
  259. ) {
  260. return std::make_shared<token>(typ, cli, userContext, cb);
  261. }
  262. /**
  263. * Constructs a token object.
  264. * @param typ The type of request that the token is tracking.
  265. * @param cli The client that created the token.
  266. * @param topic The topic associated with the token
  267. */
  268. static ptr_t create(Type typ, iasync_client& cli, const string& topic) {
  269. return std::make_shared<token>(typ, cli, topic);
  270. }
  271. /**
  272. * Constructs a token object.
  273. * @param typ The type of request that the token is tracking.
  274. * @param cli The client that created the token.
  275. * @param topic The topic associated with the token
  276. * @param userContext optional object used to pass context to the
  277. * callback. Use @em nullptr if not required.
  278. * @param cb callback listener that will be notified when subscribe has
  279. * completed
  280. */
  281. static ptr_t create(
  282. Type typ, iasync_client& cli, const string& topic, void* userContext,
  283. iaction_listener& cb
  284. ) {
  285. return std::make_shared<token>(typ, cli, topic, userContext, cb);
  286. }
  287. /**
  288. * Constructs a token object.
  289. * @param typ The type of request that the token is tracking.
  290. * @param cli The client that created the token.
  291. * @param topics The topics associated with the token
  292. */
  293. static ptr_t create(Type typ, iasync_client& cli, const_string_collection_ptr topics) {
  294. return std::make_shared<token>(typ, cli, topics);
  295. }
  296. /**
  297. * Constructs a token object.
  298. * @param typ The type of request that the token is tracking.
  299. * @param cli The client that created the token.
  300. * @param topics The topics associated with the token
  301. *
  302. * @param userContext optional object used to pass context to the
  303. * callback. Use @em nullptr if not required.
  304. * @param cb callback listener that will be notified when subscribe has
  305. */
  306. static ptr_t create(
  307. Type typ, iasync_client& cli, const_string_collection_ptr topics, void* userContext,
  308. iaction_listener& cb
  309. ) {
  310. return std::make_shared<token>(typ, cli, topics, userContext, cb);
  311. }
  312. /**
  313. * Gets the type of request the token is tracking, like CONNECT,
  314. * PUBLISH, etc.
  315. * @return The type of request that the token is tracking.
  316. */
  317. Type get_type() const { return type_; }
  318. /**
  319. * Gets the action listener for this token.
  320. * @return The action listener for this token.
  321. */
  322. virtual iaction_listener* get_action_callback() const {
  323. guard g(lock_);
  324. return listener_;
  325. }
  326. /**
  327. * Returns the MQTT client that is responsible for processing the
  328. * asynchronous action.
  329. * @return The client to which this token is connected.
  330. */
  331. virtual iasync_client* get_client() const { return cli_; }
  332. /**
  333. * Returns the ID of the message that is associated with the token.
  334. * @return The message ID of the transaction being tracked.
  335. */
  336. virtual int get_message_id() const {
  337. static_assert(sizeof(msgId_) <= sizeof(int), "MQTTAsync_token must fit into int");
  338. return int(msgId_);
  339. }
  340. /**
  341. * Gets the topic string(s) for the action being tracked by this
  342. * token.
  343. * @return A const pointer to the collection of topics being tracked by
  344. * the token.
  345. */
  346. virtual const_string_collection_ptr get_topics() const { return topics_; }
  347. /**
  348. * Retrieve the context associated with an action.
  349. * @return The context associated with an action.
  350. */
  351. virtual void* get_user_context() const {
  352. guard g(lock_);
  353. return userContext_;
  354. }
  355. /**
  356. * Returns whether or not the action has finished.
  357. * @return @em true if the transaction has completed, @em false if not.
  358. */
  359. virtual bool is_complete() const { return complete_; }
  360. /**
  361. * Determines if the reference is valid.
  362. * If the reference is invalid then it is not safe to call @em any
  363. * member functions other than @ref is_null() and @ref empty()
  364. * @return @em true if referring to a valid buffer, @em false if the
  365. * reference (pointer) is null.
  366. */
  367. explicit operator bool() const {
  368. guard g(lock_);
  369. return rc_ == MQTTASYNC_SUCCESS && reasonCode_ < 0x80;
  370. }
  371. /**
  372. * Gets the return code from the action.
  373. * This is only valid after the action has completed (i.e. if @ref
  374. * is_complete() returns @em true).
  375. * @return The return code from the action.
  376. */
  377. virtual int get_return_code() const { return rc_; }
  378. /**
  379. * Register a listener to be notified when an action completes.
  380. * @param listener The callback to be notified when actions complete.
  381. */
  382. virtual void set_action_callback(iaction_listener& listener);
  383. /**
  384. * Store some context associated with an action.
  385. * @param userContext optional object used to pass context to the
  386. * callback. Use @em nullptr if not required.
  387. */
  388. virtual void set_user_context(void* userContext) {
  389. guard g(lock_);
  390. userContext_ = userContext;
  391. }
  392. /**
  393. * Sets the number of results expected.
  394. * This is only required for subscribe many() with < MQTTv5
  395. * @param n The number of results expected.
  396. */
  397. void set_num_expected(size_t n) { nExpected_ = n; }
  398. /**
  399. * Gets the reason code for the operation.
  400. * @return The reason code for the operation.
  401. */
  402. ReasonCode get_reason_code() const { return reasonCode_; }
  403. /**
  404. * Get the error message from the C library
  405. * @return Error message for the operation
  406. */
  407. string get_error_message() const { return errMsg_; }
  408. /**
  409. * Blocks the current thread until the action this token is associated
  410. * with has completed.
  411. */
  412. virtual void wait();
  413. /**
  414. * Non-blocking check to see if the action has completed.
  415. * @return @em true if the wait finished successfully, @em false if the
  416. * action has not completed yet.
  417. */
  418. virtual bool try_wait() {
  419. guard g(lock_);
  420. if (complete_)
  421. check_ret();
  422. return complete_;
  423. }
  424. /**
  425. * Blocks the current thread until the action this token is associated
  426. * with has completed.
  427. * @param timeout The timeout (in milliseconds)
  428. * @return @em true if the wait finished successfully, @em false if a
  429. * timeout occurred.
  430. */
  431. virtual bool wait_for(long timeout) {
  432. return wait_for(std::chrono::milliseconds(timeout));
  433. }
  434. /**
  435. * Waits a relative amount of time for the action to complete.
  436. * @param relTime The amount of time to wait for the event.
  437. * @return @em true if the event gets signaled in the specified time,
  438. * @em false on a timeout.
  439. */
  440. template <class Rep, class Period>
  441. bool wait_for(const std::chrono::duration<Rep, Period>& relTime) {
  442. unique_lock g(lock_);
  443. if (!cond_.wait_for(g, std::chrono::milliseconds(relTime), [this] {
  444. return complete_;
  445. }))
  446. return false;
  447. check_ret();
  448. return true;
  449. }
  450. /**
  451. * Waits until an absolute time for the action to complete.
  452. * @param absTime The absolute time to wait for the event.
  453. * @return @em true if the event gets signaled in the specified time,
  454. * @em false on a timeout.
  455. */
  456. template <class Clock, class Duration>
  457. bool wait_until(const std::chrono::time_point<Clock, Duration>& absTime) {
  458. unique_lock g(lock_);
  459. if (!cond_.wait_until(g, absTime, [this] { return complete_; }))
  460. return false;
  461. check_ret();
  462. return true;
  463. }
  464. /**
  465. * Gets the response from a connect operation.
  466. * This returns the result of the completed operation. If the
  467. * operation is not yet complete this will block until the result
  468. * is available.
  469. * @return The result of the operation.
  470. */
  471. connect_response get_connect_response() const;
  472. /**
  473. * Gets the response from a connect operation.
  474. * This returns the result of the completed operation. If the
  475. * operation is not yet complete this will block until the result
  476. * is available.
  477. * @return The result of the operation.
  478. */
  479. subscribe_response get_subscribe_response() const;
  480. /**
  481. * Gets the response from a connect operation.
  482. * This returns the result of the completed operation. If the
  483. * operation is not yet complete this will block until the result
  484. * is available.
  485. * @return The result of the operation.
  486. */
  487. unsubscribe_response get_unsubscribe_response() const;
  488. };
  489. /** Smart/shared pointer to a token object */
  490. using token_ptr = token::ptr_t;
  491. /** Smart/shared pointer to a const token object */
  492. using const_token_ptr = token::const_ptr_t;
  493. /////////////////////////////////////////////////////////////////////////////
  494. } // namespace mqtt
  495. #endif // __mqtt_token_h