MQTTClient.h 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  1. /*******************************************************************************
  2. * Copyright (c) 2009, 2017 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, 2017
  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(__cplusplus)
  105. extern "C" {
  106. #endif
  107. #if !defined(MQTTCLIENT_H)
  108. #define MQTTCLIENT_H
  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. #if !defined(NO_PERSISTENCE)
  121. #include "MQTTClientPersistence.h"
  122. #endif
  123. /**
  124. * Return code: No error. Indicates successful completion of an MQTT client
  125. * operation.
  126. */
  127. #define MQTTCLIENT_SUCCESS 0
  128. /**
  129. * Return code: A generic error code indicating the failure of an MQTT client
  130. * operation.
  131. */
  132. #define MQTTCLIENT_FAILURE -1
  133. /* error code -2 is MQTTCLIENT_PERSISTENCE_ERROR */
  134. /**
  135. * Return code: The client is disconnected.
  136. */
  137. #define MQTTCLIENT_DISCONNECTED -3
  138. /**
  139. * Return code: The maximum number of messages allowed to be simultaneously
  140. * in-flight has been reached.
  141. */
  142. #define MQTTCLIENT_MAX_MESSAGES_INFLIGHT -4
  143. /**
  144. * Return code: An invalid UTF-8 string has been detected.
  145. */
  146. #define MQTTCLIENT_BAD_UTF8_STRING -5
  147. /**
  148. * Return code: A NULL parameter has been supplied when this is invalid.
  149. */
  150. #define MQTTCLIENT_NULL_PARAMETER -6
  151. /**
  152. * Return code: The topic has been truncated (the topic string includes
  153. * embedded NULL characters). String functions will not access the full topic.
  154. * Use the topic length value to access the full topic.
  155. */
  156. #define MQTTCLIENT_TOPICNAME_TRUNCATED -7
  157. /**
  158. * Return code: A structure parameter does not have the correct eyecatcher
  159. * and version number.
  160. */
  161. #define MQTTCLIENT_BAD_STRUCTURE -8
  162. /**
  163. * Return code: A QoS value that falls outside of the acceptable range (0,1,2)
  164. */
  165. #define MQTTCLIENT_BAD_QOS -9
  166. /**
  167. * Return code: Attempting SSL connection using non-SSL version of library
  168. */
  169. #define MQTTCLIENT_SSL_NOT_SUPPORTED -10
  170. /**
  171. * Default MQTT version to connect with. Use 3.1.1 then fall back to 3.1
  172. */
  173. #define MQTTVERSION_DEFAULT 0
  174. /**
  175. * MQTT version to connect with: 3.1
  176. */
  177. #define MQTTVERSION_3_1 3
  178. /**
  179. * MQTT version to connect with: 3.1.1
  180. */
  181. #define MQTTVERSION_3_1_1 4
  182. /**
  183. * Bad return code from subscribe, as defined in the 3.1.1 specification
  184. */
  185. #define MQTT_BAD_SUBSCRIBE 0x80
  186. /**
  187. * Initialization options
  188. */
  189. typedef struct
  190. {
  191. /** The eyecatcher for this structure. Must be MQTG. */
  192. char struct_id[4];
  193. /** The version number of this structure. Must be 0 */
  194. int struct_version;
  195. /** 1 = we do openssl init, 0 = leave it to the application */
  196. int do_openssl_init;
  197. } MQTTClient_init_options;
  198. #define MQTTClient_init_options_initializer { {'M', 'Q', 'T', 'G'}, 0, 0 }
  199. /**
  200. * Global init of mqtt library. Call once on program start to set global behaviour.
  201. * do_openssl_init - if mqtt library should initialize OpenSSL (1) or rely on the caller to do it before using the library (0)
  202. */
  203. DLLExport void MQTTClient_global_init(MQTTClient_init_options* inits);
  204. /**
  205. * A handle representing an MQTT client. A valid client handle is available
  206. * following a successful call to MQTTClient_create().
  207. */
  208. typedef void* MQTTClient;
  209. /**
  210. * A value representing an MQTT message. A delivery token is returned to the
  211. * client application when a message is published. The token can then be used to
  212. * check that the message was successfully delivered to its destination (see
  213. * MQTTClient_publish(),
  214. * MQTTClient_publishMessage(),
  215. * MQTTClient_deliveryComplete(),
  216. * MQTTClient_waitForCompletion() and
  217. * MQTTClient_getPendingDeliveryTokens()).
  218. */
  219. typedef int MQTTClient_deliveryToken;
  220. typedef int MQTTClient_token;
  221. /**
  222. * A structure representing the payload and attributes of an MQTT message. The
  223. * message topic is not part of this structure (see MQTTClient_publishMessage(),
  224. * MQTTClient_publish(), MQTTClient_receive(), MQTTClient_freeMessage()
  225. * and MQTTClient_messageArrived()).
  226. */
  227. typedef struct
  228. {
  229. /** The eyecatcher for this structure. must be MQTM. */
  230. char struct_id[4];
  231. /** The version number of this structure. Must be 0 */
  232. int struct_version;
  233. /** The length of the MQTT message payload in bytes. */
  234. int payloadlen;
  235. /** A pointer to the payload of the MQTT message. */
  236. void* payload;
  237. /**
  238. * The quality of service (QoS) assigned to the message.
  239. * There are three levels of QoS:
  240. * <DL>
  241. * <DT><B>QoS0</B></DT>
  242. * <DD>Fire and forget - the message may not be delivered</DD>
  243. * <DT><B>QoS1</B></DT>
  244. * <DD>At least once - the message will be delivered, but may be
  245. * delivered more than once in some circumstances.</DD>
  246. * <DT><B>QoS2</B></DT>
  247. * <DD>Once and one only - the message will be delivered exactly once.</DD>
  248. * </DL>
  249. */
  250. int qos;
  251. /**
  252. * The retained flag serves two purposes depending on whether the message
  253. * it is associated with is being published or received.
  254. *
  255. * <b>retained = true</b><br>
  256. * For messages being published, a true setting indicates that the MQTT
  257. * server should retain a copy of the message. The message will then be
  258. * transmitted to new subscribers to a topic that matches the message topic.
  259. * For subscribers registering a new subscription, the flag being true
  260. * indicates that the received message is not a new one, but one that has
  261. * been retained by the MQTT server.
  262. *
  263. * <b>retained = false</b> <br>
  264. * For publishers, this ndicates that this message should not be retained
  265. * by the MQTT server. For subscribers, a false setting indicates this is
  266. * a normal message, received as a result of it being published to the
  267. * server.
  268. */
  269. int retained;
  270. /**
  271. * The dup flag indicates whether or not this message is a duplicate.
  272. * It is only meaningful when receiving QoS1 messages. When true, the
  273. * client application should take appropriate action to deal with the
  274. * duplicate message.
  275. */
  276. int dup;
  277. /** The message identifier is normally reserved for internal use by the
  278. * MQTT client and server.
  279. */
  280. int msgid;
  281. } MQTTClient_message;
  282. #define MQTTClient_message_initializer { {'M', 'Q', 'T', 'M'}, 0, 0, NULL, 0, 0, 0, 0 }
  283. /**
  284. * This is a callback function. The client application
  285. * must provide an implementation of this function to enable asynchronous
  286. * receipt of messages. The function is registered with the client library by
  287. * passing it as an argument to MQTTClient_setCallbacks(). It is
  288. * called by the client library when a new message that matches a client
  289. * subscription has been received from the server. This function is executed on
  290. * a separate thread to the one on which the client application is running.
  291. * @param context A pointer to the <i>context</i> value originally passed to
  292. * MQTTClient_setCallbacks(), which contains any application-specific context.
  293. * @param topicName The topic associated with the received message.
  294. * @param topicLen The length of the topic if there are one
  295. * more NULL characters embedded in <i>topicName</i>, otherwise <i>topicLen</i>
  296. * is 0. If <i>topicLen</i> is 0, the value returned by <i>strlen(topicName)</i>
  297. * can be trusted. If <i>topicLen</i> is greater than 0, the full topic name
  298. * can be retrieved by accessing <i>topicName</i> as a byte array of length
  299. * <i>topicLen</i>.
  300. * @param message The MQTTClient_message structure for the received message.
  301. * This structure contains the message payload and attributes.
  302. * @return This function must return a boolean value indicating whether or not
  303. * the message has been safely received by the client application. Returning
  304. * true indicates that the message has been successfully handled.
  305. * Returning false indicates that there was a problem. In this
  306. * case, the client library will reinvoke MQTTClient_messageArrived() to
  307. * attempt to deliver the message to the application again.
  308. */
  309. typedef int MQTTClient_messageArrived(void* context, char* topicName, int topicLen, MQTTClient_message* message);
  310. /**
  311. * This is a callback function. The client application
  312. * must provide an implementation of this function to enable asynchronous
  313. * notification of delivery of messages. The function is registered with the
  314. * client library by passing it as an argument to MQTTClient_setCallbacks().
  315. * It is called by the client library after the client application has
  316. * published a message to the server. It indicates that the necessary
  317. * handshaking and acknowledgements for the requested quality of service (see
  318. * MQTTClient_message.qos) have been completed. This function is executed on a
  319. * separate thread to the one on which the client application is running.
  320. * <b>Note:</b>MQTTClient_deliveryComplete() is not called when messages are
  321. * published at QoS0.
  322. * @param context A pointer to the <i>context</i> value originally passed to
  323. * MQTTClient_setCallbacks(), which contains any application-specific context.
  324. * @param dt The ::MQTTClient_deliveryToken associated with
  325. * the published message. Applications can check that all messages have been
  326. * correctly published by matching the delivery tokens returned from calls to
  327. * MQTTClient_publish() and MQTTClient_publishMessage() with the tokens passed
  328. * to this callback.
  329. */
  330. typedef void MQTTClient_deliveryComplete(void* context, MQTTClient_deliveryToken dt);
  331. /**
  332. * This is a callback function. The client application
  333. * must provide an implementation of this function to enable asynchronous
  334. * notification of the loss of connection to the server. The function is
  335. * registered with the client library by passing it as an argument to
  336. * MQTTClient_setCallbacks(). It is called by the client library if the client
  337. * loses its connection to the server. The client application must take
  338. * appropriate action, such as trying to reconnect or reporting the problem.
  339. * This function is executed on a separate thread to the one on which the
  340. * client application is running.
  341. * @param context A pointer to the <i>context</i> value originally passed to
  342. * MQTTClient_setCallbacks(), which contains any application-specific context.
  343. * @param cause The reason for the disconnection.
  344. * Currently, <i>cause</i> is always set to NULL.
  345. */
  346. typedef void MQTTClient_connectionLost(void* context, char* cause);
  347. /**
  348. * This function sets the callback functions for a specific client.
  349. * If your client application doesn't use a particular callback, set the
  350. * relevant parameter to NULL. Calling MQTTClient_setCallbacks() puts the
  351. * client into multi-threaded mode. Any necessary message acknowledgements and
  352. * status communications are handled in the background without any intervention
  353. * from the client application. See @ref async for more information.
  354. *
  355. * <b>Note:</b> The MQTT client must be disconnected when this function is
  356. * called.
  357. * @param handle A valid client handle from a successful call to
  358. * MQTTClient_create().
  359. * @param context A pointer to any application-specific context. The
  360. * the <i>context</i> pointer is passed to each of the callback functions to
  361. * provide access to the context information in the callback.
  362. * @param cl A pointer to an MQTTClient_connectionLost() callback
  363. * function. You can set this to NULL if your application doesn't handle
  364. * disconnections.
  365. * @param ma A pointer to an MQTTClient_messageArrived() callback
  366. * function. This callback function must be specified when you call
  367. * MQTTClient_setCallbacks().
  368. * @param dc A pointer to an MQTTClient_deliveryComplete() callback
  369. * function. You can set this to NULL if your application publishes
  370. * synchronously or if you do not want to check for successful delivery.
  371. * @return ::MQTTCLIENT_SUCCESS if the callbacks were correctly set,
  372. * ::MQTTCLIENT_FAILURE if an error occurred.
  373. */
  374. DLLExport int MQTTClient_setCallbacks(MQTTClient handle, void* context, MQTTClient_connectionLost* cl,
  375. MQTTClient_messageArrived* ma, MQTTClient_deliveryComplete* dc);
  376. /**
  377. * This function creates an MQTT client ready for connection to the
  378. * specified server and using the specified persistent storage (see
  379. * MQTTClient_persistence). See also MQTTClient_destroy().
  380. * @param handle A pointer to an ::MQTTClient handle. The handle is
  381. * populated with a valid client reference following a successful return from
  382. * this function.
  383. * @param serverURI A null-terminated string specifying the server to
  384. * which the client will connect. It takes the form <i>protocol://host:port</i>.
  385. * Currently, <i>protocol</i> must be <i>tcp</i> or <i>ssl</i>.
  386. * For <i>host</i>, you can
  387. * specify either an IP address or a host name. For instance, to connect to
  388. * a server running on the local machines with the default MQTT port, specify
  389. * <i>tcp://localhost:1883</i>.
  390. * @param clientId The client identifier passed to the server when the
  391. * client connects to it. It is a null-terminated UTF-8 encoded string.
  392. * @param persistence_type The type of persistence to be used by the client:
  393. * <br>
  394. * ::MQTTCLIENT_PERSISTENCE_NONE: Use in-memory persistence. If the device or
  395. * system on which the client is running fails or is switched off, the current
  396. * state of any in-flight messages is lost and some messages may not be
  397. * delivered even at QoS1 and QoS2.
  398. * <br>
  399. * ::MQTTCLIENT_PERSISTENCE_DEFAULT: Use the default (file system-based)
  400. * persistence mechanism. Status about in-flight messages is held in persistent
  401. * storage and provides some protection against message loss in the case of
  402. * unexpected failure.
  403. * <br>
  404. * ::MQTTCLIENT_PERSISTENCE_USER: Use an application-specific persistence
  405. * implementation. Using this type of persistence gives control of the
  406. * persistence mechanism to the application. The application has to implement
  407. * the MQTTClient_persistence interface.
  408. * @param persistence_context If the application uses
  409. * ::MQTTCLIENT_PERSISTENCE_NONE persistence, this argument is unused and should
  410. * be set to NULL. For ::MQTTCLIENT_PERSISTENCE_DEFAULT persistence, it
  411. * should be set to the location of the persistence directory (if set
  412. * to NULL, the persistence directory used is the working directory).
  413. * Applications that use ::MQTTCLIENT_PERSISTENCE_USER persistence set this
  414. * argument to point to a valid MQTTClient_persistence structure.
  415. * @return ::MQTTCLIENT_SUCCESS if the client is successfully created, otherwise
  416. * an error code is returned.
  417. */
  418. DLLExport int MQTTClient_create(MQTTClient* handle, const char* serverURI, const char* clientId,
  419. int persistence_type, void* persistence_context);
  420. /**
  421. * MQTTClient_willOptions defines the MQTT "Last Will and Testament" (LWT) settings for
  422. * the client. In the event that a client unexpectedly loses its connection to
  423. * the server, the server publishes the LWT message to the LWT topic on
  424. * behalf of the client. This allows other clients (subscribed to the LWT topic)
  425. * to be made aware that the client has disconnected. To enable the LWT
  426. * function for a specific client, a valid pointer to an MQTTClient_willOptions
  427. * structure is passed in the MQTTClient_connectOptions structure used in the
  428. * MQTTClient_connect() call that connects the client to the server. The pointer
  429. * to MQTTClient_willOptions can be set to NULL if the LWT function is not
  430. * required.
  431. */
  432. typedef struct
  433. {
  434. /** The eyecatcher for this structure. must be MQTW. */
  435. char struct_id[4];
  436. /** The version number of this structure. Must be 0 or 1
  437. 0 means there is no binary payload option
  438. */
  439. int struct_version;
  440. /** The LWT topic to which the LWT message will be published. */
  441. const char* topicName;
  442. /** The LWT payload in string form. */
  443. const char* message;
  444. /**
  445. * The retained flag for the LWT message (see MQTTClient_message.retained).
  446. */
  447. int retained;
  448. /**
  449. * The quality of service setting for the LWT message (see
  450. * MQTTClient_message.qos and @ref qos).
  451. */
  452. int qos;
  453. /** The LWT payload in binary form. This is only checked and used if the message option is NULL */
  454. struct
  455. {
  456. int len; /**< binary payload length */
  457. const void* data; /**< binary payload data */
  458. } payload;
  459. } MQTTClient_willOptions;
  460. #define MQTTClient_willOptions_initializer { {'M', 'Q', 'T', 'W'}, 1, NULL, NULL, 0, 0, {0, NULL} }
  461. /**
  462. * MQTTClient_sslProperties defines the settings to establish an SSL/TLS connection using the
  463. * OpenSSL library. It covers the following scenarios:
  464. * - Server authentication: The client needs the digital certificate of the server. It is included
  465. * in a store containting trusted material (also known as "trust store").
  466. * - Mutual authentication: Both client and server are authenticated during the SSL handshake. In
  467. * addition to the digital certificate of the server in a trust store, the client will need its own
  468. * digital certificate and the private key used to sign its digital certificate stored in a "key store".
  469. * - Anonymous connection: Both client and server do not get authenticated and no credentials are needed
  470. * to establish an SSL connection. Note that this scenario is not fully secure since it is subject to
  471. * man-in-the-middle attacks.
  472. */
  473. typedef struct
  474. {
  475. /** The eyecatcher for this structure. Must be MQTS */
  476. char struct_id[4];
  477. /** The version number of this structure. Must be 0 */
  478. int struct_version;
  479. /** The file in PEM format containing the public digital certificates trusted by the client. */
  480. const char* trustStore;
  481. /** The file in PEM format containing the public certificate chain of the client. It may also include
  482. * the client's private key.
  483. */
  484. const char* keyStore;
  485. /** If not included in the sslKeyStore, this setting points to the file in PEM format containing
  486. * the client's private key.
  487. */
  488. const char* privateKey;
  489. /** The password to load the client's privateKey if encrypted. */
  490. const char* privateKeyPassword;
  491. /**
  492. * The list of cipher suites that the client will present to the server during the SSL handshake. For a
  493. * full explanation of the cipher list format, please see the OpenSSL on-line documentation:
  494. * http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT
  495. * If this setting is ommitted, its default value will be "ALL", that is, all the cipher suites -excluding
  496. * those offering no encryption- will be considered.
  497. * This setting can be used to set an SSL anonymous connection ("aNULL" string value, for instance).
  498. */
  499. const char* enabledCipherSuites;
  500. /** True/False option to enable verification of the server certificate **/
  501. int enableServerCertAuth;
  502. } MQTTClient_SSLOptions;
  503. #define MQTTClient_SSLOptions_initializer { {'M', 'Q', 'T', 'S'}, 0, NULL, NULL, NULL, NULL, NULL, 1 }
  504. /**
  505. * MQTTClient_connectOptions defines several settings that control the way the
  506. * client connects to an MQTT server.
  507. *
  508. * <b>Note:</b> Default values are not defined for members of
  509. * MQTTClient_connectOptions so it is good practice to specify all settings.
  510. * If the MQTTClient_connectOptions structure is defined as an automatic
  511. * variable, all members are set to random values and thus must be set by the
  512. * client application. If the MQTTClient_connectOptions structure is defined
  513. * as a static variable, initialization (in compliant compilers) sets all
  514. * values to 0 (NULL for pointers). A #keepAliveInterval setting of 0 prevents
  515. * correct operation of the client and so you <b>must</b> at least set a value
  516. * for #keepAliveInterval.
  517. */
  518. typedef struct
  519. {
  520. /** The eyecatcher for this structure. must be MQTC. */
  521. char struct_id[4];
  522. /** The version number of this structure. Must be 0, 1, 2, 3, 4 or 5.
  523. * 0 signifies no SSL options and no serverURIs
  524. * 1 signifies no serverURIs
  525. * 2 signifies no MQTTVersion
  526. * 3 signifies no returned values
  527. * 4 signifies no binary password option
  528. */
  529. int struct_version;
  530. /** The "keep alive" interval, measured in seconds, defines the maximum time
  531. * that should pass without communication between the client and the server
  532. * The client will ensure that at least one message travels across the
  533. * network within each keep alive period. In the absence of a data-related
  534. * message during the time period, the client sends a very small MQTT
  535. * "ping" message, which the server will acknowledge. The keep alive
  536. * interval enables the client to detect when the server is no longer
  537. * available without having to wait for the long TCP/IP timeout.
  538. */
  539. int keepAliveInterval;
  540. /**
  541. * This is a boolean value. The cleansession setting controls the behaviour
  542. * of both the client and the server at connection and disconnection time.
  543. * The client and server both maintain session state information. This
  544. * information is used to ensure "at least once" and "exactly once"
  545. * delivery, and "exactly once" receipt of messages. Session state also
  546. * includes subscriptions created by an MQTT client. You can choose to
  547. * maintain or discard state information between sessions.
  548. *
  549. * When cleansession is true, the state information is discarded at
  550. * connect and disconnect. Setting cleansession to false keeps the state
  551. * information. When you connect an MQTT client application with
  552. * MQTTClient_connect(), the client identifies the connection using the
  553. * client identifier and the address of the server. The server checks
  554. * whether session information for this client
  555. * has been saved from a previous connection to the server. If a previous
  556. * session still exists, and cleansession=true, then the previous session
  557. * information at the client and server is cleared. If cleansession=false,
  558. * the previous session is resumed. If no previous session exists, a new
  559. * session is started.
  560. */
  561. int cleansession;
  562. /**
  563. * This is a boolean value that controls how many messages can be in-flight
  564. * simultaneously. Setting <i>reliable</i> to true means that a published
  565. * message must be completed (acknowledgements received) before another
  566. * can be sent. Attempts to publish additional messages receive an
  567. * ::MQTTCLIENT_MAX_MESSAGES_INFLIGHT return code. Setting this flag to
  568. * false allows up to 10 messages to be in-flight. This can increase
  569. * overall throughput in some circumstances.
  570. */
  571. int reliable;
  572. /**
  573. * This is a pointer to an MQTTClient_willOptions structure. If your
  574. * application does not make use of the Last Will and Testament feature,
  575. * set this pointer to NULL.
  576. */
  577. MQTTClient_willOptions* will;
  578. /**
  579. * MQTT servers that support the MQTT v3.1.1 protocol provide authentication
  580. * and authorisation by user name and password. This is the user name
  581. * parameter.
  582. */
  583. const char* username;
  584. /**
  585. * MQTT servers that support the MQTT v3.1.1 protocol provide authentication
  586. * and authorisation by user name and password. This is the password
  587. * parameter.
  588. */
  589. const char* password;
  590. /**
  591. * The time interval in seconds to allow a connect to complete.
  592. */
  593. int connectTimeout;
  594. /**
  595. * The time interval in seconds
  596. */
  597. int retryInterval;
  598. /**
  599. * This is a pointer to an MQTTClient_SSLOptions structure. If your
  600. * application does not make use of SSL, set this pointer to NULL.
  601. */
  602. MQTTClient_SSLOptions* ssl;
  603. /**
  604. * The number of entries in the optional serverURIs array. Defaults to 0.
  605. */
  606. int serverURIcount;
  607. /**
  608. * An optional array of null-terminated strings specifying the servers to
  609. * which the client will connect. Each string takes the form <i>protocol://host:port</i>.
  610. * <i>protocol</i> must be <i>tcp</i> or <i>ssl</i>. For <i>host</i>, you can
  611. * specify either an IP address or a host name. For instance, to connect to
  612. * a server running on the local machines with the default MQTT port, specify
  613. * <i>tcp://localhost:1883</i>.
  614. * If this list is empty (the default), the server URI specified on MQTTClient_create()
  615. * is used.
  616. */
  617. char* const* serverURIs;
  618. /**
  619. * Sets the version of MQTT to be used on the connect.
  620. * MQTTVERSION_DEFAULT (0) = default: start with 3.1.1, and if that fails, fall back to 3.1
  621. * MQTTVERSION_3_1 (3) = only try version 3.1
  622. * MQTTVERSION_3_1_1 (4) = only try version 3.1.1
  623. */
  624. int MQTTVersion;
  625. /**
  626. * Returned from the connect when the MQTT version used to connect is 3.1.1
  627. */
  628. struct
  629. {
  630. const char* serverURI; /**< the serverURI connected to */
  631. int MQTTVersion; /**< the MQTT version used to connect with */
  632. int sessionPresent; /**< if the MQTT version is 3.1.1, the value of sessionPresent returned in the connack */
  633. } returned;
  634. /**
  635. * Optional binary password. Only checked and used if the password option is NULL
  636. */
  637. struct {
  638. int len; /**< binary password length */
  639. const void* data; /**< binary password data */
  640. } binarypwd;
  641. } MQTTClient_connectOptions;
  642. #define MQTTClient_connectOptions_initializer { {'M', 'Q', 'T', 'C'}, 5, 60, 1, 1, NULL, NULL, NULL, 30, 20, NULL, 0, NULL, 0, {NULL, 0, 0}, {0, NULL} }
  643. /**
  644. * MQTTClient_libraryInfo is used to store details relating to the currently used
  645. * library such as the version in use, the time it was built and relevant openSSL
  646. * options.
  647. * There is one static instance of this struct in MQTTClient.c
  648. */
  649. typedef struct
  650. {
  651. const char* name;
  652. const char* value;
  653. } MQTTClient_nameValue;
  654. /**
  655. * This function returns version information about the library.
  656. * no trace information will be returned.
  657. * @return an array of strings describing the library. The last entry is a NULL pointer.
  658. */
  659. DLLExport MQTTClient_nameValue* MQTTClient_getVersionInfo(void);
  660. /**
  661. * This function attempts to connect a previously-created client (see
  662. * MQTTClient_create()) to an MQTT server using the specified options. If you
  663. * want to enable asynchronous message and status notifications, you must call
  664. * MQTTClient_setCallbacks() prior to MQTTClient_connect().
  665. * @param handle A valid client handle from a successful call to
  666. * MQTTClient_create().
  667. * @param options A pointer to a valid MQTTClient_connectOptions
  668. * structure.
  669. * @return ::MQTTCLIENT_SUCCESS if the client successfully connects to the
  670. * server. An error code is returned if the client was unable to connect to
  671. * the server.
  672. * Error codes greater than 0 are returned by the MQTT protocol:<br><br>
  673. * <b>1</b>: Connection refused: Unacceptable protocol version<br>
  674. * <b>2</b>: Connection refused: Identifier rejected<br>
  675. * <b>3</b>: Connection refused: Server unavailable<br>
  676. * <b>4</b>: Connection refused: Bad user name or password<br>
  677. * <b>5</b>: Connection refused: Not authorized<br>
  678. * <b>6-255</b>: Reserved for future use<br>
  679. */
  680. DLLExport int MQTTClient_connect(MQTTClient handle, MQTTClient_connectOptions* options);
  681. /**
  682. * This function attempts to disconnect the client from the MQTT
  683. * server. In order to allow the client time to complete handling of messages
  684. * that are in-flight when this function is called, a timeout period is
  685. * specified. When the timeout period has expired, the client disconnects even
  686. * if there are still outstanding message acknowledgements.
  687. * The next time the client connects to the same server, any QoS 1 or 2
  688. * messages which have not completed will be retried depending on the
  689. * cleansession settings for both the previous and the new connection (see
  690. * MQTTClient_connectOptions.cleansession and MQTTClient_connect()).
  691. * @param handle A valid client handle from a successful call to
  692. * MQTTClient_create().
  693. * @param timeout The client delays disconnection for up to this time (in
  694. * milliseconds) in order to allow in-flight message transfers to complete.
  695. * @return ::MQTTCLIENT_SUCCESS if the client successfully disconnects from
  696. * the server. An error code is returned if the client was unable to disconnect
  697. * from the server
  698. */
  699. DLLExport int MQTTClient_disconnect(MQTTClient handle, int timeout);
  700. /**
  701. * This function allows the client application to test whether or not a
  702. * client is currently connected to the MQTT server.
  703. * @param handle A valid client handle from a successful call to
  704. * MQTTClient_create().
  705. * @return Boolean true if the client is connected, otherwise false.
  706. */
  707. DLLExport int MQTTClient_isConnected(MQTTClient handle);
  708. /* Subscribe is synchronous. QoS list parameter is changed on return to granted QoSs.
  709. Returns return code, MQTTCLIENT_SUCCESS == success, non-zero some sort of error (TBD) */
  710. /**
  711. * This function attempts to subscribe a client to a single topic, which may
  712. * contain wildcards (see @ref wildcard). This call also specifies the
  713. * @ref qos requested for the subscription
  714. * (see also MQTTClient_subscribeMany()).
  715. * @param handle A valid client handle from a successful call to
  716. * MQTTClient_create().
  717. * @param topic The subscription topic, which may include wildcards.
  718. * @param qos The requested quality of service for the subscription.
  719. * @return ::MQTTCLIENT_SUCCESS if the subscription request is successful.
  720. * An error code is returned if there was a problem registering the
  721. * subscription.
  722. */
  723. DLLExport int MQTTClient_subscribe(MQTTClient handle, const char* topic, int qos);
  724. /**
  725. * This function attempts to subscribe a client to a list of topics, which may
  726. * contain wildcards (see @ref wildcard). This call also specifies the
  727. * @ref qos requested for each topic (see also MQTTClient_subscribe()).
  728. * @param handle A valid client handle from a successful call to
  729. * MQTTClient_create().
  730. * @param count The number of topics for which the client is requesting
  731. * subscriptions.
  732. * @param topic An array (of length <i>count</i>) of pointers to
  733. * topics, each of which may include wildcards.
  734. * @param qos An array (of length <i>count</i>) of @ref qos
  735. * values. qos[n] is the requested QoS for topic[n].
  736. * @return ::MQTTCLIENT_SUCCESS if the subscription request is successful.
  737. * An error code is returned if there was a problem registering the
  738. * subscriptions.
  739. */
  740. DLLExport int MQTTClient_subscribeMany(MQTTClient handle, int count, char* const* topic, int* qos);
  741. /**
  742. * This function attempts to remove an existing subscription made by the
  743. * specified client.
  744. * @param handle A valid client handle from a successful call to
  745. * MQTTClient_create().
  746. * @param topic The topic for the subscription to be removed, which may
  747. * include wildcards (see @ref wildcard).
  748. * @return ::MQTTCLIENT_SUCCESS if the subscription is removed.
  749. * An error code is returned if there was a problem removing the
  750. * subscription.
  751. */
  752. DLLExport int MQTTClient_unsubscribe(MQTTClient handle, const char* topic);
  753. /**
  754. * This function attempts to remove existing subscriptions to a list of topics
  755. * made by the specified client.
  756. * @param handle A valid client handle from a successful call to
  757. * MQTTClient_create().
  758. * @param count The number subscriptions to be removed.
  759. * @param topic An array (of length <i>count</i>) of pointers to the topics of
  760. * the subscriptions to be removed, each of which may include wildcards.
  761. * @return ::MQTTCLIENT_SUCCESS if the subscriptions are removed.
  762. * An error code is returned if there was a problem removing the subscriptions.
  763. */
  764. DLLExport int MQTTClient_unsubscribeMany(MQTTClient handle, int count, char* const* topic);
  765. /**
  766. * This function attempts to publish a message to a given topic (see also
  767. * MQTTClient_publishMessage()). An ::MQTTClient_deliveryToken is issued when
  768. * this function returns successfully. If the client application needs to
  769. * test for succesful delivery of QoS1 and QoS2 messages, this can be done
  770. * either asynchronously or synchronously (see @ref async,
  771. * ::MQTTClient_waitForCompletion and MQTTClient_deliveryComplete()).
  772. * @param handle A valid client handle from a successful call to
  773. * MQTTClient_create().
  774. * @param topicName The topic associated with this message.
  775. * @param payloadlen The length of the payload in bytes.
  776. * @param payload A pointer to the byte array payload of the message.
  777. * @param qos The @ref qos of the message.
  778. * @param retained The retained flag for the message.
  779. * @param dt A pointer to an ::MQTTClient_deliveryToken. This is populated
  780. * with a token representing the message when the function returns
  781. * successfully. If your application does not use delivery tokens, set this
  782. * argument to NULL.
  783. * @return ::MQTTCLIENT_SUCCESS if the message is accepted for publication.
  784. * An error code is returned if there was a problem accepting the message.
  785. */
  786. DLLExport int MQTTClient_publish(MQTTClient handle, const char* topicName, int payloadlen, void* payload, int qos, int retained,
  787. MQTTClient_deliveryToken* dt);
  788. /**
  789. * This function attempts to publish a message to a given topic (see also
  790. * MQTTClient_publish()). An ::MQTTClient_deliveryToken is issued when
  791. * this function returns successfully. If the client application needs to
  792. * test for succesful delivery of QoS1 and QoS2 messages, this can be done
  793. * either asynchronously or synchronously (see @ref async,
  794. * ::MQTTClient_waitForCompletion and MQTTClient_deliveryComplete()).
  795. * @param handle A valid client handle from a successful call to
  796. * MQTTClient_create().
  797. * @param topicName The topic associated with this message.
  798. * @param msg A pointer to a valid MQTTClient_message structure containing
  799. * the payload and attributes of the message to be published.
  800. * @param dt A pointer to an ::MQTTClient_deliveryToken. This is populated
  801. * with a token representing the message when the function returns
  802. * successfully. If your application does not use delivery tokens, set this
  803. * argument to NULL.
  804. * @return ::MQTTCLIENT_SUCCESS if the message is accepted for publication.
  805. * An error code is returned if there was a problem accepting the message.
  806. */
  807. DLLExport int MQTTClient_publishMessage(MQTTClient handle, const char* topicName, MQTTClient_message* msg, MQTTClient_deliveryToken* dt);
  808. /**
  809. * This function is called by the client application to synchronize execution
  810. * of the main thread with completed publication of a message. When called,
  811. * MQTTClient_waitForCompletion() blocks execution until the message has been
  812. * successful delivered or the specified timeout has expired. See @ref async.
  813. * @param handle A valid client handle from a successful call to
  814. * MQTTClient_create().
  815. * @param dt The ::MQTTClient_deliveryToken that represents the message being
  816. * tested for successful delivery. Delivery tokens are issued by the
  817. * publishing functions MQTTClient_publish() and MQTTClient_publishMessage().
  818. * @param timeout The maximum time to wait in milliseconds.
  819. * @return ::MQTTCLIENT_SUCCESS if the message was successfully delivered.
  820. * An error code is returned if the timeout expires or there was a problem
  821. * checking the token.
  822. */
  823. DLLExport int MQTTClient_waitForCompletion(MQTTClient handle, MQTTClient_deliveryToken dt, unsigned long timeout);
  824. /**
  825. * This function sets a pointer to an array of delivery tokens for
  826. * messages that are currently in-flight (pending completion).
  827. *
  828. * <b>Important note:</b> The memory used to hold the array of tokens is
  829. * malloc()'d in this function. The client application is responsible for
  830. * freeing this memory when it is no longer required.
  831. * @param handle A valid client handle from a successful call to
  832. * MQTTClient_create().
  833. * @param tokens The address of a pointer to an ::MQTTClient_deliveryToken.
  834. * When the function returns successfully, the pointer is set to point to an
  835. * array of tokens representing messages pending completion. The last member of
  836. * the array is set to -1 to indicate there are no more tokens. If no tokens
  837. * are pending, the pointer is set to NULL.
  838. * @return ::MQTTCLIENT_SUCCESS if the function returns successfully.
  839. * An error code is returned if there was a problem obtaining the list of
  840. * pending tokens.
  841. */
  842. DLLExport int MQTTClient_getPendingDeliveryTokens(MQTTClient handle, MQTTClient_deliveryToken **tokens);
  843. /**
  844. * When implementing a single-threaded client, call this function periodically
  845. * to allow processing of message retries and to send MQTT keepalive pings.
  846. * If the application is calling MQTTClient_receive() regularly, then it is
  847. * not necessary to call this function.
  848. */
  849. DLLExport void MQTTClient_yield(void);
  850. /**
  851. * This function performs a synchronous receive of incoming messages. It should
  852. * be used only when the client application has not set callback methods to
  853. * support asynchronous receipt of messages (see @ref async and
  854. * MQTTClient_setCallbacks()). Using this function allows a single-threaded
  855. * client subscriber application to be written. When called, this function
  856. * blocks until the next message arrives or the specified timeout expires
  857. *(see also MQTTClient_yield()).
  858. *
  859. * <b>Important note:</b> The application must free() the memory allocated
  860. * to the topic and the message when processing is complete (see
  861. * MQTTClient_freeMessage()).
  862. * @param handle A valid client handle from a successful call to
  863. * MQTTClient_create().
  864. * @param topicName The address of a pointer to a topic. This function
  865. * allocates the memory for the topic and returns it to the application
  866. * by setting <i>topicName</i> to point to the topic.
  867. * @param topicLen The length of the topic. If the return code from this
  868. * function is ::MQTTCLIENT_TOPICNAME_TRUNCATED, the topic contains embedded
  869. * NULL characters and the full topic should be retrieved by using
  870. * <i>topicLen</i>.
  871. * @param message The address of a pointer to the received message. This
  872. * function allocates the memory for the message and returns it to the
  873. * application by setting <i>message</i> to point to the received message.
  874. * The pointer is set to NULL if the timeout expires.
  875. * @param timeout The length of time to wait for a message in milliseconds.
  876. * @return ::MQTTCLIENT_SUCCESS or ::MQTTCLIENT_TOPICNAME_TRUNCATED if a
  877. * message is received. ::MQTTCLIENT_SUCCESS can also indicate that the
  878. * timeout expired, in which case <i>message</i> is NULL. An error code is
  879. * returned if there was a problem trying to receive a message.
  880. */
  881. DLLExport int MQTTClient_receive(MQTTClient handle, char** topicName, int* topicLen, MQTTClient_message** message,
  882. unsigned long timeout);
  883. /**
  884. * This function frees memory allocated to an MQTT message, including the
  885. * additional memory allocated to the message payload. The client application
  886. * calls this function when the message has been fully processed. <b>Important
  887. * note:</b> This function does not free the memory allocated to a message
  888. * topic string. It is the responsibility of the client application to free
  889. * this memory using the MQTTClient_free() library function.
  890. * @param msg The address of a pointer to the ::MQTTClient_message structure
  891. * to be freed.
  892. */
  893. DLLExport void MQTTClient_freeMessage(MQTTClient_message** msg);
  894. /**
  895. * This function frees memory allocated by the MQTT C client library, especially the
  896. * topic name. This is needed on Windows when the client libary and application
  897. * program have been compiled with different versions of the C compiler. It is
  898. * thus good policy to always use this function when freeing any MQTT C client-
  899. * allocated memory.
  900. * @param ptr The pointer to the client library storage to be freed.
  901. */
  902. DLLExport void MQTTClient_free(void* ptr);
  903. /**
  904. * This function frees the memory allocated to an MQTT client (see
  905. * MQTTClient_create()). It should be called when the client is no longer
  906. * required.
  907. * @param handle A pointer to the handle referring to the ::MQTTClient
  908. * structure to be freed.
  909. */
  910. DLLExport void MQTTClient_destroy(MQTTClient* handle);
  911. #endif
  912. #ifdef __cplusplus
  913. }
  914. #endif
  915. /**
  916. * @cond MQTTClient_main
  917. * @page async Asynchronous vs synchronous client applications
  918. * The client library supports two modes of operation. These are referred to
  919. * as <b>synchronous</b> and <b>asynchronous</b> modes. If your application
  920. * calls MQTTClient_setCallbacks(), this puts the client into asynchronous
  921. * mode, otherwise it operates in synchronous mode.
  922. *
  923. * In synchronous mode, the client application runs on a single thread.
  924. * Messages are published using the MQTTClient_publish() and
  925. * MQTTClient_publishMessage() functions. To determine that a QoS1 or QoS2
  926. * (see @ref qos) message has been successfully delivered, the application
  927. * must call the MQTTClient_waitForCompletion() function. An example showing
  928. * synchronous publication is shown in @ref pubsync. Receiving messages in
  929. * synchronous mode uses the MQTTClient_receive() function. Client applications
  930. * must call either MQTTClient_receive() or MQTTClient_yield() relatively
  931. * frequently in order to allow processing of acknowledgements and the MQTT
  932. * "pings" that keep the network connection to the server alive.
  933. *
  934. * In asynchronous mode, the client application runs on several threads. The
  935. * main program calls functions in the client library to publish and subscribe,
  936. * just as for the synchronous mode. Processing of handshaking and maintaining
  937. * the network connection is performed in the background, however.
  938. * Notifications of status and message reception are provided to the client
  939. * application using callbacks registered with the library by the call to
  940. * MQTTClient_setCallbacks() (see MQTTClient_messageArrived(),
  941. * MQTTClient_connectionLost() and MQTTClient_deliveryComplete()).
  942. * This API is not thread safe however - it is not possible to call it from multiple
  943. * threads without synchronization. You can use the MQTTAsync API for that.
  944. *
  945. * @page wildcard Subscription wildcards
  946. * Every MQTT message includes a topic that classifies it. MQTT servers use
  947. * topics to determine which subscribers should receive messages published to
  948. * the server.
  949. *
  950. * Consider the server receiving messages from several environmental sensors.
  951. * Each sensor publishes its measurement data as a message with an associated
  952. * topic. Subscribing applications need to know which sensor originally
  953. * published each received message. A unique topic is thus used to identify
  954. * each sensor and measurement type. Topics such as SENSOR1TEMP,
  955. * SENSOR1HUMIDITY, SENSOR2TEMP and so on achieve this but are not very
  956. * flexible. If additional sensors are added to the system at a later date,
  957. * subscribing applications must be modified to receive them.
  958. *
  959. * To provide more flexibility, MQTT supports a hierarchical topic namespace.
  960. * This allows application designers to organize topics to simplify their
  961. * management. Levels in the hierarchy are delimited by the '/' character,
  962. * such as SENSOR/1/HUMIDITY. Publishers and subscribers use these
  963. * hierarchical topics as already described.
  964. *
  965. * For subscriptions, two wildcard characters are supported:
  966. * <ul>
  967. * <li>A '#' character represents a complete sub-tree of the hierarchy and
  968. * thus must be the last character in a subscription topic string, such as
  969. * SENSOR/#. This will match any topic starting with SENSOR/, such as
  970. * SENSOR/1/TEMP and SENSOR/2/HUMIDITY.</li>
  971. * <li> A '+' character represents a single level of the hierarchy and is
  972. * used between delimiters. For example, SENSOR/+/TEMP will match
  973. * SENSOR/1/TEMP and SENSOR/2/TEMP.</li>
  974. * </ul>
  975. * Publishers are not allowed to use the wildcard characters in their topic
  976. * names.
  977. *
  978. * Deciding on your topic hierarchy is an important step in your system design.
  979. *
  980. * @page qos Quality of service
  981. * The MQTT protocol provides three qualities of service for delivering
  982. * messages between clients and servers: "at most once", "at least once" and
  983. * "exactly once".
  984. *
  985. * Quality of service (QoS) is an attribute of an individual message being
  986. * published. An application sets the QoS for a specific message by setting the
  987. * MQTTClient_message.qos field to the required value.
  988. *
  989. * A subscribing client can set the maximum quality of service a server uses
  990. * to send messages that match the client subscriptions. The
  991. * MQTTClient_subscribe() and MQTTClient_subscribeMany() functions set this
  992. * maximum. The QoS of a message forwarded to a subscriber thus might be
  993. * different to the QoS given to the message by the original publisher.
  994. * The lower of the two values is used to forward a message.
  995. *
  996. * The three levels are:
  997. *
  998. * <b>QoS0, At most once:</b> The message is delivered at most once, or it
  999. * may not be delivered at all. Its delivery across the network is not
  1000. * acknowledged. The message is not stored. The message could be lost if the
  1001. * client is disconnected, or if the server fails. QoS0 is the fastest mode of
  1002. * transfer. It is sometimes called "fire and forget".
  1003. *
  1004. * The MQTT protocol does not require servers to forward publications at QoS0
  1005. * to a client. If the client is disconnected at the time the server receives
  1006. * the publication, the publication might be discarded, depending on the
  1007. * server implementation.
  1008. *
  1009. * <b>QoS1, At least once:</b> The message is always delivered at least once.
  1010. * It might be delivered multiple times if there is a failure before an
  1011. * acknowledgment is received by the sender. The message must be stored
  1012. * locally at the sender, until the sender receives confirmation that the
  1013. * message has been published by the receiver. The message is stored in case
  1014. * the message must be sent again.
  1015. *
  1016. * <b>QoS2, Exactly once:</b> The message is always delivered exactly once.
  1017. * The message must be stored locally at the sender, until the sender receives
  1018. * confirmation that the message has been published by the receiver. The
  1019. * message is stored in case the message must be sent again. QoS2 is the
  1020. * safest, but slowest mode of transfer. A more sophisticated handshaking
  1021. * and acknowledgement sequence is used than for QoS1 to ensure no duplication
  1022. * of messages occurs.
  1023. * @page pubsync Synchronous publication example
  1024. @code
  1025. #include <stdio.h>
  1026. #include <stdlib.h>
  1027. #include <string.h>
  1028. #include "MQTTClient.h"
  1029. #define ADDRESS "tcp://localhost:1883"
  1030. #define CLIENTID "ExampleClientPub"
  1031. #define TOPIC "MQTT Examples"
  1032. #define PAYLOAD "Hello World!"
  1033. #define QOS 1
  1034. #define TIMEOUT 10000L
  1035. int main(int argc, char* argv[])
  1036. {
  1037. MQTTClient client;
  1038. MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  1039. MQTTClient_message pubmsg = MQTTClient_message_initializer;
  1040. MQTTClient_deliveryToken token;
  1041. int rc;
  1042. MQTTClient_create(&client, ADDRESS, CLIENTID,
  1043. MQTTCLIENT_PERSISTENCE_NONE, NULL);
  1044. conn_opts.keepAliveInterval = 20;
  1045. conn_opts.cleansession = 1;
  1046. if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  1047. {
  1048. printf("Failed to connect, return code %d\n", rc);
  1049. exit(EXIT_FAILURE);
  1050. }
  1051. pubmsg.payload = PAYLOAD;
  1052. pubmsg.payloadlen = strlen(PAYLOAD);
  1053. pubmsg.qos = QOS;
  1054. pubmsg.retained = 0;
  1055. MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
  1056. printf("Waiting for up to %d seconds for publication of %s\n"
  1057. "on topic %s for client with ClientID: %s\n",
  1058. (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
  1059. rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
  1060. printf("Message with delivery token %d delivered\n", token);
  1061. MQTTClient_disconnect(client, 10000);
  1062. MQTTClient_destroy(&client);
  1063. return rc;
  1064. }
  1065. * @endcode
  1066. *
  1067. * @page pubasync Asynchronous publication example
  1068. @code{.c}
  1069. #include <stdio.h>
  1070. #include <stdlib.h>
  1071. #include <string.h>
  1072. #include "MQTTClient.h"
  1073. #define ADDRESS "tcp://localhost:1883"
  1074. #define CLIENTID "ExampleClientPub"
  1075. #define TOPIC "MQTT Examples"
  1076. #define PAYLOAD "Hello World!"
  1077. #define QOS 1
  1078. #define TIMEOUT 10000L
  1079. volatile MQTTClient_deliveryToken deliveredtoken;
  1080. void delivered(void *context, MQTTClient_deliveryToken dt)
  1081. {
  1082. printf("Message with token value %d delivery confirmed\n", dt);
  1083. deliveredtoken = dt;
  1084. }
  1085. int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
  1086. {
  1087. int i;
  1088. char* payloadptr;
  1089. printf("Message arrived\n");
  1090. printf(" topic: %s\n", topicName);
  1091. printf(" message: ");
  1092. payloadptr = message->payload;
  1093. for(i=0; i<message->payloadlen; i++)
  1094. {
  1095. putchar(*payloadptr++);
  1096. }
  1097. putchar('\n');
  1098. MQTTClient_freeMessage(&message);
  1099. MQTTClient_free(topicName);
  1100. return 1;
  1101. }
  1102. void connlost(void *context, char *cause)
  1103. {
  1104. printf("\nConnection lost\n");
  1105. printf(" cause: %s\n", cause);
  1106. }
  1107. int main(int argc, char* argv[])
  1108. {
  1109. MQTTClient client;
  1110. MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  1111. MQTTClient_message pubmsg = MQTTClient_message_initializer;
  1112. MQTTClient_deliveryToken token;
  1113. int rc;
  1114. MQTTClient_create(&client, ADDRESS, CLIENTID,
  1115. MQTTCLIENT_PERSISTENCE_NONE, NULL);
  1116. conn_opts.keepAliveInterval = 20;
  1117. conn_opts.cleansession = 1;
  1118. MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
  1119. if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  1120. {
  1121. printf("Failed to connect, return code %d\n", rc);
  1122. exit(EXIT_FAILURE);
  1123. }
  1124. pubmsg.payload = PAYLOAD;
  1125. pubmsg.payloadlen = strlen(PAYLOAD);
  1126. pubmsg.qos = QOS;
  1127. pubmsg.retained = 0;
  1128. deliveredtoken = 0;
  1129. MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
  1130. printf("Waiting for publication of %s\n"
  1131. "on topic %s for client with ClientID: %s\n",
  1132. PAYLOAD, TOPIC, CLIENTID);
  1133. while(deliveredtoken != token);
  1134. MQTTClient_disconnect(client, 10000);
  1135. MQTTClient_destroy(&client);
  1136. return rc;
  1137. }
  1138. * @endcode
  1139. * @page subasync Asynchronous subscription example
  1140. @code
  1141. #include <stdio.h>
  1142. #include <stdlib.h>
  1143. #include <string.h>
  1144. #include "MQTTClient.h"
  1145. #define ADDRESS "tcp://localhost:1883"
  1146. #define CLIENTID "ExampleClientSub"
  1147. #define TOPIC "MQTT Examples"
  1148. #define PAYLOAD "Hello World!"
  1149. #define QOS 1
  1150. #define TIMEOUT 10000L
  1151. volatile MQTTClient_deliveryToken deliveredtoken;
  1152. void delivered(void *context, MQTTClient_deliveryToken dt)
  1153. {
  1154. printf("Message with token value %d delivery confirmed\n", dt);
  1155. deliveredtoken = dt;
  1156. }
  1157. int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
  1158. {
  1159. int i;
  1160. char* payloadptr;
  1161. printf("Message arrived\n");
  1162. printf(" topic: %s\n", topicName);
  1163. printf(" message: ");
  1164. payloadptr = message->payload;
  1165. for(i=0; i<message->payloadlen; i++)
  1166. {
  1167. putchar(*payloadptr++);
  1168. }
  1169. putchar('\n');
  1170. MQTTClient_freeMessage(&message);
  1171. MQTTClient_free(topicName);
  1172. return 1;
  1173. }
  1174. void connlost(void *context, char *cause)
  1175. {
  1176. printf("\nConnection lost\n");
  1177. printf(" cause: %s\n", cause);
  1178. }
  1179. int main(int argc, char* argv[])
  1180. {
  1181. MQTTClient client;
  1182. MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  1183. int rc;
  1184. int ch;
  1185. MQTTClient_create(&client, ADDRESS, CLIENTID,
  1186. MQTTCLIENT_PERSISTENCE_NONE, NULL);
  1187. conn_opts.keepAliveInterval = 20;
  1188. conn_opts.cleansession = 1;
  1189. MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
  1190. if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  1191. {
  1192. printf("Failed to connect, return code %d\n", rc);
  1193. exit(EXIT_FAILURE);
  1194. }
  1195. printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
  1196. "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
  1197. MQTTClient_subscribe(client, TOPIC, QOS);
  1198. do
  1199. {
  1200. ch = getchar();
  1201. } while(ch!='Q' && ch != 'q');
  1202. MQTTClient_disconnect(client, 10000);
  1203. MQTTClient_destroy(&client);
  1204. return rc;
  1205. }
  1206. * @endcode
  1207. * @page tracing Tracing
  1208. *
  1209. * Runtime tracing is controlled by environment variables.
  1210. *
  1211. * Tracing is switched on by setting MQTT_C_CLIENT_TRACE. A value of ON, or stdout, prints to
  1212. * stdout, any other value is interpreted as a file name to use.
  1213. *
  1214. * The amount of trace detail is controlled with the MQTT_C_CLIENT_TRACE_LEVEL environment
  1215. * variable - valid values are ERROR, PROTOCOL, MINIMUM, MEDIUM and MAXIMUM
  1216. * (from least to most verbose).
  1217. *
  1218. * The variable MQTT_C_CLIENT_TRACE_MAX_LINES limits the number of lines of trace that are output
  1219. * to a file. Two files are used at most, when they are full, the last one is overwritten with the
  1220. * new trace entries. The default size is 1000 lines.
  1221. *
  1222. * ### MQTT Packet Tracing
  1223. *
  1224. * A feature that can be very useful is printing the MQTT packets that are sent and received. To
  1225. * achieve this, use the following environment variable settings:
  1226. * @code
  1227. MQTT_C_CLIENT_TRACE=ON
  1228. MQTT_C_CLIENT_TRACE_LEVEL=PROTOCOL
  1229. * @endcode
  1230. * The output you should see looks like this:
  1231. * @code
  1232. 20130528 155936.813 3 stdout-subscriber -> CONNECT cleansession: 1 (0)
  1233. 20130528 155936.813 3 stdout-subscriber <- CONNACK rc: 0
  1234. 20130528 155936.813 3 stdout-subscriber -> SUBSCRIBE msgid: 1 (0)
  1235. 20130528 155936.813 3 stdout-subscriber <- SUBACK msgid: 1
  1236. 20130528 155941.818 3 stdout-subscriber -> DISCONNECT (0)
  1237. * @endcode
  1238. * where the fields are:
  1239. * 1. date
  1240. * 2. time
  1241. * 3. socket number
  1242. * 4. client id
  1243. * 5. direction (-> from client to server, <- from server to client)
  1244. * 6. packet details
  1245. *
  1246. * ### Default Level Tracing
  1247. *
  1248. * This is an extract of a default level trace of a call to connect:
  1249. * @code
  1250. 19700101 010000.000 (1152206656) (0)> MQTTClient_connect:893
  1251. 19700101 010000.000 (1152206656) (1)> MQTTClient_connectURI:716
  1252. 20130528 160447.479 Connecting to serverURI localhost:1883
  1253. 20130528 160447.479 (1152206656) (2)> MQTTProtocol_connect:98
  1254. 20130528 160447.479 (1152206656) (3)> MQTTProtocol_addressPort:48
  1255. 20130528 160447.479 (1152206656) (3)< MQTTProtocol_addressPort:73
  1256. 20130528 160447.479 (1152206656) (3)> Socket_new:599
  1257. 20130528 160447.479 New socket 4 for localhost, port 1883
  1258. 20130528 160447.479 (1152206656) (4)> Socket_addSocket:163
  1259. 20130528 160447.479 (1152206656) (5)> Socket_setnonblocking:73
  1260. 20130528 160447.479 (1152206656) (5)< Socket_setnonblocking:78 (0)
  1261. 20130528 160447.479 (1152206656) (4)< Socket_addSocket:176 (0)
  1262. 20130528 160447.479 (1152206656) (4)> Socket_error:95
  1263. 20130528 160447.479 (1152206656) (4)< Socket_error:104 (115)
  1264. 20130528 160447.479 Connect pending
  1265. 20130528 160447.479 (1152206656) (3)< Socket_new:683 (115)
  1266. 20130528 160447.479 (1152206656) (2)< MQTTProtocol_connect:131 (115)
  1267. * @endcode
  1268. * where the fields are:
  1269. * 1. date
  1270. * 2. time
  1271. * 3. thread id
  1272. * 4. function nesting level
  1273. * 5. function entry (>) or exit (<)
  1274. * 6. function name : line of source code file
  1275. * 7. return value (if there is one)
  1276. *
  1277. * ### Memory Allocation Tracing
  1278. *
  1279. * Setting the trace level to maximum causes memory allocations and frees to be traced along with
  1280. * the default trace entries, with messages like the following:
  1281. * @code
  1282. 20130528 161819.657 Allocating 16 bytes in heap at file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c line 177 ptr 0x179f930
  1283. 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
  1284. * @endcode
  1285. * When the last MQTT client object is destroyed, if the trace is being recorded
  1286. * and all memory allocated by the client library has not been freed, an error message will be
  1287. * written to the trace. This can help with fixing memory leaks. The message will look like this:
  1288. * @code
  1289. 20130528 163909.208 Some memory not freed at shutdown, possible memory leak
  1290. 20130528 163909.208 Heap scan start, total 880 bytes
  1291. 20130528 163909.208 Heap element size 32, line 354, file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c, ptr 0x260cb00
  1292. 20130528 163909.208 Content
  1293. 20130528 163909.209 Heap scan end
  1294. * @endcode
  1295. * @endcond
  1296. */