token.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 v1.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-v10.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 propeties */
  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 token_test;
  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 cli The client that created the token.
  178. */
  179. token(Type typ, iasync_client& cli)
  180. : token(typ, cli, MQTTAsync_token(0)) {}
  181. /**
  182. * Constructs a token object.
  183. * @param cli The client that created the token.
  184. * @param userContext optional object used to pass context to the
  185. * callback. Use @em nullptr if not required.
  186. * @param cb callback listener that will be notified when subscribe has
  187. * completed
  188. */
  189. token(Type typ, iasync_client& cli, void* userContext, iaction_listener& cb)
  190. : token(typ, cli, const_string_collection_ptr(), userContext, cb) {}
  191. /**
  192. * Constructs a token object.
  193. * @param cli The client that created the token.
  194. * @param topic The topic assiciated with the token
  195. */
  196. token(Type typ, iasync_client& cli, const string& topic)
  197. : token(typ, cli, string_collection::create(topic)) {}
  198. /**
  199. * Constructs a token object.
  200. * @param cli The client that created the token.
  201. * @param topic The topic assiciated with the token
  202. * @param userContext optional object used to pass context to the
  203. * callback. Use @em nullptr if not required.
  204. * @param cb callback listener that will be notified when subscribe has
  205. * completed
  206. */
  207. token(Type typ, iasync_client& cli, const string& topic,
  208. void* userContext, iaction_listener& cb)
  209. : token(typ, cli, string_collection::create(topic), userContext, cb) {}
  210. /**
  211. * Constructs a token object.
  212. * @param cli The client that created the token.
  213. * @param topics The topics associated with the token
  214. */
  215. token(Type typ, iasync_client& cli, const_string_collection_ptr topics);
  216. /**
  217. * Constructs a token object.
  218. * @param cli The client that created the token.
  219. * @param topics The topics associated with the token
  220. * @param userContext optional object used to pass context to the
  221. * callback. Use @em nullptr if not required.
  222. * @param cb callback listener that will be notified when subscribe has
  223. * completed
  224. */
  225. token(Type typ, iasync_client& cli, const_string_collection_ptr topics,
  226. void* userContext, iaction_listener& cb);
  227. /**
  228. * Constructs a token object.
  229. * @param cli The client that created the token.
  230. * @param tok The message ID
  231. */
  232. token(Type typ, iasync_client& cli, MQTTAsync_token tok);
  233. /**
  234. * Virtual destructor.
  235. */
  236. virtual ~token() {}
  237. /**
  238. * Constructs a token object.
  239. * @param cli The client that created the token.
  240. * @return A smart/shared pointer to a token.
  241. */
  242. static ptr_t create(Type typ, iasync_client& cli) {
  243. return std::make_shared<token>(typ, cli);
  244. }
  245. /**
  246. * Constructs a token object.
  247. * @param cli The client that created the token.
  248. * @param userContext optional object used to pass context to the
  249. * callback. Use @em nullptr if not required.
  250. * @param cb callback listener that will be notified when subscribe has
  251. * completed
  252. */
  253. static ptr_t create(Type typ, iasync_client& cli, void* userContext,
  254. iaction_listener& cb) {
  255. return std::make_shared<token>(typ, cli, userContext, cb);
  256. }
  257. /**
  258. * Constructs a token object.
  259. * @param cli The client that created the token.
  260. * @param topic The topic assiciated with the token
  261. */
  262. static ptr_t create(Type typ, iasync_client& cli, const string& topic) {
  263. return std::make_shared<token>(typ, cli, topic);
  264. }
  265. /**
  266. * Constructs a token object.
  267. * @param cli The client that created the token.
  268. * @param topic The topic assiciated with the token
  269. * @param userContext optional object used to pass context to the
  270. * callback. Use @em nullptr if not required.
  271. * @param cb callback listener that will be notified when subscribe has
  272. * completed
  273. */
  274. static ptr_t create(Type typ, iasync_client& cli, const string& topic,
  275. void* userContext, iaction_listener& cb) {
  276. return std::make_shared<token>(typ, cli, topic, userContext, cb);
  277. }
  278. /**
  279. * Constructs a token object.
  280. * @param cli The client that created the token.
  281. * @param topics The topics associated with the token
  282. */
  283. static ptr_t create(Type typ, iasync_client& cli, const_string_collection_ptr topics) {
  284. return std::make_shared<token>(typ, cli, topics);
  285. }
  286. /**
  287. * Constructs a token object.
  288. * @param cli The client that created the token.
  289. * @param topics The topics associated with the token
  290. *
  291. * @param userContext optional object used to pass context to the
  292. * callback. Use @em nullptr if not required.
  293. * @param cb callback listener that will be notified when subscribe has
  294. */
  295. static ptr_t create(Type typ, iasync_client& cli, const_string_collection_ptr topics,
  296. void* userContext, iaction_listener& cb) {
  297. return std::make_shared<token>(typ, cli, topics, userContext, cb);
  298. }
  299. /**
  300. * Gets the type of action the token is tracking, like CONNECT, PUBLISH,
  301. * etc.
  302. * @return The type of action the token is tracking.
  303. */
  304. Type get_type() const { return type_; }
  305. /**
  306. * Gets the action listener for this token.
  307. * @return The action listener for this token.
  308. */
  309. virtual iaction_listener* get_action_callback() const {
  310. guard g(lock_);
  311. return listener_;
  312. }
  313. /**
  314. * Returns the MQTT client that is responsible for processing the
  315. * asynchronous action.
  316. * @return The client to which this token is connected.
  317. */
  318. virtual iasync_client* get_client() const { return cli_; }
  319. /**
  320. * Returns the ID of the message that is associated with the token.
  321. * @return The message ID of the transaction being tracked.
  322. */
  323. virtual int get_message_id() const {
  324. static_assert(sizeof(msgId_) <= sizeof(int), "MQTTAsync_token must fit into int");
  325. return int(msgId_);
  326. }
  327. /**
  328. * Gets the topic string(s) for the action being tracked by this
  329. * token.
  330. * @return A const pointer to the collection of topics being tracked by
  331. * the token.
  332. */
  333. virtual const_string_collection_ptr get_topics() const {
  334. return topics_;
  335. }
  336. /**
  337. * Retrieve the context associated with an action.
  338. * @return The context associated with an action.
  339. */
  340. virtual void* get_user_context() const {
  341. guard g(lock_);
  342. return userContext_;
  343. }
  344. /**
  345. * Returns whether or not the action has finished.
  346. * @return @em true if the transaction has completed, @em false if not.
  347. */
  348. virtual bool is_complete() const { return complete_; }
  349. /**
  350. * Gets the return code from the action.
  351. * This is only valid after the action has completed (i.e. if @ref
  352. * is_complete() returns @em true).
  353. * @return The return code from the action.
  354. */
  355. virtual int get_return_code() const { return rc_; }
  356. /**
  357. * Register a listener to be notified when an action completes.
  358. * @param listener The callback to be notified when actions complete.
  359. */
  360. virtual void set_action_callback(iaction_listener& listener) {
  361. guard g(lock_);
  362. listener_ = &listener;
  363. }
  364. /**
  365. * Store some context associated with an action.
  366. * @param userContext optional object used to pass context to the
  367. * callback. Use @em nullptr if not required.
  368. */
  369. virtual void set_user_context(void* userContext) {
  370. guard g(lock_);
  371. userContext_ = userContext;
  372. }
  373. /**
  374. * Sets the number of results expected.
  375. * This is only required for subecribe_many() with < MQTTv5
  376. * @param n The number of results expected.
  377. */
  378. void set_num_expected(size_t n) { nExpected_ = n; }
  379. /**
  380. * Gets the properties for the operation.
  381. * @return A const reference to the properties for the operation
  382. */
  383. //const properties& get_properties() const { return props_; }
  384. /**
  385. * Gets the reason code for the operation.
  386. * @return The reason code for the operation.
  387. */
  388. ReasonCode get_reason_code() const { return reasonCode_; }
  389. /**
  390. * Blocks the current thread until the action this token is associated
  391. * with has completed.
  392. */
  393. virtual void wait();
  394. /**
  395. * Non-blocking check to see if the action has completed.
  396. * @return @em true if the wait finished successfully, @em false if the
  397. * action has not completed yet.
  398. */
  399. virtual bool try_wait() {
  400. guard g(lock_);
  401. if (complete_)
  402. check_ret();
  403. return complete_;
  404. }
  405. /**
  406. * Blocks the current thread until the action this token is associated
  407. * with has completed.
  408. * @param timeout The timeout (in milliseconds)
  409. * @return @em true if the wait finished successfully, @em false if a
  410. * timeout occurred.
  411. */
  412. virtual bool wait_for(long timeout) {
  413. return wait_for(std::chrono::milliseconds(timeout));
  414. }
  415. /**
  416. * Waits a relative amount of time for the action to complete.
  417. * @param relTime The amount of time to wait for the event.
  418. * @return @em true if the event gets signaled in the specified time,
  419. * @em false on a timeout.
  420. */
  421. template <class Rep, class Period>
  422. bool wait_for(const std::chrono::duration<Rep, Period>& relTime) {
  423. unique_lock g(lock_);
  424. if (!cond_.wait_for(g, std::chrono::milliseconds(relTime),
  425. [this]{return complete_;}))
  426. return false;
  427. check_ret();
  428. return true;
  429. }
  430. /**
  431. * Waits until an absolute time for the action to complete.
  432. * @param absTime The absolute time to wait for the event.
  433. * @return @em true if the event gets signaled in the specified time,
  434. * @em false on a timeout.
  435. */
  436. template <class Clock, class Duration>
  437. bool wait_until( const std::chrono::time_point<Clock, Duration>& absTime) {
  438. unique_lock g(lock_);
  439. if (!cond_.wait_until(g, absTime, [this]{return complete_;}))
  440. return false;
  441. check_ret();
  442. return true;
  443. }
  444. /**
  445. * Gets the response from a connect operation.
  446. * This returns the result of the completed operation. If the
  447. * operaton is not yet complete this will block until the result
  448. * is available.
  449. * @return The result of the operation.
  450. */
  451. connect_response get_connect_response() const;
  452. /**
  453. * Gets the response from a connect operation.
  454. * This returns the result of the completed operation. If the
  455. * operaton is not yet complete this will block until the result
  456. * is available.
  457. * @return The result of the operation.
  458. */
  459. subscribe_response get_subscribe_response() const;
  460. /**
  461. * Gets the response from a connect operation.
  462. * This returns the result of the completed operation. If the
  463. * operaton is not yet complete this will block until the result
  464. * is available.
  465. * @return The result of the operation.
  466. */
  467. unsubscribe_response get_unsubscribe_response() const;
  468. };
  469. /** Smart/shared pointer to a token object */
  470. using token_ptr = token::ptr_t;
  471. /** Smart/shared pointer to a const token object */
  472. using const_token_ptr = token::const_ptr_t;
  473. /////////////////////////////////////////////////////////////////////////////
  474. // end namespace mqtt
  475. }
  476. #endif // __mqtt_token_h