MQTTClient.h 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  1. /*******************************************************************************
  2. * Copyright (c) 2009, 2018 IBM Corp.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * http://www.eclipse.org/legal/epl-v10.html
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Ian Craggs - initial API and implementation and/or initial documentation
  15. * Ian Craggs, Allan Stockdill-Mander - SSL updates
  16. * Ian Craggs - multiple server connection support
  17. * Ian Craggs - MQTT 3.1.1 support
  18. * Ian Craggs - remove const from eyecatchers #168
  19. *******************************************************************************/
  20. /**
  21. * @cond MQTTClient_internal
  22. * @mainpage MQTT Client Library Internals
  23. * In the beginning there was one MQTT C client library, MQTTClient, as implemented in MQTTClient.c
  24. * This library was designed to be easy to use for applications which didn't mind if some of the calls
  25. * blocked for a while. For instance, the MQTTClient_connect call will block until a successful
  26. * connection has completed, or a connection has failed, which could be as long as the "connection
  27. * timeout" interval, whose default is 30 seconds.
  28. *
  29. * However in mobile devices and other windowing environments, blocking on the GUI thread is a bad
  30. * thing as it causes the user interface to freeze. Hence a new API, MQTTAsync, implemented
  31. * in MQTTAsync.c, was devised. There are no blocking calls in this library, so it is well suited
  32. * to GUI and mobile environments, at the expense of some extra complexity.
  33. *
  34. * Both libraries are designed to be sparing in the use of threads. So multiple client objects are
  35. * handled by one or two threads, with a select call in Socket_getReadySocket(), used to determine
  36. * when a socket has incoming data. This API is thread safe: functions may be called by multiple application
  37. * threads, with the exception of ::MQTTClient_yield and ::MQTTClient_receive, which are intended
  38. * for single threaded environments only.
  39. *
  40. * @endcond
  41. * @cond MQTTClient_main
  42. * @mainpage MQTT Client library for C
  43. * © Copyright IBM Corp. 2009, 2018
  44. *
  45. * @brief An MQTT client library in C.
  46. *
  47. * These pages describe the original more synchronous API which might be
  48. * considered easier to use. Some of the calls will block. For the new
  49. * totally asynchronous API where no calls block, which is especially suitable
  50. * for use in windowed environments, see the
  51. * <a href="../../MQTTAsync/html/index.html">MQTT C Client Asynchronous API Documentation</a>.
  52. * The MQTTClient API is not thread safe, whereas the MQTTAsync API is.
  53. *
  54. * An MQTT client application connects to MQTT-capable servers.
  55. * A typical client is responsible for collecting information from a telemetry
  56. * device and publishing the information to the server. It can also subscribe
  57. * to topics, receive messages, and use this information to control the
  58. * telemetry device.
  59. *
  60. * MQTT clients implement the published MQTT v3 protocol. You can write your own
  61. * API to the MQTT protocol using the programming language and platform of your
  62. * choice. This can be time-consuming and error-prone.
  63. *
  64. * To simplify writing MQTT client applications, this library encapsulates
  65. * the MQTT v3 protocol for you. Using this library enables a fully functional
  66. * MQTT client application to be written in a few lines of code.
  67. * The information presented here documents the API provided
  68. * by the MQTT Client library for C.
  69. *
  70. * <b>Using the client</b><br>
  71. * Applications that use the client library typically use a similar structure:
  72. * <ul>
  73. * <li>Create a client object</li>
  74. * <li>Set the options to connect to an MQTT server</li>
  75. * <li>Set up callback functions if multi-threaded (asynchronous mode)
  76. * operation is being used (see @ref async).</li>
  77. * <li>Subscribe to any topics the client needs to receive</li>
  78. * <li>Repeat until finished:</li>
  79. * <ul>
  80. * <li>Publish any messages the client needs to</li>
  81. * <li>Handle any incoming messages</li>
  82. * </ul>
  83. * <li>Disconnect the client</li>
  84. * <li>Free any memory being used by the client</li>
  85. * </ul>
  86. * Some simple examples are shown here:
  87. * <ul>
  88. * <li>@ref pubsync</li>
  89. * <li>@ref pubasync</li>
  90. * <li>@ref subasync</li>
  91. * </ul>
  92. * Additional information about important concepts is provided here:
  93. * <ul>
  94. * <li>@ref async</li>
  95. * <li>@ref wildcard</li>
  96. * <li>@ref qos</li>
  97. * <li>@ref tracing</li>
  98. * </ul>
  99. * @endcond
  100. */
  101. /*
  102. /// @cond EXCLUDE
  103. */
  104. #if !defined(MQTTCLIENT_H)
  105. #define MQTTCLIENT_H
  106. #if defined(__cplusplus)
  107. extern "C" {
  108. #endif
  109. #if defined(WIN32) || defined(WIN64)
  110. #define DLLImport __declspec(dllimport)
  111. #define DLLExport __declspec(dllexport)
  112. #else
  113. #define DLLImport extern
  114. #define DLLExport __attribute__ ((visibility ("default")))
  115. #endif
  116. #include <stdio.h>
  117. /*
  118. /// @endcond
  119. */
  120. #include "MQTTProperties.h"
  121. #include "MQTTReasonCodes.h"
  122. #include "MQTTSubscribeOpts.h"
  123. #if !defined(NO_PERSISTENCE)
  124. #include "MQTTClientPersistence.h"
  125. #endif
  126. /**
  127. * Return code: No error. Indicates successful completion of an MQTT client
  128. * operation.
  129. */
  130. #define MQTTCLIENT_SUCCESS 0
  131. /**
  132. * Return code: A generic error code indicating the failure of an MQTT client
  133. * operation.
  134. */
  135. #define MQTTCLIENT_FAILURE -1
  136. /* error code -2 is MQTTCLIENT_PERSISTENCE_ERROR */
  137. /**
  138. * Return code: The client is disconnected.
  139. */
  140. #define MQTTCLIENT_DISCONNECTED -3
  141. /**
  142. * Return code: The maximum number of messages allowed to be simultaneously
  143. * in-flight has been reached.
  144. */
  145. #define MQTTCLIENT_MAX_MESSAGES_INFLIGHT -4
  146. /**
  147. * Return code: An invalid UTF-8 string has been detected.
  148. */
  149. #define MQTTCLIENT_BAD_UTF8_STRING -5
  150. /**
  151. * Return code: A NULL parameter has been supplied when this is invalid.
  152. */
  153. #define MQTTCLIENT_NULL_PARAMETER -6
  154. /**
  155. * Return code: The topic has been truncated (the topic string includes
  156. * embedded NULL characters). String functions will not access the full topic.
  157. * Use the topic length value to access the full topic.
  158. */
  159. #define MQTTCLIENT_TOPICNAME_TRUNCATED -7
  160. /**
  161. * Return code: A structure parameter does not have the correct eyecatcher
  162. * and version number.
  163. */
  164. #define MQTTCLIENT_BAD_STRUCTURE -8
  165. /**
  166. * Return code: A QoS value that falls outside of the acceptable range (0,1,2)
  167. */
  168. #define MQTTCLIENT_BAD_QOS -9
  169. /**
  170. * Return code: Attempting SSL connection using non-SSL version of library
  171. */
  172. #define MQTTCLIENT_SSL_NOT_SUPPORTED -10
  173. /**
  174. * Return code: unrecognized MQTT version
  175. */
  176. #define MQTTCLIENT_BAD_MQTT_VERSION -11
  177. /**
  178. * Return code: protocol prefix in serverURI should be tcp://, ssl://, ws:// or wss://
  179. * The TLS enabled prefixes (ssl, wss) are only valid if the TLS version of the library
  180. * is linked with.
  181. */
  182. #define MQTTCLIENT_BAD_PROTOCOL -14
  183. /**
  184. * Return code: option not applicable to the requested version of MQTT
  185. */
  186. #define MQTTCLIENT_BAD_MQTT_OPTION -15
  187. /**
  188. * Return code: call not applicable to the requested version of MQTT
  189. */
  190. #define MQTTCLIENT_WRONG_MQTT_VERSION -16
  191. /**
  192. * Default MQTT version to connect with. Use 3.1.1 then fall back to 3.1
  193. */
  194. #define MQTTVERSION_DEFAULT 0
  195. /**
  196. * MQTT version to connect with: 3.1
  197. */
  198. #define MQTTVERSION_3_1 3
  199. /**
  200. * MQTT version to connect with: 3.1.1
  201. */
  202. #define MQTTVERSION_3_1_1 4
  203. /**
  204. * MQTT version to connect with: 5
  205. */
  206. #define MQTTVERSION_5 5
  207. /**
  208. * Bad return code from subscribe, as defined in the 3.1.1 specification
  209. */
  210. #define MQTT_BAD_SUBSCRIBE 0x80
  211. /**
  212. * Initialization options
  213. */
  214. typedef struct
  215. {
  216. /** The eyecatcher for this structure. Must be MQTG. */
  217. char struct_id[4];
  218. /** The version number of this structure. Must be 0 */
  219. int struct_version;
  220. /** 1 = we do openssl init, 0 = leave it to the application */
  221. int do_openssl_init;
  222. } MQTTClient_init_options;
  223. #define MQTTClient_init_options_initializer { {'M', 'Q', 'T', 'G'}, 0, 0 }
  224. /**
  225. * Global init of mqtt library. Call once on program start to set global behaviour.
  226. * do_openssl_init - if mqtt library should initialize OpenSSL (1) or rely on the caller to do it before using the library (0)
  227. */
  228. DLLExport void MQTTClient_global_init(MQTTClient_init_options* inits);
  229. /**
  230. * A handle representing an MQTT client. A valid client handle is available
  231. * following a successful call to MQTTClient_create().
  232. */
  233. typedef void* MQTTClient;
  234. /**
  235. * A value representing an MQTT message. A delivery token is returned to the
  236. * client application when a message is published. The token can then be used to
  237. * check that the message was successfully delivered to its destination (see
  238. * MQTTClient_publish(),
  239. * MQTTClient_publishMessage(),
  240. * MQTTClient_deliveryComplete(),
  241. * MQTTClient_waitForCompletion() and
  242. * MQTTClient_getPendingDeliveryTokens()).
  243. */
  244. typedef int MQTTClient_deliveryToken;
  245. typedef int MQTTClient_token;
  246. /**
  247. * A structure representing the payload and attributes of an MQTT message. The
  248. * message topic is not part of this structure (see MQTTClient_publishMessage(),
  249. * MQTTClient_publish(), MQTTClient_receive(), MQTTClient_freeMessage()
  250. * and MQTTClient_messageArrived()).
  251. */
  252. typedef struct
  253. {
  254. /** The eyecatcher for this structure. must be MQTM. */
  255. char struct_id[4];
  256. /** The version number of this structure. Must be 0 or 1
  257. * 0 indicates no message properties */
  258. int struct_version;
  259. /** The length of the MQTT message payload in bytes. */
  260. int payloadlen;
  261. /** A pointer to the payload of the MQTT message. */
  262. void* payload;
  263. /**
  264. * The quality of service (QoS) assigned to the message.
  265. * There are three levels of QoS:
  266. * <DL>
  267. * <DT><B>QoS0</B></DT>
  268. * <DD>Fire and forget - the message may not be delivered</DD>
  269. * <DT><B>QoS1</B></DT>
  270. * <DD>At least once - the message will be delivered, but may be
  271. * delivered more than once in some circumstances.</DD>
  272. * <DT><B>QoS2</B></DT>
  273. * <DD>Once and one only - the message will be delivered exactly once.</DD>
  274. * </DL>
  275. */
  276. int qos;
  277. /**
  278. * The retained flag serves two purposes depending on whether the message
  279. * it is associated with is being published or received.
  280. *
  281. * <b>retained = true</b><br>
  282. * For messages being published, a true setting indicates that the MQTT
  283. * server should retain a copy of the message. The message will then be
  284. * transmitted to new subscribers to a topic that matches the message topic.
  285. * For subscribers registering a new subscription, the flag being true
  286. * indicates that the received message is not a new one, but one that has
  287. * been retained by the MQTT server.
  288. *
  289. * <b>retained = false</b> <br>
  290. * For publishers, this indicates that this message should not be retained
  291. * by the MQTT server. For subscribers, a false setting indicates this is
  292. * a normal message, received as a result of it being published to the
  293. * server.
  294. */
  295. int retained;
  296. /**
  297. * The dup flag indicates whether or not this message is a duplicate.
  298. * It is only meaningful when receiving QoS1 messages. When true, the
  299. * client application should take appropriate action to deal with the
  300. * duplicate message.
  301. */
  302. int dup;
  303. /** The message identifier is normally reserved for internal use by the
  304. * MQTT client and server.
  305. */
  306. int msgid;
  307. /**
  308. * The MQTT V5 properties associated with the message.
  309. */
  310. MQTTProperties properties;
  311. } MQTTClient_message;
  312. #define MQTTClient_message_initializer { {'M', 'Q', 'T', 'M'}, 1, 0, NULL, 0, 0, 0, 0, MQTTProperties_initializer }
  313. /**
  314. * This is a callback function. The client application
  315. * must provide an implementation of this function to enable asynchronous
  316. * receipt of messages. The function is registered with the client library by
  317. * passing it as an argument to MQTTClient_setCallbacks(). It is
  318. * called by the client library when a new message that matches a client
  319. * subscription has been received from the server. This function is executed on
  320. * a separate thread to the one on which the client application is running.
  321. * @param context A pointer to the <i>context</i> value originally passed to
  322. * MQTTClient_setCallbacks(), which contains any application-specific context.
  323. * @param topicName The topic associated with the received message.
  324. * @param topicLen The length of the topic if there are one
  325. * more NULL characters embedded in <i>topicName</i>, otherwise <i>topicLen</i>
  326. * is 0. If <i>topicLen</i> is 0, the value returned by <i>strlen(topicName)</i>
  327. * can be trusted. If <i>topicLen</i> is greater than 0, the full topic name
  328. * can be retrieved by accessing <i>topicName</i> as a byte array of length
  329. * <i>topicLen</i>.
  330. * @param message The MQTTClient_message structure for the received message.
  331. * This structure contains the message payload and attributes.
  332. * @return This function must return a boolean value indicating whether or not
  333. * the message has been safely received by the client application. Returning
  334. * true indicates that the message has been successfully handled.
  335. * Returning false indicates that there was a problem. In this
  336. * case, the client library will reinvoke MQTTClient_messageArrived() to
  337. * attempt to deliver the message to the application again.
  338. */
  339. typedef int MQTTClient_messageArrived(void* context, char* topicName, int topicLen, MQTTClient_message* message);
  340. /**
  341. * This is a callback function. The client application
  342. * must provide an implementation of this function to enable asynchronous
  343. * notification of delivery of messages. The function is registered with the
  344. * client library by passing it as an argument to MQTTClient_setCallbacks().
  345. * It is called by the client library after the client application has
  346. * published a message to the server. It indicates that the necessary
  347. * handshaking and acknowledgements for the requested quality of service (see
  348. * MQTTClient_message.qos) have been completed. This function is executed on a
  349. * separate thread to the one on which the client application is running.
  350. * <b>Note:</b>MQTTClient_deliveryComplete() is not called when messages are
  351. * published at QoS0.
  352. * @param context A pointer to the <i>context</i> value originally passed to
  353. * MQTTClient_setCallbacks(), which contains any application-specific context.
  354. * @param dt The ::MQTTClient_deliveryToken associated with
  355. * the published message. Applications can check that all messages have been
  356. * correctly published by matching the delivery tokens returned from calls to
  357. * MQTTClient_publish() and MQTTClient_publishMessage() with the tokens passed
  358. * to this callback.
  359. */
  360. typedef void MQTTClient_deliveryComplete(void* context, MQTTClient_deliveryToken dt);
  361. /**
  362. * This is a callback function. The client application
  363. * must provide an implementation of this function to enable asynchronous
  364. * notification of the loss of connection to the server. The function is
  365. * registered with the client library by passing it as an argument to
  366. * MQTTClient_setCallbacks(). It is called by the client library if the client
  367. * loses its connection to the server. The client application must take
  368. * appropriate action, such as trying to reconnect or reporting the problem.
  369. * This function is executed on a separate thread to the one on which the
  370. * client application is running.
  371. * @param context A pointer to the <i>context</i> value originally passed to
  372. * MQTTClient_setCallbacks(), which contains any application-specific context.
  373. * @param cause The reason for the disconnection.
  374. * Currently, <i>cause</i> is always set to NULL.
  375. */
  376. typedef void MQTTClient_connectionLost(void* context, char* cause);
  377. /**
  378. * This function sets the callback functions for a specific client.
  379. * If your client application doesn't use a particular callback, set the
  380. * relevant parameter to NULL. Calling MQTTClient_setCallbacks() puts the
  381. * client into multi-threaded mode. Any necessary message acknowledgements and
  382. * status communications are handled in the background without any intervention
  383. * from the client application. See @ref async for more information.
  384. *
  385. * <b>Note:</b> The MQTT client must be disconnected when this function is
  386. * called.
  387. * @param handle A valid client handle from a successful call to
  388. * MQTTClient_create().
  389. * @param context A pointer to any application-specific context. The
  390. * the <i>context</i> pointer is passed to each of the callback functions to
  391. * provide access to the context information in the callback.
  392. * @param cl A pointer to an MQTTClient_connectionLost() callback
  393. * function. You can set this to NULL if your application doesn't handle
  394. * disconnections.
  395. * @param ma A pointer to an MQTTClient_messageArrived() callback
  396. * function. This callback function must be specified when you call
  397. * MQTTClient_setCallbacks().
  398. * @param dc A pointer to an MQTTClient_deliveryComplete() callback
  399. * function. You can set this to NULL if your application publishes
  400. * synchronously or if you do not want to check for successful delivery.
  401. * @return ::MQTTCLIENT_SUCCESS if the callbacks were correctly set,
  402. * ::MQTTCLIENT_FAILURE if an error occurred.
  403. */
  404. DLLExport int MQTTClient_setCallbacks(MQTTClient handle, void* context, MQTTClient_connectionLost* cl,
  405. MQTTClient_messageArrived* ma, MQTTClient_deliveryComplete* dc);
  406. /**
  407. * This is a callback function, which will be called when the a disconnect
  408. * packet is received from the server. This applies to MQTT V5 and above only.
  409. * @param context A pointer to the <i>context</i> value originally passed to
  410. * ::MQTTAsync_setDisconnected(), which contains any application-specific context.
  411. * @param properties The MQTT V5 properties received with the disconnect, if any.
  412. * @param reasonCode The MQTT V5 reason code received with the disconnect.
  413. * Currently, <i>cause</i> is always set to NULL.
  414. */
  415. typedef void MQTTClient_disconnected(void* context, MQTTProperties* properties,
  416. enum MQTTReasonCodes reasonCode);
  417. /**
  418. * Sets the MQTTClient_disconnected() callback function for a client. This will be called
  419. * if a disconnect packet is received from the server. Only valid for MQTT V5 and above.
  420. * @param handle A valid client handle from a successful call to
  421. * MQTTClient_create().
  422. * @param context A pointer to any application-specific context. The
  423. * the <i>context</i> pointer is passed to each of the callback functions to
  424. * provide access to the context information in the callback.
  425. * @param co A pointer to an MQTTClient_disconnected() callback
  426. * function. NULL removes the callback setting.
  427. * @return ::MQTTCLIENT_SUCCESS if the callbacks were correctly set,
  428. * ::MQTTCLIENT_FAILURE if an error occurred.
  429. */
  430. DLLExport int MQTTClient_setDisconnected(MQTTClient handle, void* context, MQTTClient_disconnected* co);
  431. /**
  432. * This is a callback function, the MQTT V5 version of MQTTClient_deliveryComplete().
  433. * The client application
  434. * must provide an implementation of this function to enable asynchronous
  435. * notification of the completed delivery of messages.
  436. * It is called by the client library after the client application has
  437. * published a message to the server. It indicates that the necessary
  438. * handshaking and acknowledgements for the requested quality of service (see
  439. * MQTTClient_message.qos) have been completed. This function is executed on a
  440. * separate thread to the one on which the client application is running.
  441. * <b>Note:</b> It is not called when messages are published at QoS0.
  442. * @param context A pointer to the <i>context</i> value originally passed to
  443. * MQTTClient_setCallbacks(), which contains any application-specific context.
  444. * @param dt The ::MQTTClient_deliveryToken associated with
  445. * the published message. Applications can check that all messages have been
  446. * correctly published by matching the delivery tokens returned from calls to
  447. * MQTTClient_publish() and MQTTClient_publishMessage() with the tokens passed
  448. * to this callback.
  449. * @param packet_type the last received packet type for this completion. For QoS 1
  450. * always PUBACK. For QoS 2 could be PUBREC or PUBCOMP.
  451. * @param properties the MQTT V5 properties returned with the last packet from the server
  452. * @param reasonCode the reason code returned from the server
  453. */
  454. typedef void MQTTClient_published(void* context, int dt, int packet_type, MQTTProperties* properties,
  455. enum MQTTReasonCodes reasonCode);
  456. DLLExport int MQTTClient_setPublished(MQTTClient handle, void* context, MQTTClient_published* co);
  457. /**
  458. * This function creates an MQTT client ready for connection to the
  459. * specified server and using the specified persistent storage (see
  460. * MQTTClient_persistence). See also MQTTClient_destroy().
  461. * @param handle A pointer to an ::MQTTClient handle. The handle is
  462. * populated with a valid client reference following a successful return from
  463. * this function.
  464. * @param serverURI A null-terminated string specifying the server to
  465. * which the client will connect. It takes the form <i>protocol://host:port</i>.
  466. * Currently, <i>protocol</i> must be <i>tcp</i> or <i>ssl</i>.
  467. * For <i>host</i>, you can
  468. * specify either an IP address or a host name. For instance, to connect to
  469. * a server running on the local machines with the default MQTT port, specify
  470. * <i>tcp://localhost:1883</i>.
  471. * @param clientId The client identifier passed to the server when the
  472. * client connects to it. It is a null-terminated UTF-8 encoded string.
  473. * @param persistence_type The type of persistence to be used by the client:
  474. * <br>
  475. * ::MQTTCLIENT_PERSISTENCE_NONE: Use in-memory persistence. If the device or
  476. * system on which the client is running fails or is switched off, the current
  477. * state of any in-flight messages is lost and some messages may not be
  478. * delivered even at QoS1 and QoS2.
  479. * <br>
  480. * ::MQTTCLIENT_PERSISTENCE_DEFAULT: Use the default (file system-based)
  481. * persistence mechanism. Status about in-flight messages is held in persistent
  482. * storage and provides some protection against message loss in the case of
  483. * unexpected failure.
  484. * <br>
  485. * ::MQTTCLIENT_PERSISTENCE_USER: Use an application-specific persistence
  486. * implementation. Using this type of persistence gives control of the
  487. * persistence mechanism to the application. The application has to implement
  488. * the MQTTClient_persistence interface.
  489. * @param persistence_context If the application uses
  490. * ::MQTTCLIENT_PERSISTENCE_NONE persistence, this argument is unused and should
  491. * be set to NULL. For ::MQTTCLIENT_PERSISTENCE_DEFAULT persistence, it
  492. * should be set to the location of the persistence directory (if set
  493. * to NULL, the persistence directory used is the working directory).
  494. * Applications that use ::MQTTCLIENT_PERSISTENCE_USER persistence set this
  495. * argument to point to a valid MQTTClient_persistence structure.
  496. * @return ::MQTTCLIENT_SUCCESS if the client is successfully created, otherwise
  497. * an error code is returned.
  498. */
  499. DLLExport int MQTTClient_create(MQTTClient* handle, const char* serverURI, const char* clientId,
  500. int persistence_type, void* persistence_context);
  501. typedef struct
  502. {
  503. /** The eyecatcher for this structure. must be MQCO. */
  504. char struct_id[4];
  505. /** The version number of this structure. Must be 0 */
  506. int struct_version;
  507. /** Whether the MQTT version is 3.1, 3.1.1, or 5. To use V5, this must be set.
  508. * MQTT V5 has to be chosen here, because during the create call the message persistence
  509. * is initialized, and we want to know whether the format of any persisted messages
  510. * is appropriate for the MQTT version we are going to connect with. Selecting 3.1 or
  511. * 3.1.1 and attempting to read 5.0 persisted messages will result in an error on create. */
  512. int MQTTVersion;
  513. } MQTTClient_createOptions;
  514. #define MQTTClient_createOptions_initializer { {'M', 'Q', 'C', 'O'}, 0, MQTTVERSION_DEFAULT }
  515. /**
  516. * A version of :MQTTClient_create() with additional options.
  517. * This function creates an MQTT client ready for connection to the
  518. * specified server and using the specified persistent storage (see
  519. * MQTTClient_persistence). See also MQTTClient_destroy().
  520. * @param handle A pointer to an ::MQTTClient handle. The handle is
  521. * populated with a valid client reference following a successful return from
  522. * this function.
  523. * @param serverURI A null-terminated string specifying the server to
  524. * which the client will connect. It takes the form <i>protocol://host:port</i>.
  525. * Currently, <i>protocol</i> must be <i>tcp</i> or <i>ssl</i>.
  526. * For <i>host</i>, you can
  527. * specify either an IP address or a host name. For instance, to connect to
  528. * a server running on the local machines with the default MQTT port, specify
  529. * <i>tcp://localhost:1883</i>.
  530. * @param clientId The client identifier passed to the server when the
  531. * client connects to it. It is a null-terminated UTF-8 encoded string.
  532. * @param persistence_type The type of persistence to be used by the client:
  533. * <br>
  534. * ::MQTTCLIENT_PERSISTENCE_NONE: Use in-memory persistence. If the device or
  535. * system on which the client is running fails or is switched off, the current
  536. * state of any in-flight messages is lost and some messages may not be
  537. * delivered even at QoS1 and QoS2.
  538. * <br>
  539. * ::MQTTCLIENT_PERSISTENCE_DEFAULT: Use the default (file system-based)
  540. * persistence mechanism. Status about in-flight messages is held in persistent
  541. * storage and provides some protection against message loss in the case of
  542. * unexpected failure.
  543. * <br>
  544. * ::MQTTCLIENT_PERSISTENCE_USER: Use an application-specific persistence
  545. * implementation. Using this type of persistence gives control of the
  546. * persistence mechanism to the application. The application has to implement
  547. * the MQTTClient_persistence interface.
  548. * @param persistence_context If the application uses
  549. * ::MQTTCLIENT_PERSISTENCE_NONE persistence, this argument is unused and should
  550. * be set to NULL. For ::MQTTCLIENT_PERSISTENCE_DEFAULT persistence, it
  551. * should be set to the location of the persistence directory (if set
  552. * to NULL, the persistence directory used is the working directory).
  553. * Applications that use ::MQTTCLIENT_PERSISTENCE_USER persistence set this
  554. * argument to point to a valid MQTTClient_persistence structure.
  555. * @param options additional options for the create.
  556. * @return ::MQTTCLIENT_SUCCESS if the client is successfully created, otherwise
  557. * an error code is returned.
  558. */
  559. DLLExport int MQTTClient_createWithOptions(MQTTClient* handle, const char* serverURI, const char* clientId,
  560. int persistence_type, void* persistence_context, MQTTClient_createOptions* options);
  561. /**
  562. * MQTTClient_willOptions defines the MQTT "Last Will and Testament" (LWT) settings for
  563. * the client. In the event that a client unexpectedly loses its connection to
  564. * the server, the server publishes the LWT message to the LWT topic on
  565. * behalf of the client. This allows other clients (subscribed to the LWT topic)
  566. * to be made aware that the client has disconnected. To enable the LWT
  567. * function for a specific client, a valid pointer to an MQTTClient_willOptions
  568. * structure is passed in the MQTTClient_connectOptions structure used in the
  569. * MQTTClient_connect() call that connects the client to the server. The pointer
  570. * to MQTTClient_willOptions can be set to NULL if the LWT function is not
  571. * required.
  572. */
  573. typedef struct
  574. {
  575. /** The eyecatcher for this structure. must be MQTW. */
  576. char struct_id[4];
  577. /** The version number of this structure. Must be 0 or 1
  578. 0 means there is no binary payload option
  579. */
  580. int struct_version;
  581. /** The LWT topic to which the LWT message will be published. */
  582. const char* topicName;
  583. /** The LWT payload in string form. */
  584. const char* message;
  585. /**
  586. * The retained flag for the LWT message (see MQTTClient_message.retained).
  587. */
  588. int retained;
  589. /**
  590. * The quality of service setting for the LWT message (see
  591. * MQTTClient_message.qos and @ref qos).
  592. */
  593. int qos;
  594. /** The LWT payload in binary form. This is only checked and used if the message option is NULL */
  595. struct
  596. {
  597. int len; /**< binary payload length */
  598. const void* data; /**< binary payload data */
  599. } payload;
  600. } MQTTClient_willOptions;
  601. #define MQTTClient_willOptions_initializer { {'M', 'Q', 'T', 'W'}, 1, NULL, NULL, 0, 0, {0, NULL} }
  602. #define MQTT_SSL_VERSION_DEFAULT 0
  603. #define MQTT_SSL_VERSION_TLS_1_0 1
  604. #define MQTT_SSL_VERSION_TLS_1_1 2
  605. #define MQTT_SSL_VERSION_TLS_1_2 3
  606. /**
  607. * MQTTClient_sslProperties defines the settings to establish an SSL/TLS connection using the
  608. * OpenSSL library. It covers the following scenarios:
  609. * - Server authentication: The client needs the digital certificate of the server. It is included
  610. * in a store containting trusted material (also known as "trust store").
  611. * - Mutual authentication: Both client and server are authenticated during the SSL handshake. In
  612. * addition to the digital certificate of the server in a trust store, the client will need its own
  613. * digital certificate and the private key used to sign its digital certificate stored in a "key store".
  614. * - Anonymous connection: Both client and server do not get authenticated and no credentials are needed
  615. * to establish an SSL connection. Note that this scenario is not fully secure since it is subject to
  616. * man-in-the-middle attacks.
  617. */
  618. typedef struct
  619. {
  620. /** The eyecatcher for this structure. Must be MQTS */
  621. char struct_id[4];
  622. /** The version number of this structure. Must be 0, or 1 to enable TLS version selection. */
  623. int struct_version;
  624. /** The file in PEM format containing the public digital certificates trusted by the client. */
  625. const char* trustStore;
  626. /** The file in PEM format containing the public certificate chain of the client. It may also include
  627. * the client's private key.
  628. */
  629. const char* keyStore;
  630. /** If not included in the sslKeyStore, this setting points to the file in PEM format containing
  631. * the client's private key.
  632. */
  633. const char* privateKey;
  634. /** The password to load the client's privateKey if encrypted. */
  635. const char* privateKeyPassword;
  636. /**
  637. * The list of cipher suites that the client will present to the server during the SSL handshake. For a
  638. * full explanation of the cipher list format, please see the OpenSSL on-line documentation:
  639. * http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT
  640. * If this setting is ommitted, its default value will be "ALL", that is, all the cipher suites -excluding
  641. * those offering no encryption- will be considered.
  642. * This setting can be used to set an SSL anonymous connection ("aNULL" string value, for instance).
  643. */
  644. const char* enabledCipherSuites;
  645. /** True/False option to enable verification of the server certificate **/
  646. int enableServerCertAuth;
  647. /** The SSL/TLS version to use. Specify one of MQTT_SSL_VERSION_DEFAULT (0),
  648. * MQTT_SSL_VERSION_TLS_1_0 (1), MQTT_SSL_VERSION_TLS_1_1 (2) or MQTT_SSL_VERSION_TLS_1_2 (3).
  649. * Only used if struct_version is >= 1.
  650. */
  651. int sslVersion;
  652. /**
  653. * Whether to carry out post-connect checks, including that a certificate
  654. * matches the given host name.
  655. * Exists only if struct_version >= 2
  656. */
  657. int verify;
  658. /**
  659. * From the OpenSSL documentation:
  660. * If CApath is not NULL, it points to a directory containing CA certificates in PEM format.
  661. * Exists only if struct_version >= 2
  662. */
  663. const char* CApath;
  664. /**
  665. * Callback function for OpenSSL error handler ERR_print_errors_cb
  666. * Exists only if struct_version >= 3
  667. */
  668. int (*ssl_error_cb) (const char *str, size_t len, void *u);
  669. /**
  670. * Application-specific contex for OpenSSL error handler ERR_print_errors_cb
  671. * Exists only if struct_version >= 3
  672. */
  673. void* ssl_error_context;
  674. /**
  675. * Callback function for setting TLS-PSK options. Parameters correspond to that of
  676. * SSL_CTX_set_psk_client_callback, except for u which is the pointer ssl_psk_context.
  677. * Exists only if struct_version >= 4
  678. */
  679. unsigned int (*ssl_psk_cb) (const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len, void *u);
  680. /**
  681. * Application-specific contex for ssl_psk_cb
  682. * Exists only if struct_version >= 4
  683. */
  684. void* ssl_psk_context;
  685. /**
  686. * Don't load default SSL CA. Should be used together with PSK to make sure
  687. * regular servers with certificate in place is not accepted.
  688. * Exists only if struct_version >= 4
  689. */
  690. int disableDefaultTrustStore;
  691. } MQTTClient_SSLOptions;
  692. #define MQTTClient_SSLOptions_initializer { {'M', 'Q', 'T', 'S'}, 4, NULL, NULL, NULL, NULL, NULL, 1, MQTT_SSL_VERSION_DEFAULT, 0, NULL, NULL, NULL, NULL, NULL, 0 }
  693. /**
  694. * MQTTClient_connectOptions defines several settings that control the way the
  695. * client connects to an MQTT server.
  696. *
  697. * <b>Note:</b> Default values are not defined for members of
  698. * MQTTClient_connectOptions so it is good practice to specify all settings.
  699. * If the MQTTClient_connectOptions structure is defined as an automatic
  700. * variable, all members are set to random values and thus must be set by the
  701. * client application. If the MQTTClient_connectOptions structure is defined
  702. * as a static variable, initialization (in compliant compilers) sets all
  703. * values to 0 (NULL for pointers). A #keepAliveInterval setting of 0 prevents
  704. * correct operation of the client and so you <b>must</b> at least set a value
  705. * for #keepAliveInterval.
  706. */
  707. typedef struct
  708. {
  709. /** The eyecatcher for this structure. must be MQTC. */
  710. char struct_id[4];
  711. /** The version number of this structure. Must be 0, 1, 2, 3, 4, 5 or 6.
  712. * 0 signifies no SSL options and no serverURIs
  713. * 1 signifies no serverURIs
  714. * 2 signifies no MQTTVersion
  715. * 3 signifies no returned values
  716. * 4 signifies no binary password option
  717. * 5 signifies no maxInflightMessages and cleanstart
  718. */
  719. int struct_version;
  720. /** The "keep alive" interval, measured in seconds, defines the maximum time
  721. * that should pass without communication between the client and the server
  722. * The client will ensure that at least one message travels across the
  723. * network within each keep alive period. In the absence of a data-related
  724. * message during the time period, the client sends a very small MQTT
  725. * "ping" message, which the server will acknowledge. The keep alive
  726. * interval enables the client to detect when the server is no longer
  727. * available without having to wait for the long TCP/IP timeout.
  728. */
  729. int keepAliveInterval;
  730. /**
  731. * This is a boolean value. The cleansession setting controls the behaviour
  732. * of both the client and the server at connection and disconnection time.
  733. * The client and server both maintain session state information. This
  734. * information is used to ensure "at least once" and "exactly once"
  735. * delivery, and "exactly once" receipt of messages. Session state also
  736. * includes subscriptions created by an MQTT client. You can choose to
  737. * maintain or discard state information between sessions.
  738. *
  739. * When cleansession is true, the state information is discarded at
  740. * connect and disconnect. Setting cleansession to false keeps the state
  741. * information. When you connect an MQTT client application with
  742. * MQTTClient_connect(), the client identifies the connection using the
  743. * client identifier and the address of the server. The server checks
  744. * whether session information for this client
  745. * has been saved from a previous connection to the server. If a previous
  746. * session still exists, and cleansession=true, then the previous session
  747. * information at the client and server is cleared. If cleansession=false,
  748. * the previous session is resumed. If no previous session exists, a new
  749. * session is started.
  750. */
  751. int cleansession;
  752. /**
  753. * This is a boolean value that controls how many messages can be in-flight
  754. * simultaneously. Setting <i>reliable</i> to true means that a published
  755. * message must be completed (acknowledgements received) before another
  756. * can be sent. Attempts to publish additional messages receive an
  757. * ::MQTTCLIENT_MAX_MESSAGES_INFLIGHT return code. Setting this flag to
  758. * false allows up to 10 messages to be in-flight. This can increase
  759. * overall throughput in some circumstances.
  760. */
  761. int reliable;
  762. /**
  763. * This is a pointer to an MQTTClient_willOptions structure. If your
  764. * application does not make use of the Last Will and Testament feature,
  765. * set this pointer to NULL.
  766. */
  767. MQTTClient_willOptions* will;
  768. /**
  769. * MQTT servers that support the MQTT v3.1.1 protocol provide authentication
  770. * and authorisation by user name and password. This is the user name
  771. * parameter.
  772. */
  773. const char* username;
  774. /**
  775. * MQTT servers that support the MQTT v3.1.1 protocol provide authentication
  776. * and authorisation by user name and password. This is the password
  777. * parameter.
  778. */
  779. const char* password;
  780. /**
  781. * The time interval in seconds to allow a connect to complete.
  782. */
  783. int connectTimeout;
  784. /**
  785. * The time interval in seconds after which unacknowledged publish requests are
  786. * retried during a TCP session. With MQTT 3.1.1 and later, retries are
  787. * not required except on reconnect. 0 turns off in-session retries, and is the
  788. * recommended setting. Adding retries to an already overloaded network only
  789. * exacerbates the problem.
  790. */
  791. int retryInterval;
  792. /**
  793. * This is a pointer to an MQTTClient_SSLOptions structure. If your
  794. * application does not make use of SSL, set this pointer to NULL.
  795. */
  796. MQTTClient_SSLOptions* ssl;
  797. /**
  798. * The number of entries in the optional serverURIs array. Defaults to 0.
  799. */
  800. int serverURIcount;
  801. /**
  802. * An optional array of null-terminated strings specifying the servers to
  803. * which the client will connect. Each string takes the form <i>protocol://host:port</i>.
  804. * <i>protocol</i> must be <i>tcp</i> or <i>ssl</i>. For <i>host</i>, you can
  805. * specify either an IP address or a host name. For instance, to connect to
  806. * a server running on the local machines with the default MQTT port, specify
  807. * <i>tcp://localhost:1883</i>.
  808. * If this list is empty (the default), the server URI specified on MQTTClient_create()
  809. * is used.
  810. */
  811. char* const* serverURIs;
  812. /**
  813. * Sets the version of MQTT to be used on the connect.
  814. * MQTTVERSION_DEFAULT (0) = default: start with 3.1.1, and if that fails, fall back to 3.1
  815. * MQTTVERSION_3_1 (3) = only try version 3.1
  816. * MQTTVERSION_3_1_1 (4) = only try version 3.1.1
  817. * MQTTVERSION_5 (5) = only try version 5.0
  818. */
  819. int MQTTVersion;
  820. /**
  821. * Returned from the connect when the MQTT version used to connect is 3.1.1
  822. */
  823. struct
  824. {
  825. const char* serverURI; /**< the serverURI connected to */
  826. int MQTTVersion; /**< the MQTT version used to connect with */
  827. int sessionPresent; /**< if the MQTT version is 3.1.1, the value of sessionPresent returned in the connack */
  828. } returned;
  829. /**
  830. * Optional binary password. Only checked and used if the password option is NULL
  831. */
  832. struct
  833. {
  834. int len; /**< binary password length */
  835. const void* data; /**< binary password data */
  836. } binarypwd;
  837. /**
  838. * The maximum number of messages in flight
  839. */
  840. int maxInflightMessages;
  841. /*
  842. * MQTT V5 clean start flag. Only clears state at the beginning of the session.
  843. */
  844. int cleanstart;
  845. } MQTTClient_connectOptions;
  846. #define MQTTClient_connectOptions_initializer { {'M', 'Q', 'T', 'C'}, 6, 60, 1, 1, NULL, NULL, NULL, 30, 0, NULL, 0, NULL, MQTTVERSION_DEFAULT, {NULL, 0, 0}, {0, NULL}, -1, 0}
  847. #define MQTTClient_connectOptions_initializer5 { {'M', 'Q', 'T', 'C'}, 6, 60, 0, 1, NULL, NULL, NULL, 30, 0, NULL, 0, NULL, MQTTVERSION_5, {NULL, 0, 0}, {0, NULL}, -1, 1}
  848. /**
  849. * MQTTClient_libraryInfo is used to store details relating to the currently used
  850. * library such as the version in use, the time it was built and relevant openSSL
  851. * options.
  852. * There is one static instance of this struct in MQTTClient.c
  853. */
  854. typedef struct
  855. {
  856. const char* name;
  857. const char* value;
  858. } MQTTClient_nameValue;
  859. /**
  860. * This function returns version information about the library.
  861. * no trace information will be returned.
  862. * @return an array of strings describing the library. The last entry is a NULL pointer.
  863. */
  864. DLLExport MQTTClient_nameValue* MQTTClient_getVersionInfo(void);
  865. /**
  866. * This function attempts to connect a previously-created client (see
  867. * MQTTClient_create()) to an MQTT server using the specified options. If you
  868. * want to enable asynchronous message and status notifications, you must call
  869. * MQTTClient_setCallbacks() prior to MQTTClient_connect().
  870. * @param handle A valid client handle from a successful call to
  871. * MQTTClient_create().
  872. * @param options A pointer to a valid MQTTClient_connectOptions
  873. * structure.
  874. * @return ::MQTTCLIENT_SUCCESS if the client successfully connects to the
  875. * server. An error code is returned if the client was unable to connect to
  876. * the server.
  877. * Error codes greater than 0 are returned by the MQTT protocol:<br><br>
  878. * <b>1</b>: Connection refused: Unacceptable protocol version<br>
  879. * <b>2</b>: Connection refused: Identifier rejected<br>
  880. * <b>3</b>: Connection refused: Server unavailable<br>
  881. * <b>4</b>: Connection refused: Bad user name or password<br>
  882. * <b>5</b>: Connection refused: Not authorized<br>
  883. * <b>6-255</b>: Reserved for future use<br>
  884. */
  885. DLLExport int MQTTClient_connect(MQTTClient handle, MQTTClient_connectOptions* options);
  886. typedef struct MQTTResponse
  887. {
  888. int version;
  889. enum MQTTReasonCodes reasonCode;
  890. int reasonCodeCount; /* used for subscribeMany5 and unsubscribeMany5 */
  891. enum MQTTReasonCodes* reasonCodes; /* used for subscribeMany5 and unsubscribeMany5 */
  892. MQTTProperties* properties; /* optional */
  893. } MQTTResponse;
  894. #define MQTTResponse_initializer {1, MQTTREASONCODE_SUCCESS, 0, NULL, NULL}
  895. DLLExport void MQTTResponse_free(MQTTResponse response);
  896. DLLExport MQTTResponse MQTTClient_connect5(MQTTClient handle, MQTTClient_connectOptions* options,
  897. MQTTProperties* connectProperties, MQTTProperties* willProperties);
  898. /**
  899. * This function attempts to disconnect the client from the MQTT
  900. * server. In order to allow the client time to complete handling of messages
  901. * that are in-flight when this function is called, a timeout period is
  902. * specified. When the timeout period has expired, the client disconnects even
  903. * if there are still outstanding message acknowledgements.
  904. * The next time the client connects to the same server, any QoS 1 or 2
  905. * messages which have not completed will be retried depending on the
  906. * cleansession settings for both the previous and the new connection (see
  907. * MQTTClient_connectOptions.cleansession and MQTTClient_connect()).
  908. * @param handle A valid client handle from a successful call to
  909. * MQTTClient_create().
  910. * @param timeout The client delays disconnection for up to this time (in
  911. * milliseconds) in order to allow in-flight message transfers to complete.
  912. * @return ::MQTTCLIENT_SUCCESS if the client successfully disconnects from
  913. * the server. An error code is returned if the client was unable to disconnect
  914. * from the server
  915. */
  916. DLLExport int MQTTClient_disconnect(MQTTClient handle, int timeout);
  917. DLLExport int MQTTClient_disconnect5(MQTTClient handle, int timeout, enum MQTTReasonCodes reason, MQTTProperties* props);
  918. /**
  919. * This function allows the client application to test whether or not a
  920. * client is currently connected to the MQTT server.
  921. * @param handle A valid client handle from a successful call to
  922. * MQTTClient_create().
  923. * @return Boolean true if the client is connected, otherwise false.
  924. */
  925. DLLExport int MQTTClient_isConnected(MQTTClient handle);
  926. /* Subscribe is synchronous. QoS list parameter is changed on return to granted QoSs.
  927. Returns return code, MQTTCLIENT_SUCCESS == success, non-zero some sort of error (TBD) */
  928. /**
  929. * This function attempts to subscribe a client to a single topic, which may
  930. * contain wildcards (see @ref wildcard). This call also specifies the
  931. * @ref qos requested for the subscription
  932. * (see also MQTTClient_subscribeMany()).
  933. * @param handle A valid client handle from a successful call to
  934. * MQTTClient_create().
  935. * @param topic The subscription topic, which may include wildcards.
  936. * @param qos The requested quality of service for the subscription.
  937. * @return ::MQTTCLIENT_SUCCESS if the subscription request is successful.
  938. * An error code is returned if there was a problem registering the
  939. * subscription.
  940. */
  941. DLLExport int MQTTClient_subscribe(MQTTClient handle, const char* topic, int qos);
  942. DLLExport MQTTResponse MQTTClient_subscribe5(MQTTClient handle, const char* topic, int qos,
  943. MQTTSubscribe_options* opts, MQTTProperties* props);
  944. /**
  945. * This function attempts to subscribe a client to a list of topics, which may
  946. * contain wildcards (see @ref wildcard). This call also specifies the
  947. * @ref qos requested for each topic (see also MQTTClient_subscribe()).
  948. * @param handle A valid client handle from a successful call to
  949. * MQTTClient_create().
  950. * @param count The number of topics for which the client is requesting
  951. * subscriptions.
  952. * @param topic An array (of length <i>count</i>) of pointers to
  953. * topics, each of which may include wildcards.
  954. * @param qos An array (of length <i>count</i>) of @ref qos
  955. * values. qos[n] is the requested QoS for topic[n].
  956. * @return ::MQTTCLIENT_SUCCESS if the subscription request is successful.
  957. * An error code is returned if there was a problem registering the
  958. * subscriptions.
  959. */
  960. DLLExport int MQTTClient_subscribeMany(MQTTClient handle, int count, char* const* topic, int* qos);
  961. DLLExport MQTTResponse MQTTClient_subscribeMany5(MQTTClient handle, int count, char* const* topic,
  962. int* qos, MQTTSubscribe_options* opts, MQTTProperties* props);
  963. /**
  964. * This function attempts to remove an existing subscription made by the
  965. * specified client.
  966. * @param handle A valid client handle from a successful call to
  967. * MQTTClient_create().
  968. * @param topic The topic for the subscription to be removed, which may
  969. * include wildcards (see @ref wildcard).
  970. * @return ::MQTTCLIENT_SUCCESS if the subscription is removed.
  971. * An error code is returned if there was a problem removing the
  972. * subscription.
  973. */
  974. DLLExport int MQTTClient_unsubscribe(MQTTClient handle, const char* topic);
  975. DLLExport MQTTResponse MQTTClient_unsubscribe5(MQTTClient handle, const char* topic, MQTTProperties* props);
  976. /**
  977. * This function attempts to remove existing subscriptions to a list of topics
  978. * made by the specified client.
  979. * @param handle A valid client handle from a successful call to
  980. * MQTTClient_create().
  981. * @param count The number subscriptions to be removed.
  982. * @param topic An array (of length <i>count</i>) of pointers to the topics of
  983. * the subscriptions to be removed, each of which may include wildcards.
  984. * @return ::MQTTCLIENT_SUCCESS if the subscriptions are removed.
  985. * An error code is returned if there was a problem removing the subscriptions.
  986. */
  987. DLLExport int MQTTClient_unsubscribeMany(MQTTClient handle, int count, char* const* topic);
  988. DLLExport MQTTResponse MQTTClient_unsubscribeMany5(MQTTClient handle, int count, char* const* topic, MQTTProperties* props);
  989. /**
  990. * This function attempts to publish a message to a given topic (see also
  991. * MQTTClient_publishMessage()). An ::MQTTClient_deliveryToken is issued when
  992. * this function returns successfully. If the client application needs to
  993. * test for succesful delivery of QoS1 and QoS2 messages, this can be done
  994. * either asynchronously or synchronously (see @ref async,
  995. * ::MQTTClient_waitForCompletion and MQTTClient_deliveryComplete()).
  996. * @param handle A valid client handle from a successful call to
  997. * MQTTClient_create().
  998. * @param topicName The topic associated with this message.
  999. * @param payloadlen The length of the payload in bytes.
  1000. * @param payload A pointer to the byte array payload of the message.
  1001. * @param qos The @ref qos of the message.
  1002. * @param retained The retained flag for the message.
  1003. * @param dt A pointer to an ::MQTTClient_deliveryToken. This is populated
  1004. * with a token representing the message when the function returns
  1005. * successfully. If your application does not use delivery tokens, set this
  1006. * argument to NULL.
  1007. * @return ::MQTTCLIENT_SUCCESS if the message is accepted for publication.
  1008. * An error code is returned if there was a problem accepting the message.
  1009. */
  1010. DLLExport int MQTTClient_publish(MQTTClient handle, const char* topicName, int payloadlen, const void* payload, int qos, int retained,
  1011. MQTTClient_deliveryToken* dt);
  1012. DLLExport MQTTResponse MQTTClient_publish5(MQTTClient handle, const char* topicName, int payloadlen, const void* payload,
  1013. int qos, int retained, MQTTProperties* properties, MQTTClient_deliveryToken* dt);
  1014. /**
  1015. * This function attempts to publish a message to a given topic (see also
  1016. * MQTTClient_publish()). An ::MQTTClient_deliveryToken is issued when
  1017. * this function returns successfully. If the client application needs to
  1018. * test for succesful delivery of QoS1 and QoS2 messages, this can be done
  1019. * either asynchronously or synchronously (see @ref async,
  1020. * ::MQTTClient_waitForCompletion and MQTTClient_deliveryComplete()).
  1021. * @param handle A valid client handle from a successful call to
  1022. * MQTTClient_create().
  1023. * @param topicName The topic associated with this message.
  1024. * @param msg A pointer to a valid MQTTClient_message structure containing
  1025. * the payload and attributes of the message to be published.
  1026. * @param dt A pointer to an ::MQTTClient_deliveryToken. This is populated
  1027. * with a token representing the message when the function returns
  1028. * successfully. If your application does not use delivery tokens, set this
  1029. * argument to NULL.
  1030. * @return ::MQTTCLIENT_SUCCESS if the message is accepted for publication.
  1031. * An error code is returned if there was a problem accepting the message.
  1032. */
  1033. DLLExport int MQTTClient_publishMessage(MQTTClient handle, const char* topicName, MQTTClient_message* msg, MQTTClient_deliveryToken* dt);
  1034. DLLExport MQTTResponse MQTTClient_publishMessage5(MQTTClient handle, const char* topicName, MQTTClient_message* msg,
  1035. MQTTClient_deliveryToken* dt);
  1036. /**
  1037. * This function is called by the client application to synchronize execution
  1038. * of the main thread with completed publication of a message. When called,
  1039. * MQTTClient_waitForCompletion() blocks execution until the message has been
  1040. * successful delivered or the specified timeout has expired. See @ref async.
  1041. * @param handle A valid client handle from a successful call to
  1042. * MQTTClient_create().
  1043. * @param dt The ::MQTTClient_deliveryToken that represents the message being
  1044. * tested for successful delivery. Delivery tokens are issued by the
  1045. * publishing functions MQTTClient_publish() and MQTTClient_publishMessage().
  1046. * @param timeout The maximum time to wait in milliseconds.
  1047. * @return ::MQTTCLIENT_SUCCESS if the message was successfully delivered.
  1048. * An error code is returned if the timeout expires or there was a problem
  1049. * checking the token.
  1050. */
  1051. DLLExport int MQTTClient_waitForCompletion(MQTTClient handle, MQTTClient_deliveryToken dt, unsigned long timeout);
  1052. /**
  1053. * This function sets a pointer to an array of delivery tokens for
  1054. * messages that are currently in-flight (pending completion).
  1055. *
  1056. * <b>Important note:</b> The memory used to hold the array of tokens is
  1057. * malloc()'d in this function. The client application is responsible for
  1058. * freeing this memory when it is no longer required.
  1059. * @param handle A valid client handle from a successful call to
  1060. * MQTTClient_create().
  1061. * @param tokens The address of a pointer to an ::MQTTClient_deliveryToken.
  1062. * When the function returns successfully, the pointer is set to point to an
  1063. * array of tokens representing messages pending completion. The last member of
  1064. * the array is set to -1 to indicate there are no more tokens. If no tokens
  1065. * are pending, the pointer is set to NULL.
  1066. * @return ::MQTTCLIENT_SUCCESS if the function returns successfully.
  1067. * An error code is returned if there was a problem obtaining the list of
  1068. * pending tokens.
  1069. */
  1070. DLLExport int MQTTClient_getPendingDeliveryTokens(MQTTClient handle, MQTTClient_deliveryToken **tokens);
  1071. /**
  1072. * When implementing a single-threaded client, call this function periodically
  1073. * to allow processing of message retries and to send MQTT keepalive pings.
  1074. * If the application is calling MQTTClient_receive() regularly, then it is
  1075. * not necessary to call this function.
  1076. */
  1077. DLLExport void MQTTClient_yield(void);
  1078. /**
  1079. * This function performs a synchronous receive of incoming messages. It should
  1080. * be used only when the client application has not set callback methods to
  1081. * support asynchronous receipt of messages (see @ref async and
  1082. * MQTTClient_setCallbacks()). Using this function allows a single-threaded
  1083. * client subscriber application to be written. When called, this function
  1084. * blocks until the next message arrives or the specified timeout expires
  1085. *(see also MQTTClient_yield()).
  1086. *
  1087. * <b>Important note:</b> The application must free() the memory allocated
  1088. * to the topic and the message when processing is complete (see
  1089. * MQTTClient_freeMessage()).
  1090. * @param handle A valid client handle from a successful call to
  1091. * MQTTClient_create().
  1092. * @param topicName The address of a pointer to a topic. This function
  1093. * allocates the memory for the topic and returns it to the application
  1094. * by setting <i>topicName</i> to point to the topic.
  1095. * @param topicLen The length of the topic. If the return code from this
  1096. * function is ::MQTTCLIENT_TOPICNAME_TRUNCATED, the topic contains embedded
  1097. * NULL characters and the full topic should be retrieved by using
  1098. * <i>topicLen</i>.
  1099. * @param message The address of a pointer to the received message. This
  1100. * function allocates the memory for the message and returns it to the
  1101. * application by setting <i>message</i> to point to the received message.
  1102. * The pointer is set to NULL if the timeout expires.
  1103. * @param timeout The length of time to wait for a message in milliseconds.
  1104. * @return ::MQTTCLIENT_SUCCESS or ::MQTTCLIENT_TOPICNAME_TRUNCATED if a
  1105. * message is received. ::MQTTCLIENT_SUCCESS can also indicate that the
  1106. * timeout expired, in which case <i>message</i> is NULL. An error code is
  1107. * returned if there was a problem trying to receive a message.
  1108. */
  1109. DLLExport int MQTTClient_receive(MQTTClient handle, char** topicName, int* topicLen, MQTTClient_message** message,
  1110. unsigned long timeout);
  1111. /**
  1112. * This function frees memory allocated to an MQTT message, including the
  1113. * additional memory allocated to the message payload. The client application
  1114. * calls this function when the message has been fully processed. <b>Important
  1115. * note:</b> This function does not free the memory allocated to a message
  1116. * topic string. It is the responsibility of the client application to free
  1117. * this memory using the MQTTClient_free() library function.
  1118. * @param msg The address of a pointer to the ::MQTTClient_message structure
  1119. * to be freed.
  1120. */
  1121. DLLExport void MQTTClient_freeMessage(MQTTClient_message** msg);
  1122. /**
  1123. * This function frees memory allocated by the MQTT C client library, especially the
  1124. * topic name. This is needed on Windows when the client libary and application
  1125. * program have been compiled with different versions of the C compiler. It is
  1126. * thus good policy to always use this function when freeing any MQTT C client-
  1127. * allocated memory.
  1128. * @param ptr The pointer to the client library storage to be freed.
  1129. */
  1130. DLLExport void MQTTClient_free(void* ptr);
  1131. /**
  1132. * This function frees the memory allocated to an MQTT client (see
  1133. * MQTTClient_create()). It should be called when the client is no longer
  1134. * required.
  1135. * @param handle A pointer to the handle referring to the ::MQTTClient
  1136. * structure to be freed.
  1137. */
  1138. DLLExport void MQTTClient_destroy(MQTTClient* handle);
  1139. enum MQTTCLIENT_TRACE_LEVELS
  1140. {
  1141. MQTTCLIENT_TRACE_MAXIMUM = 1,
  1142. MQTTCLIENT_TRACE_MEDIUM,
  1143. MQTTCLIENT_TRACE_MINIMUM,
  1144. MQTTCLIENT_TRACE_PROTOCOL,
  1145. MQTTCLIENT_TRACE_ERROR,
  1146. MQTTCLIENT_TRACE_SEVERE,
  1147. MQTTCLIENT_TRACE_FATAL,
  1148. };
  1149. /**
  1150. * This function sets the level of trace information which will be
  1151. * returned in the trace callback.
  1152. * @param level the trace level required
  1153. */
  1154. DLLExport void MQTTClient_setTraceLevel(enum MQTTCLIENT_TRACE_LEVELS level);
  1155. /**
  1156. * This is a callback function prototype which must be implemented if you want
  1157. * to receive trace information.
  1158. * @param level the trace level of the message returned
  1159. * @param message the trace message. This is a pointer to a static buffer which
  1160. * will be overwritten on each call. You must copy the data if you want to keep
  1161. * it for later.
  1162. */
  1163. typedef void MQTTClient_traceCallback(enum MQTTCLIENT_TRACE_LEVELS level, char* message);
  1164. /**
  1165. * This function sets the trace callback if needed. If set to NULL,
  1166. * no trace information will be returned. The default trace level is
  1167. * MQTTASYNC_TRACE_MINIMUM.
  1168. * @param callback a pointer to the function which will handle the trace information
  1169. */
  1170. DLLExport void MQTTClient_setTraceCallback(MQTTClient_traceCallback* callback);
  1171. /**
  1172. * Returns a pointer to the string representation of the error or NULL.
  1173. *
  1174. * Do not free after use. Returns NULL if the error code is unknown.
  1175. */
  1176. DLLExport const char* MQTTClient_strerror(int code);
  1177. #ifdef __cplusplus
  1178. }
  1179. #endif
  1180. #endif
  1181. /**
  1182. * @cond MQTTClient_main
  1183. * @page async Asynchronous vs synchronous client applications
  1184. * The client library supports two modes of operation. These are referred to
  1185. * as <b>synchronous</b> and <b>asynchronous</b> modes. If your application
  1186. * calls MQTTClient_setCallbacks(), this puts the client into asynchronous
  1187. * mode, otherwise it operates in synchronous mode.
  1188. *
  1189. * In synchronous mode, the client application runs on a single thread.
  1190. * Messages are published using the MQTTClient_publish() and
  1191. * MQTTClient_publishMessage() functions. To determine that a QoS1 or QoS2
  1192. * (see @ref qos) message has been successfully delivered, the application
  1193. * must call the MQTTClient_waitForCompletion() function. An example showing
  1194. * synchronous publication is shown in @ref pubsync. Receiving messages in
  1195. * synchronous mode uses the MQTTClient_receive() function. Client applications
  1196. * must call either MQTTClient_receive() or MQTTClient_yield() relatively
  1197. * frequently in order to allow processing of acknowledgements and the MQTT
  1198. * "pings" that keep the network connection to the server alive.
  1199. *
  1200. * In asynchronous mode, the client application runs on several threads. The
  1201. * main program calls functions in the client library to publish and subscribe,
  1202. * just as for the synchronous mode. Processing of handshaking and maintaining
  1203. * the network connection is performed in the background, however.
  1204. * Notifications of status and message reception are provided to the client
  1205. * application using callbacks registered with the library by the call to
  1206. * MQTTClient_setCallbacks() (see MQTTClient_messageArrived(),
  1207. * MQTTClient_connectionLost() and MQTTClient_deliveryComplete()).
  1208. * This API is not thread safe however - it is not possible to call it from multiple
  1209. * threads without synchronization. You can use the MQTTAsync API for that.
  1210. *
  1211. * @page wildcard Subscription wildcards
  1212. * Every MQTT message includes a topic that classifies it. MQTT servers use
  1213. * topics to determine which subscribers should receive messages published to
  1214. * the server.
  1215. *
  1216. * Consider the server receiving messages from several environmental sensors.
  1217. * Each sensor publishes its measurement data as a message with an associated
  1218. * topic. Subscribing applications need to know which sensor originally
  1219. * published each received message. A unique topic is thus used to identify
  1220. * each sensor and measurement type. Topics such as SENSOR1TEMP,
  1221. * SENSOR1HUMIDITY, SENSOR2TEMP and so on achieve this but are not very
  1222. * flexible. If additional sensors are added to the system at a later date,
  1223. * subscribing applications must be modified to receive them.
  1224. *
  1225. * To provide more flexibility, MQTT supports a hierarchical topic namespace.
  1226. * This allows application designers to organize topics to simplify their
  1227. * management. Levels in the hierarchy are delimited by the '/' character,
  1228. * such as SENSOR/1/HUMIDITY. Publishers and subscribers use these
  1229. * hierarchical topics as already described.
  1230. *
  1231. * For subscriptions, two wildcard characters are supported:
  1232. * <ul>
  1233. * <li>A '#' character represents a complete sub-tree of the hierarchy and
  1234. * thus must be the last character in a subscription topic string, such as
  1235. * SENSOR/#. This will match any topic starting with SENSOR/, such as
  1236. * SENSOR/1/TEMP and SENSOR/2/HUMIDITY.</li>
  1237. * <li> A '+' character represents a single level of the hierarchy and is
  1238. * used between delimiters. For example, SENSOR/+/TEMP will match
  1239. * SENSOR/1/TEMP and SENSOR/2/TEMP.</li>
  1240. * </ul>
  1241. * Publishers are not allowed to use the wildcard characters in their topic
  1242. * names.
  1243. *
  1244. * Deciding on your topic hierarchy is an important step in your system design.
  1245. *
  1246. * @page qos Quality of service
  1247. * The MQTT protocol provides three qualities of service for delivering
  1248. * messages between clients and servers: "at most once", "at least once" and
  1249. * "exactly once".
  1250. *
  1251. * Quality of service (QoS) is an attribute of an individual message being
  1252. * published. An application sets the QoS for a specific message by setting the
  1253. * MQTTClient_message.qos field to the required value.
  1254. *
  1255. * A subscribing client can set the maximum quality of service a server uses
  1256. * to send messages that match the client subscriptions. The
  1257. * MQTTClient_subscribe() and MQTTClient_subscribeMany() functions set this
  1258. * maximum. The QoS of a message forwarded to a subscriber thus might be
  1259. * different to the QoS given to the message by the original publisher.
  1260. * The lower of the two values is used to forward a message.
  1261. *
  1262. * The three levels are:
  1263. *
  1264. * <b>QoS0, At most once:</b> The message is delivered at most once, or it
  1265. * may not be delivered at all. Its delivery across the network is not
  1266. * acknowledged. The message is not stored. The message could be lost if the
  1267. * client is disconnected, or if the server fails. QoS0 is the fastest mode of
  1268. * transfer. It is sometimes called "fire and forget".
  1269. *
  1270. * The MQTT protocol does not require servers to forward publications at QoS0
  1271. * to a client. If the client is disconnected at the time the server receives
  1272. * the publication, the publication might be discarded, depending on the
  1273. * server implementation.
  1274. *
  1275. * <b>QoS1, At least once:</b> The message is always delivered at least once.
  1276. * It might be delivered multiple times if there is a failure before an
  1277. * acknowledgment is received by the sender. The message must be stored
  1278. * locally at the sender, until the sender receives confirmation that the
  1279. * message has been published by the receiver. The message is stored in case
  1280. * the message must be sent again.
  1281. *
  1282. * <b>QoS2, Exactly once:</b> The message is always delivered exactly once.
  1283. * The message must be stored locally at the sender, until the sender receives
  1284. * confirmation that the message has been published by the receiver. The
  1285. * message is stored in case the message must be sent again. QoS2 is the
  1286. * safest, but slowest mode of transfer. A more sophisticated handshaking
  1287. * and acknowledgement sequence is used than for QoS1 to ensure no duplication
  1288. * of messages occurs.
  1289. * @page pubsync Synchronous publication example
  1290. @code
  1291. #include <stdio.h>
  1292. #include <stdlib.h>
  1293. #include <string.h>
  1294. #include "MQTTClient.h"
  1295. #define ADDRESS "tcp://localhost:1883"
  1296. #define CLIENTID "ExampleClientPub"
  1297. #define TOPIC "MQTT Examples"
  1298. #define PAYLOAD "Hello World!"
  1299. #define QOS 1
  1300. #define TIMEOUT 10000L
  1301. int main(int argc, char* argv[])
  1302. {
  1303. MQTTClient client;
  1304. MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  1305. MQTTClient_message pubmsg = MQTTClient_message_initializer;
  1306. MQTTClient_deliveryToken token;
  1307. int rc;
  1308. MQTTClient_create(&client, ADDRESS, CLIENTID,
  1309. MQTTCLIENT_PERSISTENCE_NONE, NULL);
  1310. conn_opts.keepAliveInterval = 20;
  1311. conn_opts.cleansession = 1;
  1312. if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  1313. {
  1314. printf("Failed to connect, return code %d\n", rc);
  1315. exit(EXIT_FAILURE);
  1316. }
  1317. pubmsg.payload = PAYLOAD;
  1318. pubmsg.payloadlen = strlen(PAYLOAD);
  1319. pubmsg.qos = QOS;
  1320. pubmsg.retained = 0;
  1321. MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
  1322. printf("Waiting for up to %d seconds for publication of %s\n"
  1323. "on topic %s for client with ClientID: %s\n",
  1324. (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
  1325. rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
  1326. printf("Message with delivery token %d delivered\n", token);
  1327. MQTTClient_disconnect(client, 10000);
  1328. MQTTClient_destroy(&client);
  1329. return rc;
  1330. }
  1331. * @endcode
  1332. *
  1333. * @page pubasync Asynchronous publication example
  1334. @code{.c}
  1335. #include <stdio.h>
  1336. #include <stdlib.h>
  1337. #include <string.h>
  1338. #include "MQTTClient.h"
  1339. #define ADDRESS "tcp://localhost:1883"
  1340. #define CLIENTID "ExampleClientPub"
  1341. #define TOPIC "MQTT Examples"
  1342. #define PAYLOAD "Hello World!"
  1343. #define QOS 1
  1344. #define TIMEOUT 10000L
  1345. volatile MQTTClient_deliveryToken deliveredtoken;
  1346. void delivered(void *context, MQTTClient_deliveryToken dt)
  1347. {
  1348. printf("Message with token value %d delivery confirmed\n", dt);
  1349. deliveredtoken = dt;
  1350. }
  1351. int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
  1352. {
  1353. int i;
  1354. char* payloadptr;
  1355. printf("Message arrived\n");
  1356. printf(" topic: %s\n", topicName);
  1357. printf(" message: ");
  1358. payloadptr = message->payload;
  1359. for(i=0; i<message->payloadlen; i++)
  1360. {
  1361. putchar(*payloadptr++);
  1362. }
  1363. putchar('\n');
  1364. MQTTClient_freeMessage(&message);
  1365. MQTTClient_free(topicName);
  1366. return 1;
  1367. }
  1368. void connlost(void *context, char *cause)
  1369. {
  1370. printf("\nConnection lost\n");
  1371. printf(" cause: %s\n", cause);
  1372. }
  1373. int main(int argc, char* argv[])
  1374. {
  1375. MQTTClient client;
  1376. MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  1377. MQTTClient_message pubmsg = MQTTClient_message_initializer;
  1378. MQTTClient_deliveryToken token;
  1379. int rc;
  1380. MQTTClient_create(&client, ADDRESS, CLIENTID,
  1381. MQTTCLIENT_PERSISTENCE_NONE, NULL);
  1382. conn_opts.keepAliveInterval = 20;
  1383. conn_opts.cleansession = 1;
  1384. MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
  1385. if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  1386. {
  1387. printf("Failed to connect, return code %d\n", rc);
  1388. exit(EXIT_FAILURE);
  1389. }
  1390. pubmsg.payload = PAYLOAD;
  1391. pubmsg.payloadlen = strlen(PAYLOAD);
  1392. pubmsg.qos = QOS;
  1393. pubmsg.retained = 0;
  1394. deliveredtoken = 0;
  1395. MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
  1396. printf("Waiting for publication of %s\n"
  1397. "on topic %s for client with ClientID: %s\n",
  1398. PAYLOAD, TOPIC, CLIENTID);
  1399. while(deliveredtoken != token);
  1400. MQTTClient_disconnect(client, 10000);
  1401. MQTTClient_destroy(&client);
  1402. return rc;
  1403. }
  1404. * @endcode
  1405. * @page subasync Asynchronous subscription example
  1406. @code
  1407. #include <stdio.h>
  1408. #include <stdlib.h>
  1409. #include <string.h>
  1410. #include "MQTTClient.h"
  1411. #define ADDRESS "tcp://localhost:1883"
  1412. #define CLIENTID "ExampleClientSub"
  1413. #define TOPIC "MQTT Examples"
  1414. #define PAYLOAD "Hello World!"
  1415. #define QOS 1
  1416. #define TIMEOUT 10000L
  1417. volatile MQTTClient_deliveryToken deliveredtoken;
  1418. void delivered(void *context, MQTTClient_deliveryToken dt)
  1419. {
  1420. printf("Message with token value %d delivery confirmed\n", dt);
  1421. deliveredtoken = dt;
  1422. }
  1423. int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
  1424. {
  1425. int i;
  1426. char* payloadptr;
  1427. printf("Message arrived\n");
  1428. printf(" topic: %s\n", topicName);
  1429. printf(" message: ");
  1430. payloadptr = message->payload;
  1431. for(i=0; i<message->payloadlen; i++)
  1432. {
  1433. putchar(*payloadptr++);
  1434. }
  1435. putchar('\n');
  1436. MQTTClient_freeMessage(&message);
  1437. MQTTClient_free(topicName);
  1438. return 1;
  1439. }
  1440. void connlost(void *context, char *cause)
  1441. {
  1442. printf("\nConnection lost\n");
  1443. printf(" cause: %s\n", cause);
  1444. }
  1445. int main(int argc, char* argv[])
  1446. {
  1447. MQTTClient client;
  1448. MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  1449. int rc;
  1450. int ch;
  1451. MQTTClient_create(&client, ADDRESS, CLIENTID,
  1452. MQTTCLIENT_PERSISTENCE_NONE, NULL);
  1453. conn_opts.keepAliveInterval = 20;
  1454. conn_opts.cleansession = 1;
  1455. MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
  1456. if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  1457. {
  1458. printf("Failed to connect, return code %d\n", rc);
  1459. exit(EXIT_FAILURE);
  1460. }
  1461. printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
  1462. "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
  1463. MQTTClient_subscribe(client, TOPIC, QOS);
  1464. do
  1465. {
  1466. ch = getchar();
  1467. } while(ch!='Q' && ch != 'q');
  1468. MQTTClient_disconnect(client, 10000);
  1469. MQTTClient_destroy(&client);
  1470. return rc;
  1471. }
  1472. * @endcode
  1473. * @page tracing Tracing
  1474. *
  1475. * Runtime tracing is controlled by environment variables.
  1476. *
  1477. * Tracing is switched on by setting MQTT_C_CLIENT_TRACE. A value of ON, or stdout, prints to
  1478. * stdout, any other value is interpreted as a file name to use.
  1479. *
  1480. * The amount of trace detail is controlled with the MQTT_C_CLIENT_TRACE_LEVEL environment
  1481. * variable - valid values are ERROR, PROTOCOL, MINIMUM, MEDIUM and MAXIMUM
  1482. * (from least to most verbose).
  1483. *
  1484. * The variable MQTT_C_CLIENT_TRACE_MAX_LINES limits the number of lines of trace that are output
  1485. * to a file. Two files are used at most, when they are full, the last one is overwritten with the
  1486. * new trace entries. The default size is 1000 lines.
  1487. *
  1488. * ### MQTT Packet Tracing
  1489. *
  1490. * A feature that can be very useful is printing the MQTT packets that are sent and received. To
  1491. * achieve this, use the following environment variable settings:
  1492. * @code
  1493. MQTT_C_CLIENT_TRACE=ON
  1494. MQTT_C_CLIENT_TRACE_LEVEL=PROTOCOL
  1495. * @endcode
  1496. * The output you should see looks like this:
  1497. * @code
  1498. 20130528 155936.813 3 stdout-subscriber -> CONNECT cleansession: 1 (0)
  1499. 20130528 155936.813 3 stdout-subscriber <- CONNACK rc: 0
  1500. 20130528 155936.813 3 stdout-subscriber -> SUBSCRIBE msgid: 1 (0)
  1501. 20130528 155936.813 3 stdout-subscriber <- SUBACK msgid: 1
  1502. 20130528 155941.818 3 stdout-subscriber -> DISCONNECT (0)
  1503. * @endcode
  1504. * where the fields are:
  1505. * 1. date
  1506. * 2. time
  1507. * 3. socket number
  1508. * 4. client id
  1509. * 5. direction (-> from client to server, <- from server to client)
  1510. * 6. packet details
  1511. *
  1512. * ### Default Level Tracing
  1513. *
  1514. * This is an extract of a default level trace of a call to connect:
  1515. * @code
  1516. 19700101 010000.000 (1152206656) (0)> MQTTClient_connect:893
  1517. 19700101 010000.000 (1152206656) (1)> MQTTClient_connectURI:716
  1518. 20130528 160447.479 Connecting to serverURI localhost:1883
  1519. 20130528 160447.479 (1152206656) (2)> MQTTProtocol_connect:98
  1520. 20130528 160447.479 (1152206656) (3)> MQTTProtocol_addressPort:48
  1521. 20130528 160447.479 (1152206656) (3)< MQTTProtocol_addressPort:73
  1522. 20130528 160447.479 (1152206656) (3)> Socket_new:599
  1523. 20130528 160447.479 New socket 4 for localhost, port 1883
  1524. 20130528 160447.479 (1152206656) (4)> Socket_addSocket:163
  1525. 20130528 160447.479 (1152206656) (5)> Socket_setnonblocking:73
  1526. 20130528 160447.479 (1152206656) (5)< Socket_setnonblocking:78 (0)
  1527. 20130528 160447.479 (1152206656) (4)< Socket_addSocket:176 (0)
  1528. 20130528 160447.479 (1152206656) (4)> Socket_error:95
  1529. 20130528 160447.479 (1152206656) (4)< Socket_error:104 (115)
  1530. 20130528 160447.479 Connect pending
  1531. 20130528 160447.479 (1152206656) (3)< Socket_new:683 (115)
  1532. 20130528 160447.479 (1152206656) (2)< MQTTProtocol_connect:131 (115)
  1533. * @endcode
  1534. * where the fields are:
  1535. * 1. date
  1536. * 2. time
  1537. * 3. thread id
  1538. * 4. function nesting level
  1539. * 5. function entry (>) or exit (<)
  1540. * 6. function name : line of source code file
  1541. * 7. return value (if there is one)
  1542. *
  1543. * ### Memory Allocation Tracing
  1544. *
  1545. * Setting the trace level to maximum causes memory allocations and frees to be traced along with
  1546. * the default trace entries, with messages like the following:
  1547. * @code
  1548. 20130528 161819.657 Allocating 16 bytes in heap at file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c line 177 ptr 0x179f930
  1549. 20130528 161819.657 Freeing 16 bytes in heap at file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c line 201, heap use now 896 bytes
  1550. * @endcode
  1551. * When the last MQTT client object is destroyed, if the trace is being recorded
  1552. * and all memory allocated by the client library has not been freed, an error message will be
  1553. * written to the trace. This can help with fixing memory leaks. The message will look like this:
  1554. * @code
  1555. 20130528 163909.208 Some memory not freed at shutdown, possible memory leak
  1556. 20130528 163909.208 Heap scan start, total 880 bytes
  1557. 20130528 163909.208 Heap element size 32, line 354, file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c, ptr 0x260cb00
  1558. 20130528 163909.208 Content
  1559. 20130528 163909.209 Heap scan end
  1560. * @endcode
  1561. * @endcond
  1562. */