token.h 17 KB

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