MQTTAsync.h 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405
  1. /*******************************************************************************
  2. * Copyright (c) 2009, 2025 IBM Corp., Ian Craggs and others
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v2.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * https://www.eclipse.org/legal/epl-2.0/
  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
  15. * Ian Craggs, Allan Stockdill-Mander - SSL connections
  16. * Ian Craggs - multiple server connection support
  17. * Ian Craggs - MQTT 3.1.1 support
  18. * Ian Craggs - fix for bug 444103 - success/failure callbacks not invoked
  19. * Ian Craggs - automatic reconnect and offline buffering (send while disconnected)
  20. * Ian Craggs - binary will message
  21. * Ian Craggs - binary password
  22. * Ian Craggs - remove const on eyecatchers #168
  23. * Ian Craggs - MQTT 5.0
  24. *******************************************************************************/
  25. /********************************************************************/
  26. /**
  27. * @cond MQTTAsync_main
  28. * @mainpage Asynchronous MQTT client library for C (MQTTAsync)
  29. *
  30. * © Copyright 2009, 2025 IBM Corp., Ian Craggs and others.
  31. *
  32. * @brief An Asynchronous MQTT client library for C.
  33. *
  34. * Version 1.3.14
  35. *
  36. * An MQTT client application connects to MQTT-capable servers.
  37. * A typical client is responsible for collecting information from a telemetry
  38. * device and publishing the information to the server. It can also subscribe
  39. * to topics, receive messages, and use this information to control the
  40. * telemetry device.
  41. *
  42. * MQTT clients implement the published MQTT v3 protocol. You can write your own
  43. * API to the MQTT protocol using the programming language and platform of your
  44. * choice. This can be time-consuming and error-prone.
  45. *
  46. * To simplify writing MQTT client applications, this library encapsulates
  47. * the MQTT v3 protocol for you. Using this library enables a fully functional
  48. * MQTT client application to be written in a few lines of code.
  49. * The information presented here documents the API provided
  50. * by the Asynchronous MQTT Client library for C.
  51. *
  52. * <b>Using the client</b><br>
  53. * Applications that use the client library typically use a similar structure:
  54. * <ul>
  55. * <li>Create a client object</li>
  56. * <li>Set the options to connect to an MQTT server</li>
  57. * <li>Set up callback functions</li>
  58. * <li>Connect the client to an MQTT server</li>
  59. * <li>Subscribe to any topics the client needs to receive</li>
  60. * <li>Repeat until finished:</li>
  61. * <ul>
  62. * <li>Publish any messages the client needs to</li>
  63. * <li>Handle any incoming messages</li>
  64. * </ul>
  65. * <li>Disconnect the client</li>
  66. * <li>Free any memory being used by the client</li>
  67. * </ul>
  68. * Some simple examples are shown here:
  69. * <ul>
  70. * <li>@ref publish</li>
  71. * <li>@ref subscribe</li>
  72. * </ul>
  73. * Additional information about important concepts is provided here:
  74. * <ul>
  75. * <li>@ref async</li>
  76. * <li>@ref wildcard</li>
  77. * <li>@ref qos</li>
  78. * <li>@ref tracing</li>
  79. * <li>@ref auto_reconnect</li>
  80. * <li>@ref offline_publish</li>
  81. * <li>@ref HTTP_proxies</li>
  82. * </ul>
  83. * @endcond
  84. */
  85. /*
  86. /// @cond EXCLUDE
  87. */
  88. #if !defined(MQTTASYNC_H)
  89. #define MQTTASYNC_H
  90. #if defined(__cplusplus)
  91. extern "C" {
  92. #endif
  93. #include <stdio.h>
  94. /*
  95. /// @endcond
  96. */
  97. #include "MQTTExportDeclarations.h"
  98. #include "MQTTProperties.h"
  99. #include "MQTTReasonCodes.h"
  100. #include "MQTTSubscribeOpts.h"
  101. #if !defined(NO_PERSISTENCE)
  102. #include "MQTTClientPersistence.h"
  103. #else
  104. #define MQTTCLIENT_PERSISTENCE_NONE 1
  105. #endif
  106. /**
  107. * Return code: No error. Indicates successful completion of an MQTT client
  108. * operation.
  109. */
  110. #define MQTTASYNC_SUCCESS 0
  111. /**
  112. * Return code: A generic error code indicating the failure of an MQTT client
  113. * operation.
  114. */
  115. #define MQTTASYNC_FAILURE -1
  116. /* error code -2 is MQTTAsync_PERSISTENCE_ERROR */
  117. #define MQTTASYNC_PERSISTENCE_ERROR -2
  118. /**
  119. * Return code: The client is disconnected.
  120. */
  121. #define MQTTASYNC_DISCONNECTED -3
  122. /**
  123. * Return code: The maximum number of messages allowed to be simultaneously
  124. * in-flight has been reached.
  125. */
  126. #define MQTTASYNC_MAX_MESSAGES_INFLIGHT -4
  127. /**
  128. * Return code: An invalid UTF-8 string has been detected.
  129. */
  130. #define MQTTASYNC_BAD_UTF8_STRING -5
  131. /**
  132. * Return code: A NULL parameter has been supplied when this is invalid.
  133. */
  134. #define MQTTASYNC_NULL_PARAMETER -6
  135. /**
  136. * Return code: The topic has been truncated (the topic string includes
  137. * embedded NULL characters). String functions will not access the full topic.
  138. * Use the topic length value to access the full topic.
  139. */
  140. #define MQTTASYNC_TOPICNAME_TRUNCATED -7
  141. /**
  142. * Return code: A structure parameter does not have the correct eyecatcher
  143. * and version number.
  144. */
  145. #define MQTTASYNC_BAD_STRUCTURE -8
  146. /**
  147. * Return code: A qos parameter is not 0, 1 or 2
  148. */
  149. #define MQTTASYNC_BAD_QOS -9
  150. /**
  151. * Return code: All 65535 MQTT msgids are being used
  152. */
  153. #define MQTTASYNC_NO_MORE_MSGIDS -10
  154. /**
  155. * Return code: the request is being discarded when not complete
  156. */
  157. #define MQTTASYNC_OPERATION_INCOMPLETE -11
  158. /**
  159. * Return code: no more messages can be buffered
  160. */
  161. #define MQTTASYNC_MAX_BUFFERED_MESSAGES -12
  162. /**
  163. * Return code: Attempting SSL connection using non-SSL version of library
  164. */
  165. #define MQTTASYNC_SSL_NOT_SUPPORTED -13
  166. /**
  167. * Return code: protocol prefix in serverURI should be:
  168. * @li @em tcp:// or @em mqtt:// - Insecure TCP
  169. * @li @em ssl:// or @em mqtts:// - Encrypted SSL/TLS
  170. * @li @em ws:// - Insecure websockets
  171. * @li @em wss:// - Secure web sockets
  172. *
  173. * The TLS enabled prefixes (ssl, mqtts, wss) are only valid if the TLS
  174. * version of the library is linked with.
  175. */
  176. #define MQTTASYNC_BAD_PROTOCOL -14
  177. /**
  178. * Return code: don't use options for another version of MQTT
  179. */
  180. #define MQTTASYNC_BAD_MQTT_OPTION -15
  181. /**
  182. * Return code: call not applicable to the client's version of MQTT
  183. */
  184. #define MQTTASYNC_WRONG_MQTT_VERSION -16
  185. /**
  186. * Return code: 0 length will topic
  187. */
  188. #define MQTTASYNC_0_LEN_WILL_TOPIC -17
  189. /*
  190. * Return code: connect or disconnect command ignored because there is already a connect or disconnect
  191. * command at the head of the list waiting to be processed. Use the onSuccess/onFailure callbacks to wait
  192. * for the previous connect or disconnect command to be complete.
  193. */
  194. #define MQTTASYNC_COMMAND_IGNORED -18
  195. /*
  196. * Return code: maxBufferedMessages in the connect options must be >= 0
  197. */
  198. #define MQTTASYNC_MAX_BUFFERED -19
  199. /**
  200. * Default MQTT version to connect with. Use 3.1.1 then fall back to 3.1
  201. */
  202. #define MQTTVERSION_DEFAULT 0
  203. /**
  204. * MQTT version to connect with: 3.1
  205. */
  206. #define MQTTVERSION_3_1 3
  207. /**
  208. * MQTT version to connect with: 3.1.1
  209. */
  210. #define MQTTVERSION_3_1_1 4
  211. /**
  212. * MQTT version to connect with: 5
  213. */
  214. #define MQTTVERSION_5 5
  215. /**
  216. * Bad return code from subscribe, as defined in the 3.1.1 specification
  217. */
  218. #define MQTT_BAD_SUBSCRIBE 0x80
  219. /**
  220. * Initialization options
  221. */
  222. typedef struct
  223. {
  224. /** The eyecatcher for this structure. Must be MQTG. */
  225. char struct_id[4];
  226. /** The version number of this structure. Must be 0 */
  227. int struct_version;
  228. /** 1 = we do openssl init, 0 = leave it to the application */
  229. int do_openssl_init;
  230. } MQTTAsync_init_options;
  231. #define MQTTAsync_init_options_initializer { {'M', 'Q', 'T', 'G'}, 0, 0 }
  232. /**
  233. * Global init of mqtt library. Call once on program start to set global behaviour.
  234. * handle_openssl_init - if mqtt library should handle openssl init (1) or rely on the caller to init it before using mqtt (0)
  235. */
  236. LIBMQTT_API void MQTTAsync_global_init(MQTTAsync_init_options* inits);
  237. /**
  238. * A handle representing an MQTT client. A valid client handle is available
  239. * following a successful call to MQTTAsync_create().
  240. */
  241. typedef void* MQTTAsync;
  242. /**
  243. * A value representing an MQTT message. A token is returned to the
  244. * client application when a message is published. The token can then be used to
  245. * check that the message was successfully delivered to its destination (see
  246. * MQTTAsync_publish(),
  247. * MQTTAsync_publishMessage(),
  248. * MQTTAsync_deliveryComplete(), and
  249. * MQTTAsync_getPendingTokens()).
  250. */
  251. typedef int MQTTAsync_token;
  252. /**
  253. * A structure representing the payload and attributes of an MQTT message. The
  254. * message topic is not part of this structure (see MQTTAsync_publishMessage(),
  255. * MQTTAsync_publish(), MQTTAsync_receive(), MQTTAsync_freeMessage()
  256. * and MQTTAsync_messageArrived()).
  257. */
  258. typedef struct
  259. {
  260. /** The eyecatcher for this structure. must be MQTM. */
  261. char struct_id[4];
  262. /** The version number of this structure. Must be 0 or 1.
  263. * 0 indicates no message properties */
  264. int struct_version;
  265. /** The length of the MQTT message payload in bytes. */
  266. int payloadlen;
  267. /** A pointer to the payload of the MQTT message. */
  268. void* payload;
  269. /**
  270. * The quality of service (QoS) assigned to the message.
  271. * There are three levels of QoS:
  272. * <DL>
  273. * <DT><B>QoS0</B></DT>
  274. * <DD>Fire and forget - the message may not be delivered</DD>
  275. * <DT><B>QoS1</B></DT>
  276. * <DD>At least once - the message will be delivered, but may be
  277. * delivered more than once in some circumstances.</DD>
  278. * <DT><B>QoS2</B></DT>
  279. * <DD>Once and one only - the message will be delivered exactly once.</DD>
  280. * </DL>
  281. */
  282. int qos;
  283. /**
  284. * The retained flag serves two purposes depending on whether the message
  285. * it is associated with is being published or received.
  286. *
  287. * <b>retained = true</b><br>
  288. * For messages being published, a true setting indicates that the MQTT
  289. * server should retain a copy of the message. The message will then be
  290. * transmitted to new subscribers to a topic that matches the message topic.
  291. * For subscribers registering a new subscription, the flag being true
  292. * indicates that the received message is not a new one, but one that has
  293. * been retained by the MQTT server.
  294. *
  295. * <b>retained = false</b> <br>
  296. * For publishers, this indicates that this message should not be retained
  297. * by the MQTT server. For subscribers, a false setting indicates this is
  298. * a normal message, received as a result of it being published to the
  299. * server.
  300. */
  301. int retained;
  302. /**
  303. * The dup flag indicates whether or not this message is a duplicate.
  304. * It is only meaningful when receiving QoS1 messages. When true, the
  305. * client application should take appropriate action to deal with the
  306. * duplicate message. This is an output parameter only.
  307. */
  308. int dup;
  309. /** The message identifier is reserved for internal use by the
  310. * MQTT client and server. It is an output parameter only - writing
  311. * to it will serve no purpose. It contains the MQTT message id of
  312. * an incoming publish message.
  313. */
  314. int msgid;
  315. /**
  316. * The MQTT V5 properties associated with the message.
  317. */
  318. MQTTProperties properties;
  319. } MQTTAsync_message;
  320. #define MQTTAsync_message_initializer { {'M', 'Q', 'T', 'M'}, 1, 0, NULL, 0, 0, 0, 0, MQTTProperties_initializer }
  321. /**
  322. * This is a callback function. The client application
  323. * must provide an implementation of this function to enable asynchronous
  324. * receipt of messages. The function is registered with the client library by
  325. * passing it as an argument to MQTTAsync_setCallbacks(). It is
  326. * called by the client library when a new message that matches a client
  327. * subscription has been received from the server. This function is executed on
  328. * a separate thread to the one on which the client application is running.
  329. *
  330. * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
  331. * called within this callback.
  332. * @param context A pointer to the <i>context</i> value originally passed to
  333. * MQTTAsync_setCallbacks(), which contains any application-specific context.
  334. * @param topicName The topic associated with the received message.
  335. * @param topicLen The length of the topic if there are one
  336. * more NULL characters embedded in <i>topicName</i>, otherwise <i>topicLen</i>
  337. * is 0. If <i>topicLen</i> is 0, the value returned by <i>strlen(topicName)</i>
  338. * can be trusted. If <i>topicLen</i> is greater than 0, the full topic name
  339. * can be retrieved by accessing <i>topicName</i> as a byte array of length
  340. * <i>topicLen</i>.
  341. * @param message The MQTTAsync_message structure for the received message.
  342. * This structure contains the message payload and attributes.
  343. * @return This function must return 0 or 1 indicating whether or not
  344. * the message has been safely received by the client application. <br>
  345. * Returning 1 indicates that the message has been successfully handled.
  346. * To free the message storage, ::MQTTAsync_freeMessage must be called.
  347. * To free the topic name storage, ::MQTTAsync_free must be called.<br>
  348. * Returning 0 indicates that there was a problem. In this
  349. * case, the client library will reinvoke MQTTAsync_messageArrived() to
  350. * attempt to deliver the message to the application again.
  351. * Do not free the message and topic storage when returning 0, otherwise
  352. * the redelivery will fail.
  353. */
  354. typedef int MQTTAsync_messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message);
  355. /**
  356. * This is a callback function. The client application
  357. * must provide an implementation of this function to enable asynchronous
  358. * notification of delivery of messages to the server. The function is
  359. * registered with the client library by passing it as an argument to MQTTAsync_setCallbacks().
  360. * It is called by the client library after the client application has
  361. * published a message to the server. It indicates that the necessary
  362. * handshaking and acknowledgements for the requested quality of service (see
  363. * MQTTAsync_message.qos) have been completed. This function is executed on a
  364. * separate thread to the one on which the client application is running.
  365. *
  366. * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
  367. * called within this callback.
  368. * @param context A pointer to the <i>context</i> value originally passed to
  369. * MQTTAsync_setCallbacks(), which contains any application-specific context.
  370. * @param token The ::MQTTAsync_token associated with
  371. * the published message. Applications can check that all messages have been
  372. * correctly published by matching the tokens returned from calls to
  373. * MQTTAsync_send() and MQTTAsync_sendMessage() with the tokens passed
  374. * to this callback.
  375. */
  376. typedef void MQTTAsync_deliveryComplete(void* context, MQTTAsync_token token);
  377. /**
  378. * This is a callback function. The client application
  379. * must provide an implementation of this function to enable asynchronous
  380. * notification of the loss of connection to the server. The function is
  381. * registered with the client library by passing it as an argument to
  382. * MQTTAsync_setCallbacks(). It is called by the client library if the client
  383. * loses its connection to the server. The client application must take
  384. * appropriate action, such as trying to reconnect or reporting the problem.
  385. * This function is executed on a separate thread to the one on which the
  386. * client application is running.
  387. *
  388. * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
  389. * called within this callback.
  390. * @param context A pointer to the <i>context</i> value originally passed to
  391. * MQTTAsync_setCallbacks(), which contains any application-specific context.
  392. * @param cause The reason for the disconnection.
  393. * Currently, <i>cause</i> is always set to NULL.
  394. */
  395. typedef void MQTTAsync_connectionLost(void* context, char* cause);
  396. /**
  397. * This is a callback function, which will be called when the client
  398. * library successfully connects. This is superfluous when the connection
  399. * is made in response to a MQTTAsync_connect call, because the onSuccess
  400. * callback can be used. It is intended for use when automatic reconnect
  401. * is enabled, so that when a reconnection attempt succeeds in the background,
  402. * the application is notified and can take any required actions.
  403. *
  404. * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
  405. * called within this callback.
  406. * @param context A pointer to the <i>context</i> value originally passed to
  407. * MQTTAsync_setCallbacks(), which contains any application-specific context.
  408. * @param cause The reason for the disconnection.
  409. * Currently, <i>cause</i> is always set to NULL.
  410. */
  411. typedef void MQTTAsync_connected(void* context, char* cause);
  412. /**
  413. * This is a callback function, which will be called when the client
  414. * library receives a disconnect packet from the server. This applies to MQTT V5 and above only.
  415. *
  416. * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
  417. * called within this callback.
  418. * @param context A pointer to the <i>context</i> value originally passed to
  419. * MQTTAsync_setCallbacks(), which contains any application-specific context.
  420. * @param properties the properties in the disconnect packet.
  421. * @param reasonCode the reason code from the disconnect packet
  422. */
  423. typedef void MQTTAsync_disconnected(void* context, MQTTProperties* properties,
  424. enum MQTTReasonCodes reasonCode);
  425. /**
  426. * Sets the MQTTAsync_disconnected() callback function for a client.
  427. * @param handle A valid client handle from a successful call to
  428. * MQTTAsync_create().
  429. *
  430. * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
  431. * called within this callback.
  432. * @param context A pointer to any application-specific context. The
  433. * the <i>context</i> pointer is passed to each of the callback functions to
  434. * provide access to the context information in the callback.
  435. * @param co A pointer to an MQTTAsync_connected() callback
  436. * function. NULL removes the callback setting.
  437. * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
  438. * ::MQTTASYNC_FAILURE if an error occurred.
  439. */
  440. LIBMQTT_API int MQTTAsync_setDisconnected(MQTTAsync handle, void* context, MQTTAsync_disconnected* co);
  441. /** The connect options that can be updated before an automatic reconnect. */
  442. typedef struct
  443. {
  444. /** The eyecatcher for this structure. Will be MQCD. */
  445. char struct_id[4];
  446. /** The version number of this structure. Will be 0 */
  447. int struct_version;
  448. /**
  449. * MQTT servers that support the MQTT v3.1 protocol provide authentication
  450. * and authorisation by user name and password. This is the user name parameter.
  451. * Set data to NULL to remove. To change, allocate new
  452. * storage with ::MQTTAsync_allocate - this will then be free later by the library.
  453. */
  454. const char* username;
  455. /**
  456. * The password parameter of the MQTT authentication.
  457. * Set data to NULL to remove. To change, allocate new
  458. * storage with ::MQTTAsync_allocate - this will then be free later by the library.
  459. */
  460. struct {
  461. int len; /**< binary password length */
  462. const void* data; /**< binary password data */
  463. } binarypwd;
  464. } MQTTAsync_connectData;
  465. #define MQTTAsync_connectData_initializer {{'M', 'Q', 'C', 'D'}, 0, NULL, {0, NULL}}
  466. /**
  467. * This is a callback function which will allow the client application to update the
  468. * connection data.
  469. * @param data The connection data which can be modified by the application.
  470. * @return Return a non-zero value to update the connect data, zero to keep the same data.
  471. */
  472. typedef int MQTTAsync_updateConnectOptions(void* context, MQTTAsync_connectData* data);
  473. /**
  474. * Sets the MQTTAsync_updateConnectOptions() callback function for a client.
  475. * @param handle A valid client handle from a successful call to MQTTAsync_create().
  476. * @param context A pointer to any application-specific context. The
  477. * the <i>context</i> pointer is passed to each of the callback functions to
  478. * provide access to the context information in the callback.
  479. * @param co A pointer to an MQTTAsync_updateConnectOptions() callback
  480. * function. NULL removes the callback setting.
  481. */
  482. LIBMQTT_API int MQTTAsync_setUpdateConnectOptions(MQTTAsync handle, void* context, MQTTAsync_updateConnectOptions* co);
  483. #if !defined(NO_PERSISTENCE)
  484. /**
  485. * Sets the MQTTPersistence_beforeWrite() callback function for a client.
  486. * @param handle A valid client handle from a successful call to MQTTAsync_create().
  487. * @param context A pointer to any application-specific context. The
  488. * the <i>context</i> pointer is passed to the callback function to
  489. * provide access to the context information in the callback.
  490. * @param co A pointer to an MQTTPersistence_beforeWrite() callback
  491. * function. NULL removes the callback setting.
  492. */
  493. LIBMQTT_API int MQTTAsync_setBeforePersistenceWrite(MQTTAsync handle, void* context, MQTTPersistence_beforeWrite* co);
  494. /**
  495. * Sets the MQTTPersistence_afterRead() callback function for a client.
  496. * @param handle A valid client handle from a successful call to MQTTAsync_create().
  497. * @param context A pointer to any application-specific context. The
  498. * the <i>context</i> pointer is passed to the callback function to
  499. * provide access to the context information in the callback.
  500. * @param co A pointer to an MQTTPersistence_beforeWrite() callback
  501. * function. NULL removes the callback setting.
  502. */
  503. LIBMQTT_API int MQTTAsync_setAfterPersistenceRead(MQTTAsync handle, void* context, MQTTPersistence_afterRead* co);
  504. #endif
  505. /** The data returned on completion of an unsuccessful API call in the response callback onFailure. */
  506. typedef struct
  507. {
  508. /** A token identifying the failed request. */
  509. MQTTAsync_token token;
  510. /** A numeric code identifying the error. */
  511. int code;
  512. /** Optional text explaining the error. Can be NULL. */
  513. const char *message;
  514. } MQTTAsync_failureData;
  515. /** The data returned on completion of an unsuccessful API call in the response callback onFailure. */
  516. typedef struct
  517. {
  518. /** The eyecatcher for this structure. Will be MQFD. */
  519. char struct_id[4];
  520. /** The version number of this structure. Will be 0 */
  521. int struct_version;
  522. /** A token identifying the failed request. */
  523. MQTTAsync_token token;
  524. /** The MQTT reason code returned. */
  525. enum MQTTReasonCodes reasonCode;
  526. /** The MQTT properties on the ack, if any. */
  527. MQTTProperties properties;
  528. /** A numeric code identifying the MQTT client library error. */
  529. int code;
  530. /** Optional further text explaining the error. Can be NULL. */
  531. const char *message;
  532. /** Packet type on which the failure occurred - used for publish QoS 1/2 exchanges*/
  533. int packet_type;
  534. } MQTTAsync_failureData5;
  535. #define MQTTAsync_failureData5_initializer {{'M', 'Q', 'F', 'D'}, 0, 0, MQTTREASONCODE_SUCCESS, MQTTProperties_initializer, 0, NULL, 0}
  536. /** The data returned on completion of a successful API call in the response callback onSuccess. */
  537. typedef struct
  538. {
  539. /** A token identifying the successful request. Can be used to refer to the request later. */
  540. MQTTAsync_token token;
  541. /** A union of the different values that can be returned for subscribe, unsubscribe and publish. */
  542. union
  543. {
  544. /** For subscribe, the granted QoS of the subscription returned by the server.
  545. * Also for subscribeMany, if only 1 subscription was requested. */
  546. int qos;
  547. /** For subscribeMany, if more than one subscription was requested,
  548. * the list of granted QoSs of the subscriptions returned by the server. */
  549. int* qosList;
  550. /** For publish, the message being sent to the server. */
  551. struct
  552. {
  553. MQTTAsync_message message; /**< the message being sent to the server */
  554. char* destinationName; /**< the topic destination for the message */
  555. } pub;
  556. /* For connect, the server connected to, MQTT version used, and sessionPresent flag */
  557. struct
  558. {
  559. char* serverURI; /**< the connection string of the server */
  560. int MQTTVersion; /**< the version of MQTT being used */
  561. int sessionPresent; /**< the session present flag returned from the server */
  562. } connect;
  563. } alt;
  564. } MQTTAsync_successData;
  565. /** The data returned on completion of a successful API call in the response callback onSuccess. */
  566. typedef struct
  567. {
  568. char struct_id[4]; /**< The eyecatcher for this structure. Will be MQSD. */
  569. int struct_version; /**< The version number of this structure. Will be 0 */
  570. /** A token identifying the successful request. Can be used to refer to the request later. */
  571. MQTTAsync_token token;
  572. enum MQTTReasonCodes reasonCode; /**< MQTT V5 reason code returned */
  573. MQTTProperties properties; /**< MQTT V5 properties returned, if any */
  574. /** A union of the different values that can be returned for subscribe, unsubscribe and publish. */
  575. union
  576. {
  577. /** For subscribeMany, the list of reasonCodes returned by the server. */
  578. struct
  579. {
  580. int reasonCodeCount; /**< the number of reason codes in the reasonCodes array */
  581. enum MQTTReasonCodes* reasonCodes; /**< an array of reasonCodes */
  582. } sub;
  583. /** For publish, the message being sent to the server. */
  584. struct
  585. {
  586. MQTTAsync_message message; /**< the message being sent to the server */
  587. char* destinationName; /**< the topic destination for the message */
  588. } pub;
  589. /* For connect, the server connected to, MQTT version used, and sessionPresent flag */
  590. struct
  591. {
  592. char* serverURI; /**< the connection string of the server */
  593. int MQTTVersion; /**< the version of MQTT being used */
  594. int sessionPresent; /**< the session present flag returned from the server */
  595. } connect;
  596. /** For unsubscribeMany, the list of reasonCodes returned by the server. */
  597. struct
  598. {
  599. int reasonCodeCount; /**< the number of reason codes in the reasonCodes array */
  600. enum MQTTReasonCodes* reasonCodes; /**< an array of reasonCodes */
  601. } unsub;
  602. } alt;
  603. } MQTTAsync_successData5;
  604. #define MQTTAsync_successData5_initializer {{'M', 'Q', 'S', 'D'}, 0, 0, MQTTREASONCODE_SUCCESS, MQTTProperties_initializer, {.sub={0,0}}}
  605. /**
  606. * This is a callback function. The client application
  607. * must provide an implementation of this function to enable asynchronous
  608. * notification of the successful completion of an API call. The function is
  609. * registered with the client library by passing it as an argument in
  610. * ::MQTTAsync_responseOptions.
  611. *
  612. * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
  613. * called within this callback.
  614. * @param context A pointer to the <i>context</i> value originally passed to
  615. * ::MQTTAsync_responseOptions, which contains any application-specific context.
  616. * @param response Any success data associated with the API completion.
  617. */
  618. typedef void MQTTAsync_onSuccess(void* context, MQTTAsync_successData* response);
  619. /**
  620. * This is a callback function, the MQTT V5 version of ::MQTTAsync_onSuccess.
  621. * The client application
  622. * must provide an implementation of this function to enable asynchronous
  623. * notification of the successful completion of an API call. The function is
  624. * registered with the client library by passing it as an argument in
  625. * ::MQTTAsync_responseOptions.
  626. *
  627. * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
  628. * called within this callback.
  629. * @param context A pointer to the <i>context</i> value originally passed to
  630. * ::MQTTAsync_responseOptions, which contains any application-specific context.
  631. * @param response Any success data associated with the API completion.
  632. */
  633. typedef void MQTTAsync_onSuccess5(void* context, MQTTAsync_successData5* response);
  634. /**
  635. * This is a callback function. The client application
  636. * must provide an implementation of this function to enable asynchronous
  637. * notification of the unsuccessful completion of an API call. The function is
  638. * registered with the client library by passing it as an argument in
  639. * ::MQTTAsync_responseOptions.
  640. *
  641. * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
  642. * called within this callback.
  643. * @param context A pointer to the <i>context</i> value originally passed to
  644. * ::MQTTAsync_responseOptions, which contains any application-specific context.
  645. * @param response Failure data associated with the API completion.
  646. */
  647. typedef void MQTTAsync_onFailure(void* context, MQTTAsync_failureData* response);
  648. /**
  649. * This is a callback function, the MQTT V5 version of ::MQTTAsync_onFailure.
  650. * The application must provide an implementation of this function to enable asynchronous
  651. * notification of the unsuccessful completion of an API call. The function is
  652. * registered with the client library by passing it as an argument in
  653. * ::MQTTAsync_responseOptions.
  654. *
  655. * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
  656. * called within this callback.
  657. * @param context A pointer to the <i>context</i> value originally passed to
  658. * ::MQTTAsync_responseOptions, which contains any application-specific context.
  659. * @param response Failure data associated with the API completion.
  660. */
  661. typedef void MQTTAsync_onFailure5(void* context, MQTTAsync_failureData5* response);
  662. /** Structure to define call options. For MQTT 5.0 there is input data as well as that
  663. * describing the response method. So there is now also a synonym ::MQTTAsync_callOptions
  664. * to better reflect the use. This responseOptions name is kept for backward
  665. * compatibility.
  666. */
  667. typedef struct MQTTAsync_responseOptions
  668. {
  669. /** The eyecatcher for this structure. Must be MQTR */
  670. char struct_id[4];
  671. /** The version number of this structure. Must be 0 or 1
  672. * if 0, no MQTTV5 options */
  673. int struct_version;
  674. /**
  675. * A pointer to a callback function to be called if the API call successfully
  676. * completes. Can be set to NULL, in which case no indication of successful
  677. * completion will be received.
  678. */
  679. MQTTAsync_onSuccess* onSuccess;
  680. /**
  681. * A pointer to a callback function to be called if the API call fails.
  682. * Can be set to NULL, in which case no indication of unsuccessful
  683. * completion will be received.
  684. */
  685. MQTTAsync_onFailure* onFailure;
  686. /**
  687. * A pointer to any application-specific context. The
  688. * the <i>context</i> pointer is passed to success or failure callback functions to
  689. * provide access to the context information in the callback.
  690. */
  691. void* context;
  692. /**
  693. * A token is returned from the call. It can be used to track
  694. * the state of this request, both in the callbacks and in future calls
  695. * such as ::MQTTAsync_waitForCompletion. This is output only - any
  696. * change by the application will be ignored.
  697. */
  698. MQTTAsync_token token;
  699. /**
  700. * A pointer to a callback function to be called if the API call successfully
  701. * completes. Can be set to NULL, in which case no indication of successful
  702. * completion will be received.
  703. */
  704. MQTTAsync_onSuccess5* onSuccess5;
  705. /**
  706. * A pointer to a callback function to be called if the API call successfully
  707. * completes. Can be set to NULL, in which case no indication of successful
  708. * completion will be received.
  709. */
  710. MQTTAsync_onFailure5* onFailure5;
  711. /**
  712. * MQTT V5 input properties
  713. */
  714. MQTTProperties properties;
  715. /*
  716. * MQTT V5 subscribe options, when used with subscribe only.
  717. */
  718. MQTTSubscribe_options subscribeOptions;
  719. /*
  720. * MQTT V5 subscribe option count, when used with subscribeMany only.
  721. * The number of entries in the subscribe_options_list array.
  722. */
  723. int subscribeOptionsCount;
  724. /*
  725. * MQTT V5 subscribe option array, when used with subscribeMany only.
  726. */
  727. MQTTSubscribe_options* subscribeOptionsList;
  728. } MQTTAsync_responseOptions;
  729. #define MQTTAsync_responseOptions_initializer { {'M', 'Q', 'T', 'R'}, 1, NULL, NULL, 0, 0, NULL, NULL, MQTTProperties_initializer, MQTTSubscribe_options_initializer, 0, NULL}
  730. /** A synonym for responseOptions to better reflect its usage since MQTT 5.0 */
  731. typedef struct MQTTAsync_responseOptions MQTTAsync_callOptions;
  732. #define MQTTAsync_callOptions_initializer MQTTAsync_responseOptions_initializer
  733. /**
  734. * This function sets the global callback functions for a specific client.
  735. * If your client application doesn't use a particular callback, set the
  736. * relevant parameter to NULL (except for message arrived, which must be given).
  737. * Any necessary message acknowledgements and status communications are handled
  738. * in the background without any intervention
  739. * from the client application.
  740. *
  741. * <b>Note:</b> The MQTT client must be disconnected when this function is
  742. * called.
  743. * @param handle A valid client handle from a successful call to
  744. * MQTTAsync_create().
  745. * @param context A pointer to any application-specific context. The
  746. * the <i>context</i> pointer is passed to each of the callback functions to
  747. * provide access to the context information in the callback.
  748. * @param cl A pointer to an MQTTAsync_connectionLost() callback
  749. * function. You can set this to NULL if your application doesn't handle
  750. * disconnections.
  751. * @param ma A pointer to an MQTTAsync_messageArrived() callback
  752. * function. If this callback is not set, an error will be returned.
  753. * You must set this callback because otherwise there would be
  754. * no way to deliver any incoming messages.
  755. * @param dc A pointer to an MQTTAsync_deliveryComplete() callback
  756. * function. You can set this to NULL if you do not want to check
  757. * for successful delivery.
  758. * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
  759. * ::MQTTASYNC_FAILURE if an error occurred.
  760. */
  761. LIBMQTT_API int MQTTAsync_setCallbacks(MQTTAsync handle, void* context, MQTTAsync_connectionLost* cl,
  762. MQTTAsync_messageArrived* ma, MQTTAsync_deliveryComplete* dc);
  763. /**
  764. * This function sets the callback function for a connection lost event for
  765. * a specific client. Any necessary message acknowledgements and status
  766. * communications are handled in the background without any intervention
  767. * from the client application.
  768. *
  769. * <b>Note:</b> The MQTT client must be disconnected when this function is
  770. * called.
  771. * @param handle A valid client handle from a successful call to
  772. * MQTTAsync_create().
  773. * @param context A pointer to any application-specific context. The
  774. * the <i>context</i> pointer is passed the callback functions to provide
  775. * access to the context information in the callback.
  776. * @param cl A pointer to an MQTTAsync_connectionLost() callback
  777. * function. You can set this to NULL if your application doesn't handle
  778. * disconnections.
  779. * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
  780. * ::MQTTASYNC_FAILURE if an error occurred.
  781. */
  782. LIBMQTT_API int MQTTAsync_setConnectionLostCallback(MQTTAsync handle, void* context,
  783. MQTTAsync_connectionLost* cl);
  784. /**
  785. * This function sets the callback function for a message arrived event for
  786. * a specific client. Any necessary message acknowledgements and status
  787. * communications are handled in the background without any intervention
  788. * from the client application. If you do not set a messageArrived callback
  789. * function, you will not be notified of the receipt of any messages as a
  790. * result of a subscription.
  791. *
  792. * <b>Note:</b> The MQTT client must be disconnected when this function is
  793. * called.
  794. * @param handle A valid client handle from a successful call to
  795. * MQTTAsync_create().
  796. * @param context A pointer to any application-specific context. The
  797. * the <i>context</i> pointer is passed to the callback functions to provide
  798. * access to the context information in the callback.
  799. * @param ma A pointer to an MQTTAsync_messageArrived() callback
  800. * function. You can set this to NULL if your application doesn't handle
  801. * receipt of messages.
  802. * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
  803. * ::MQTTASYNC_FAILURE if an error occurred.
  804. */
  805. LIBMQTT_API int MQTTAsync_setMessageArrivedCallback(MQTTAsync handle, void* context,
  806. MQTTAsync_messageArrived* ma);
  807. /**
  808. * This function sets the callback function for a delivery complete event
  809. * for a specific client. Any necessary message acknowledgements and status
  810. * communications are handled in the background without any intervention
  811. * from the client application.
  812. *
  813. * <b>Note:</b> The MQTT client must be disconnected when this function is
  814. * called.
  815. * @param handle A valid client handle from a successful call to
  816. * MQTTAsync_create().
  817. * @param context A pointer to any application-specific context. The
  818. * the <i>context</i> pointer is passed to the callback functions to provide
  819. * access to the context information in the callback.
  820. * @param dc A pointer to an MQTTAsync_deliveryComplete() callback
  821. * function. You can set this to NULL if you do not want to check
  822. * for successful delivery.
  823. * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
  824. * ::MQTTASYNC_FAILURE if an error occurred.
  825. */
  826. LIBMQTT_API int MQTTAsync_setDeliveryCompleteCallback(MQTTAsync handle, void* context,
  827. MQTTAsync_deliveryComplete* dc);
  828. /**
  829. * Sets the MQTTAsync_connected() callback function for a client.
  830. * @param handle A valid client handle from a successful call to
  831. * MQTTAsync_create().
  832. * @param context A pointer to any application-specific context. The
  833. * the <i>context</i> pointer is passed to each of the callback functions to
  834. * provide access to the context information in the callback.
  835. * @param co A pointer to an MQTTAsync_connected() callback
  836. * function. NULL removes the callback setting.
  837. * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
  838. * ::MQTTASYNC_FAILURE if an error occurred.
  839. */
  840. LIBMQTT_API int MQTTAsync_setConnected(MQTTAsync handle, void* context, MQTTAsync_connected* co);
  841. /**
  842. * Reconnects a client with the previously used connect options. Connect
  843. * must have previously been called for this to work.
  844. * @param handle A valid client handle from a successful call to
  845. * MQTTAsync_create().
  846. * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
  847. * ::MQTTASYNC_FAILURE if an error occurred.
  848. */
  849. LIBMQTT_API int MQTTAsync_reconnect(MQTTAsync handle);
  850. /**
  851. * This function creates an MQTT client ready for connection to the
  852. * specified server and using the specified persistent storage (see
  853. * MQTTAsync_persistence). See also MQTTAsync_destroy().
  854. * @param handle A pointer to an ::MQTTAsync handle. The handle is
  855. * populated with a valid client reference following a successful return from
  856. * this function.
  857. * @param serverURI A null-terminated string specifying the server to
  858. * which the client will connect. It takes the form
  859. * <i>protocol://host:port</i> where <i>protocol</i> must be:
  860. * <br>
  861. * @em tcp:// or @em mqtt:// - Insecure TCP
  862. * <br>
  863. * @em ssl:// or @em mqtts:// - Encrypted SSL/TLS
  864. * <br>
  865. * @em ws:// - Insecure websockets
  866. * <br>
  867. * @em wss:// - Secure web sockets
  868. * <br>
  869. * The TLS enabled prefixes (ssl, mqtts, wss) are only valid if a TLS
  870. * version of the library is linked with.
  871. * For <i>host</i>, you can specify either an IP address or a host name. For
  872. * instance, to connect to a server running on the local machines with the
  873. * default MQTT port, specify <i>tcp://localhost:1883</i>.
  874. * @param clientId The client identifier passed to the server when the
  875. * client connects to it. It is a null-terminated UTF-8 encoded string.
  876. * @param persistence_type The type of persistence to be used by the client:
  877. * <br>
  878. * ::MQTTCLIENT_PERSISTENCE_NONE: Use in-memory persistence. If the device or
  879. * system on which the client is running fails or is switched off, the current
  880. * state of any in-flight messages is lost and some messages may not be
  881. * delivered even at QoS1 and QoS2.
  882. * <br>
  883. * ::MQTTCLIENT_PERSISTENCE_DEFAULT: Use the default (file system-based)
  884. * persistence mechanism. Status about in-flight messages is held in persistent
  885. * storage and provides some protection against message loss in the case of
  886. * unexpected failure.
  887. * <br>
  888. * ::MQTTCLIENT_PERSISTENCE_USER: Use an application-specific persistence
  889. * implementation. Using this type of persistence gives control of the
  890. * persistence mechanism to the application. The application has to implement
  891. * the MQTTClient_persistence interface.
  892. * @param persistence_context If the application uses
  893. * ::MQTTCLIENT_PERSISTENCE_NONE persistence, this argument is unused and should
  894. * be set to NULL. For ::MQTTCLIENT_PERSISTENCE_DEFAULT persistence, it
  895. * should be set to the location of the persistence directory (if set
  896. * to NULL, the persistence directory used is the working directory).
  897. * Applications that use ::MQTTCLIENT_PERSISTENCE_USER persistence set this
  898. * argument to point to a valid MQTTClient_persistence structure.
  899. * @return ::MQTTASYNC_SUCCESS if the client is successfully created, otherwise
  900. * an error code is returned.
  901. */
  902. LIBMQTT_API int MQTTAsync_create(MQTTAsync* handle, const char* serverURI, const char* clientId,
  903. int persistence_type, void* persistence_context);
  904. /** Options for the ::MQTTAsync_createWithOptions call */
  905. typedef struct
  906. {
  907. /** The eyecatcher for this structure. must be MQCO. */
  908. char struct_id[4];
  909. /** The version number of this structure. Must be 0, 1, 2 or 3
  910. * 0 means no MQTTVersion
  911. * 1 means no allowDisconnectedSendAtAnyTime, deleteOldestMessages, restoreMessages
  912. * 2 means no persistQoS0
  913. */
  914. int struct_version;
  915. /** Whether to allow messages to be sent when the client library is not connected. */
  916. int sendWhileDisconnected;
  917. /** The maximum number of messages allowed to be buffered. This is intended to be used to
  918. * limit the number of messages queued while the client is not connected. It also applies
  919. * when the client is connected, however, so has to be greater than 0. */
  920. int maxBufferedMessages;
  921. /** Whether the MQTT version is 3.1, 3.1.1, or 5. To use V5, this must be set.
  922. * MQTT V5 has to be chosen here, because during the create call the message persistence
  923. * is initialized, and we want to know whether the format of any persisted messages
  924. * is appropriate for the MQTT version we are going to connect with. Selecting 3.1 or
  925. * 3.1.1 and attempting to read 5.0 persisted messages will result in an error on create. */
  926. int MQTTVersion;
  927. /**
  928. * Allow sending of messages while disconnected before a first successful connect.
  929. */
  930. int allowDisconnectedSendAtAnyTime;
  931. /*
  932. * When the maximum number of buffered messages is reached, delete the oldest rather than the newest.
  933. */
  934. int deleteOldestMessages;
  935. /*
  936. * Restore messages from persistence on create - or clear it.
  937. */
  938. int restoreMessages;
  939. /*
  940. * Persist QoS0 publish commands - an option to not persist them.
  941. */
  942. int persistQoS0;
  943. } MQTTAsync_createOptions;
  944. #define MQTTAsync_createOptions_initializer { {'M', 'Q', 'C', 'O'}, 2, 0, 100, MQTTVERSION_DEFAULT, 0, 0, 1, 1}
  945. #define MQTTAsync_createOptions_initializer5 { {'M', 'Q', 'C', 'O'}, 2, 0, 100, MQTTVERSION_5, 0, 0, 1, 1}
  946. LIBMQTT_API int MQTTAsync_createWithOptions(MQTTAsync* handle, const char* serverURI, const char* clientId,
  947. int persistence_type, void* persistence_context, MQTTAsync_createOptions* options);
  948. /**
  949. * MQTTAsync_willOptions defines the MQTT "Last Will and Testament" (LWT) settings for
  950. * the client. In the event that a client unexpectedly loses its connection to
  951. * the server, the server publishes the LWT message to the LWT topic on
  952. * behalf of the client. This allows other clients (subscribed to the LWT topic)
  953. * to be made aware that the client has disconnected. To enable the LWT
  954. * function for a specific client, a valid pointer to an MQTTAsync_willOptions
  955. * structure is passed in the MQTTAsync_connectOptions structure used in the
  956. * MQTTAsync_connect() call that connects the client to the server. The pointer
  957. * to MQTTAsync_willOptions can be set to NULL if the LWT function is not
  958. * required.
  959. */
  960. typedef struct
  961. {
  962. /** The eyecatcher for this structure. must be MQTW. */
  963. char struct_id[4];
  964. /** The version number of this structure. Must be 0 or 1
  965. 0 indicates no binary will message support
  966. */
  967. int struct_version;
  968. /** The LWT topic to which the LWT message will be published. */
  969. const char* topicName;
  970. /** The LWT payload. */
  971. const char* message;
  972. /**
  973. * The retained flag for the LWT message (see MQTTAsync_message.retained).
  974. */
  975. int retained;
  976. /**
  977. * The quality of service setting for the LWT message (see
  978. * MQTTAsync_message.qos and @ref qos).
  979. */
  980. int qos;
  981. /** The LWT payload in binary form. This is only checked and used if the message option is NULL */
  982. struct
  983. {
  984. int len; /**< binary payload length */
  985. const void* data; /**< binary payload data */
  986. } payload;
  987. } MQTTAsync_willOptions;
  988. #define MQTTAsync_willOptions_initializer { {'M', 'Q', 'T', 'W'}, 1, NULL, NULL, 0, 0, { 0, NULL } }
  989. #define MQTT_SSL_VERSION_DEFAULT 0
  990. #define MQTT_SSL_VERSION_TLS_1_0 1
  991. #define MQTT_SSL_VERSION_TLS_1_1 2
  992. #define MQTT_SSL_VERSION_TLS_1_2 3
  993. /**
  994. * MQTTAsync_sslProperties defines the settings to establish an SSL/TLS connection using the
  995. * OpenSSL library. It covers the following scenarios:
  996. * - Server authentication: The client needs the digital certificate of the server. It is included
  997. * in a store containting trusted material (also known as "trust store").
  998. * - Mutual authentication: Both client and server are authenticated during the SSL handshake. In
  999. * addition to the digital certificate of the server in a trust store, the client will need its own
  1000. * digital certificate and the private key used to sign its digital certificate stored in a "key store".
  1001. * - Anonymous connection: Both client and server do not get authenticated and no credentials are needed
  1002. * to establish an SSL connection. Note that this scenario is not fully secure since it is subject to
  1003. * man-in-the-middle attacks.
  1004. */
  1005. typedef struct
  1006. {
  1007. /** The eyecatcher for this structure. Must be MQTS */
  1008. char struct_id[4];
  1009. /** The version number of this structure. Must be 0, 1, 2, 3, 4 or 5.
  1010. * 0 means no sslVersion
  1011. * 1 means no verify, CApath
  1012. * 2 means no ssl_error_context, ssl_error_cb
  1013. * 3 means no ssl_psk_cb, ssl_psk_context, disableDefaultTrustStore
  1014. * 4 means no protos, protos_len
  1015. */
  1016. int struct_version;
  1017. /** The file in PEM format containing the public digital certificates trusted by the client. */
  1018. const char* trustStore;
  1019. /** The file in PEM format containing the public certificate chain of the client. It may also include
  1020. * the client's private key.
  1021. */
  1022. const char* keyStore;
  1023. /** If not included in the sslKeyStore, this setting points to the file in PEM format containing
  1024. * the client's private key.
  1025. */
  1026. const char* privateKey;
  1027. /** The password to load the client's privateKey if encrypted. */
  1028. const char* privateKeyPassword;
  1029. /**
  1030. * The list of cipher suites that the client will present to the server during the SSL handshake. For a
  1031. * full explanation of the cipher list format, please see the OpenSSL on-line documentation:
  1032. * http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT
  1033. * If this setting is ommitted, its default value will be "ALL", that is, all the cipher suites -excluding
  1034. * those offering no encryption- will be considered.
  1035. * This setting can be used to set an SSL anonymous connection ("aNULL" string value, for instance).
  1036. */
  1037. const char* enabledCipherSuites;
  1038. /** True/False option to enable verification of the server certificate **/
  1039. int enableServerCertAuth;
  1040. /** The SSL/TLS version to use. Specify one of MQTT_SSL_VERSION_DEFAULT (0),
  1041. * MQTT_SSL_VERSION_TLS_1_0 (1), MQTT_SSL_VERSION_TLS_1_1 (2) or MQTT_SSL_VERSION_TLS_1_2 (3).
  1042. * Only used if struct_version is >= 1.
  1043. */
  1044. int sslVersion;
  1045. /**
  1046. * Whether to carry out post-connect checks, including that a certificate
  1047. * matches the given host name.
  1048. * Exists only if struct_version >= 2
  1049. */
  1050. int verify;
  1051. /**
  1052. * From the OpenSSL documentation:
  1053. * If CApath is not NULL, it points to a directory containing CA certificates in PEM format.
  1054. * Exists only if struct_version >= 2
  1055. */
  1056. const char* CApath;
  1057. /**
  1058. * Callback function for OpenSSL error handler ERR_print_errors_cb
  1059. * Exists only if struct_version >= 3
  1060. */
  1061. int (*ssl_error_cb) (const char *str, size_t len, void *u);
  1062. /**
  1063. * Application-specific contex for OpenSSL error handler ERR_print_errors_cb
  1064. * Exists only if struct_version >= 3
  1065. */
  1066. void* ssl_error_context;
  1067. /**
  1068. * Callback function for setting TLS-PSK options. Parameters correspond to that of
  1069. * SSL_CTX_set_psk_client_callback, except for u which is the pointer ssl_psk_context.
  1070. * Exists only if struct_version >= 4
  1071. */
  1072. 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);
  1073. /**
  1074. * Application-specific contex for ssl_psk_cb
  1075. * Exists only if struct_version >= 4
  1076. */
  1077. void* ssl_psk_context;
  1078. /**
  1079. * Don't load default SSL CA. Should be used together with PSK to make sure
  1080. * regular servers with certificate in place is not accepted.
  1081. * Exists only if struct_version >= 4
  1082. */
  1083. int disableDefaultTrustStore;
  1084. /**
  1085. * The protocol-lists must be in wire-format, which is defined as a vector of non-empty, 8-bit length-prefixed, byte strings.
  1086. * The length-prefix byte is not included in the length. Each string is limited to 255 bytes. A byte-string length of 0 is invalid.
  1087. * A truncated byte-string is invalid.
  1088. * Check documentation for SSL_CTX_set_alpn_protos
  1089. * Exists only if struct_version >= 5
  1090. */
  1091. const unsigned char *protos;
  1092. /**
  1093. * The length of the vector protos vector
  1094. * Exists only if struct_version >= 5
  1095. */
  1096. unsigned int protos_len;
  1097. } MQTTAsync_SSLOptions;
  1098. #define MQTTAsync_SSLOptions_initializer { {'M', 'Q', 'T', 'S'}, 5, NULL, NULL, NULL, NULL, NULL, 1, MQTT_SSL_VERSION_DEFAULT, 0, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0 }
  1099. /** Utility structure where name/value pairs are needed */
  1100. typedef struct
  1101. {
  1102. const char* name; /**< name string */
  1103. const char* value; /**< value string */
  1104. } MQTTAsync_nameValue;
  1105. /**
  1106. * MQTTAsync_connectOptions defines several settings that control the way the
  1107. * client connects to an MQTT server.
  1108. *
  1109. * Suitable default values are set in the following initializers:
  1110. * - MQTTAsync_connectOptions_initializer: for MQTT 3.1.1 non-WebSockets
  1111. * - MQTTAsync_connectOptions_initializer5: for MQTT 5.0 non-WebSockets
  1112. * - MQTTAsync_connectOptions_initializer_ws: for MQTT 3.1.1 WebSockets
  1113. * - MQTTAsync_connectOptions_initializer5_ws: for MQTT 5.0 WebSockets
  1114. */
  1115. typedef struct
  1116. {
  1117. /** The eyecatcher for this structure. must be MQTC. */
  1118. char struct_id[4];
  1119. /** The version number of this structure. Must be 0, 1, 2, 3 4 5 6, 7 or 8.
  1120. * 0 signifies no SSL options and no serverURIs
  1121. * 1 signifies no serverURIs
  1122. * 2 signifies no MQTTVersion
  1123. * 3 signifies no automatic reconnect options
  1124. * 4 signifies no binary password option (just string)
  1125. * 5 signifies no MQTTV5 properties
  1126. * 6 signifies no HTTP headers option
  1127. * 7 signifies no HTTP proxy and HTTPS proxy options
  1128. */
  1129. int struct_version;
  1130. /** The "keep alive" interval, measured in seconds, defines the maximum time
  1131. * that should pass without communication between the client and the server
  1132. * The client will ensure that at least one message travels across the
  1133. * network within each keep alive period. In the absence of a data-related
  1134. * message during the time period, the client sends a very small MQTT
  1135. * "ping" message, which the server will acknowledge. The keep alive
  1136. * interval enables the client to detect when the server is no longer
  1137. * available without having to wait for the long TCP/IP timeout.
  1138. * Set to 0 if you do not want any keep alive processing.
  1139. */
  1140. int keepAliveInterval;
  1141. /**
  1142. * This is a boolean value. The cleansession setting controls the behaviour
  1143. * of both the client and the server at connection and disconnection time.
  1144. * The client and server both maintain session state information. This
  1145. * information is used to ensure "at least once" and "exactly once"
  1146. * delivery, and "exactly once" receipt of messages. Session state also
  1147. * includes subscriptions created by an MQTT client. You can choose to
  1148. * maintain or discard state information between sessions.
  1149. *
  1150. * When cleansession is true, the state information is discarded at
  1151. * connect and disconnect. Setting cleansession to false keeps the state
  1152. * information. When you connect an MQTT client application with
  1153. * MQTTAsync_connect(), the client identifies the connection using the
  1154. * client identifier and the address of the server. The server checks
  1155. * whether session information for this client
  1156. * has been saved from a previous connection to the server. If a previous
  1157. * session still exists, and cleansession=true, then the previous session
  1158. * information at the client and server is cleared. If cleansession=false,
  1159. * the previous session is resumed. If no previous session exists, a new
  1160. * session is started.
  1161. */
  1162. int cleansession;
  1163. /**
  1164. * This controls how many messages can be in-flight simultaneously.
  1165. */
  1166. int maxInflight;
  1167. /**
  1168. * This is a pointer to an MQTTAsync_willOptions structure. If your
  1169. * application does not make use of the Last Will and Testament feature,
  1170. * set this pointer to NULL.
  1171. */
  1172. MQTTAsync_willOptions* will;
  1173. /**
  1174. * MQTT servers that support the MQTT v3.1 protocol provide authentication
  1175. * and authorisation by user name and password. This is the user name
  1176. * parameter.
  1177. */
  1178. const char* username;
  1179. /**
  1180. * MQTT servers that support the MQTT v3.1 protocol provide authentication
  1181. * and authorisation by user name and password. This is the password
  1182. * parameter.
  1183. */
  1184. const char* password;
  1185. /**
  1186. * The time interval in seconds to allow a connect to complete.
  1187. */
  1188. int connectTimeout;
  1189. /**
  1190. * The time interval in seconds after which unacknowledged publish requests are
  1191. * retried during a TCP session. With MQTT 3.1.1 and later, retries are
  1192. * not required except on reconnect. 0 turns off in-session retries, and is the
  1193. * recommended setting. Adding retries to an already overloaded network only
  1194. * exacerbates the problem.
  1195. */
  1196. int retryInterval;
  1197. /**
  1198. * This is a pointer to an MQTTAsync_SSLOptions structure. If your
  1199. * application does not make use of SSL, set this pointer to NULL.
  1200. */
  1201. MQTTAsync_SSLOptions* ssl;
  1202. /**
  1203. * A pointer to a callback function to be called if the connect successfully
  1204. * completes. Can be set to NULL, in which case no indication of successful
  1205. * completion will be received.
  1206. */
  1207. MQTTAsync_onSuccess* onSuccess;
  1208. /**
  1209. * A pointer to a callback function to be called if the connect fails.
  1210. * Can be set to NULL, in which case no indication of unsuccessful
  1211. * completion will be received.
  1212. */
  1213. MQTTAsync_onFailure* onFailure;
  1214. /**
  1215. * A pointer to any application-specific context. The
  1216. * the <i>context</i> pointer is passed to success or failure callback functions to
  1217. * provide access to the context information in the callback.
  1218. */
  1219. void* context;
  1220. /**
  1221. * The number of entries in the serverURIs array.
  1222. */
  1223. int serverURIcount;
  1224. /**
  1225. * An array of null-terminated strings specifying the servers to
  1226. * which the client will connect. Each string takes the form <i>protocol://host:port</i>.
  1227. * <i>protocol</i> must be <i>tcp</i>, <i>ssl</i>, <i>ws</i> or <i>wss</i>.
  1228. * The TLS enabled prefixes (ssl, wss) are only valid if a TLS version of the library
  1229. * is linked with.
  1230. * For <i>host</i>, you can
  1231. * specify either an IP address or a domain name. For instance, to connect to
  1232. * a server running on the local machines with the default MQTT port, specify
  1233. * <i>tcp://localhost:1883</i>.
  1234. */
  1235. char* const* serverURIs;
  1236. /**
  1237. * Sets the version of MQTT to be used on the connect.
  1238. * MQTTVERSION_DEFAULT (0) = default: start with 3.1.1, and if that fails, fall back to 3.1
  1239. * MQTTVERSION_3_1 (3) = only try version 3.1
  1240. * MQTTVERSION_3_1_1 (4) = only try version 3.1.1
  1241. */
  1242. int MQTTVersion;
  1243. /**
  1244. * Reconnect automatically in the case of a connection being lost. 0=false, 1=true
  1245. */
  1246. int automaticReconnect;
  1247. /**
  1248. * The minimum automatic reconnect retry interval in seconds. Doubled on each failed retry.
  1249. */
  1250. int minRetryInterval;
  1251. /**
  1252. * The maximum automatic reconnect retry interval in seconds. The doubling stops here on failed retries.
  1253. */
  1254. int maxRetryInterval;
  1255. /**
  1256. * Optional binary password. Only checked and used if the password option is NULL
  1257. */
  1258. struct {
  1259. int len; /**< binary password length */
  1260. const void* data; /**< binary password data */
  1261. } binarypwd;
  1262. /*
  1263. * MQTT V5 clean start flag. Only clears state at the beginning of the session.
  1264. */
  1265. int cleanstart;
  1266. /**
  1267. * MQTT V5 properties for connect
  1268. */
  1269. MQTTProperties *connectProperties;
  1270. /**
  1271. * MQTT V5 properties for the will message in the connect
  1272. */
  1273. MQTTProperties *willProperties;
  1274. /**
  1275. * A pointer to a callback function to be called if the connect successfully
  1276. * completes. Can be set to NULL, in which case no indication of successful
  1277. * completion will be received.
  1278. */
  1279. MQTTAsync_onSuccess5* onSuccess5;
  1280. /**
  1281. * A pointer to a callback function to be called if the connect fails.
  1282. * Can be set to NULL, in which case no indication of unsuccessful
  1283. * completion will be received.
  1284. */
  1285. MQTTAsync_onFailure5* onFailure5;
  1286. /**
  1287. * HTTP headers for websockets
  1288. */
  1289. const MQTTAsync_nameValue* httpHeaders;
  1290. /**
  1291. * The string value of the HTTP proxy. Examples:
  1292. * - http://your.proxy.server:8080/
  1293. * - http://user:pass@my.proxy.server:8080/
  1294. */
  1295. const char* httpProxy;
  1296. /**
  1297. * HTTPS proxy setting. See ::MQTTAsync_connectOptions.httpProxy and the section @ref HTTP_proxies.
  1298. */
  1299. const char* httpsProxy;
  1300. } MQTTAsync_connectOptions;
  1301. /** Initializer for connect options for MQTT 3.1.1 non-WebSocket connections */
  1302. #define MQTTAsync_connectOptions_initializer { {'M', 'Q', 'T', 'C'}, 8, 60, 1, 65535, NULL, NULL, NULL, 30, 0,\
  1303. NULL, NULL, NULL, NULL, 0, NULL, MQTTVERSION_DEFAULT, 0, 1, 60, {0, NULL}, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
  1304. /** Initializer for connect options for MQTT 5.0 non-WebSocket connections */
  1305. #define MQTTAsync_connectOptions_initializer5 { {'M', 'Q', 'T', 'C'}, 8, 60, 0, 65535, NULL, NULL, NULL, 30, 0,\
  1306. NULL, NULL, NULL, NULL, 0, NULL, MQTTVERSION_5, 0, 1, 60, {0, NULL}, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
  1307. /** Initializer for connect options for MQTT 3.1.1 WebSockets connections.
  1308. * The keepalive interval is set to 45 seconds to avoid webserver 60 second inactivity timeouts.
  1309. */
  1310. #define MQTTAsync_connectOptions_initializer_ws { {'M', 'Q', 'T', 'C'}, 8, 45, 1, 65535, NULL, NULL, NULL, 30, 0,\
  1311. NULL, NULL, NULL, NULL, 0, NULL, MQTTVERSION_DEFAULT, 0, 1, 60, {0, NULL}, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
  1312. /** Initializer for connect options for MQTT 5.0 WebSockets connections.
  1313. * The keepalive interval is set to 45 seconds to avoid webserver 60 second inactivity timeouts.
  1314. */
  1315. #define MQTTAsync_connectOptions_initializer5_ws { {'M', 'Q', 'T', 'C'}, 8, 45, 0, 65535, NULL, NULL, NULL, 30, 0,\
  1316. NULL, NULL, NULL, NULL, 0, NULL, MQTTVERSION_5, 0, 1, 60, {0, NULL}, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
  1317. /**
  1318. * This function attempts to connect a previously-created client (see
  1319. * MQTTAsync_create()) to an MQTT server using the specified options. If you
  1320. * want to enable asynchronous message and status notifications, you must call
  1321. * MQTTAsync_setCallbacks() prior to MQTTAsync_connect().
  1322. * @param handle A valid client handle from a successful call to
  1323. * MQTTAsync_create().
  1324. * @param options A pointer to a valid MQTTAsync_connectOptions
  1325. * structure.
  1326. * @return ::MQTTASYNC_SUCCESS if the client connect request was accepted.
  1327. * If the client was unable to connect to the server, an error code is
  1328. * returned via the onFailure callback, if set.
  1329. * Error codes greater than 0 are returned by the MQTT protocol:<br><br>
  1330. * <b>1</b>: Connection refused: Unacceptable protocol version<br>
  1331. * <b>2</b>: Connection refused: Identifier rejected<br>
  1332. * <b>3</b>: Connection refused: Server unavailable<br>
  1333. * <b>4</b>: Connection refused: Bad user name or password<br>
  1334. * <b>5</b>: Connection refused: Not authorized<br>
  1335. * <b>6-255</b>: Reserved for future use<br>
  1336. */
  1337. LIBMQTT_API int MQTTAsync_connect(MQTTAsync handle, const MQTTAsync_connectOptions* options);
  1338. /** Options for the ::MQTTAsync_disconnect call */
  1339. typedef struct
  1340. {
  1341. /** The eyecatcher for this structure. Must be MQTD. */
  1342. char struct_id[4];
  1343. /** The version number of this structure. Must be 0 or 1. 0 signifies no V5 properties */
  1344. int struct_version;
  1345. /**
  1346. * The client delays disconnection for up to this time (in
  1347. * milliseconds) in order to allow in-flight message transfers to complete.
  1348. */
  1349. int timeout;
  1350. /**
  1351. * A pointer to a callback function to be called if the disconnect successfully
  1352. * completes. Can be set to NULL, in which case no indication of successful
  1353. * completion will be received.
  1354. */
  1355. MQTTAsync_onSuccess* onSuccess;
  1356. /**
  1357. * A pointer to a callback function to be called if the disconnect fails.
  1358. * Can be set to NULL, in which case no indication of unsuccessful
  1359. * completion will be received.
  1360. */
  1361. MQTTAsync_onFailure* onFailure;
  1362. /**
  1363. * A pointer to any application-specific context. The
  1364. * the <i>context</i> pointer is passed to success or failure callback functions to
  1365. * provide access to the context information in the callback.
  1366. */
  1367. void* context;
  1368. /**
  1369. * MQTT V5 input properties
  1370. */
  1371. MQTTProperties properties;
  1372. /**
  1373. * Reason code for MQTTV5 disconnect
  1374. */
  1375. enum MQTTReasonCodes reasonCode;
  1376. /**
  1377. * A pointer to a callback function to be called if the disconnect successfully
  1378. * completes. Can be set to NULL, in which case no indication of successful
  1379. * completion will be received.
  1380. */
  1381. MQTTAsync_onSuccess5* onSuccess5;
  1382. /**
  1383. * A pointer to a callback function to be called if the disconnect fails.
  1384. * Can be set to NULL, in which case no indication of unsuccessful
  1385. * completion will be received.
  1386. */
  1387. MQTTAsync_onFailure5* onFailure5;
  1388. } MQTTAsync_disconnectOptions;
  1389. #define MQTTAsync_disconnectOptions_initializer { {'M', 'Q', 'T', 'D'}, 0, 0, NULL, NULL, NULL,\
  1390. MQTTProperties_initializer, MQTTREASONCODE_SUCCESS, NULL, NULL }
  1391. #define MQTTAsync_disconnectOptions_initializer5 { {'M', 'Q', 'T', 'D'}, 1, 0, NULL, NULL, NULL,\
  1392. MQTTProperties_initializer, MQTTREASONCODE_SUCCESS, NULL, NULL }
  1393. /**
  1394. * This function attempts to disconnect the client from the MQTT
  1395. * server. In order to allow the client time to complete handling of messages
  1396. * that are in-flight when this function is called, a timeout period is
  1397. * specified. When the timeout period has expired, the client disconnects even
  1398. * if there are still outstanding message acknowledgements.
  1399. * The next time the client connects to the same server, any QoS 1 or 2
  1400. * messages which have not completed will be retried depending on the
  1401. * cleansession settings for both the previous and the new connection (see
  1402. * MQTTAsync_connectOptions.cleansession and MQTTAsync_connect()).
  1403. * @param handle A valid client handle from a successful call to
  1404. * MQTTAsync_create().
  1405. * @param options The client delays disconnection for up to this time (in
  1406. * milliseconds) in order to allow in-flight message transfers to complete.
  1407. * @return ::MQTTASYNC_SUCCESS if the client successfully disconnects from
  1408. * the server. An error code is returned if the client was unable to disconnect
  1409. * from the server
  1410. */
  1411. LIBMQTT_API int MQTTAsync_disconnect(MQTTAsync handle, const MQTTAsync_disconnectOptions* options);
  1412. /**
  1413. * This function allows the client application to test whether or not a
  1414. * client is currently connected to the MQTT server.
  1415. * @param handle A valid client handle from a successful call to
  1416. * MQTTAsync_create().
  1417. * @return Boolean true if the client is connected, otherwise false.
  1418. */
  1419. LIBMQTT_API int MQTTAsync_isConnected(MQTTAsync handle);
  1420. /**
  1421. * This function attempts to subscribe a client to a single topic, which may
  1422. * contain wildcards (see @ref wildcard). This call also specifies the
  1423. * @ref qos requested for the subscription
  1424. * (see also MQTTAsync_subscribeMany()).
  1425. * @param handle A valid client handle from a successful call to
  1426. * MQTTAsync_create().
  1427. * @param topic The subscription topic, which may include wildcards.
  1428. * @param qos The requested quality of service for the subscription.
  1429. * @param response A pointer to a response options structure. Used to set callback functions.
  1430. * @return ::MQTTASYNC_SUCCESS if the subscription request is successful.
  1431. * An error code is returned if there was a problem registering the
  1432. * subscription.
  1433. */
  1434. LIBMQTT_API int MQTTAsync_subscribe(MQTTAsync handle, const char* topic, int qos, MQTTAsync_responseOptions* response);
  1435. /**
  1436. * This function attempts to subscribe a client to a list of topics, which may
  1437. * contain wildcards (see @ref wildcard). This call also specifies the
  1438. * @ref qos requested for each topic (see also MQTTAsync_subscribe()).
  1439. * @param handle A valid client handle from a successful call to
  1440. * MQTTAsync_create().
  1441. * @param count The number of topics for which the client is requesting
  1442. * subscriptions.
  1443. * @param topic An array (of length <i>count</i>) of pointers to
  1444. * topics, each of which may include wildcards.
  1445. * @param qos An array (of length <i>count</i>) of @ref qos
  1446. * values. qos[n] is the requested QoS for topic[n].
  1447. * @param response A pointer to a response options structure. Used to set callback functions.
  1448. * @return ::MQTTASYNC_SUCCESS if the subscription request is successful.
  1449. * An error code is returned if there was a problem registering the
  1450. * subscriptions.
  1451. */
  1452. LIBMQTT_API int MQTTAsync_subscribeMany(MQTTAsync handle, int count, char* const* topic, const int* qos, MQTTAsync_responseOptions* response);
  1453. /**
  1454. * This function attempts to remove an existing subscription made by the
  1455. * specified client.
  1456. * @param handle A valid client handle from a successful call to
  1457. * MQTTAsync_create().
  1458. * @param topic The topic for the subscription to be removed, which may
  1459. * include wildcards (see @ref wildcard).
  1460. * @param response A pointer to a response options structure. Used to set callback functions.
  1461. * @return ::MQTTASYNC_SUCCESS if the subscription is removed.
  1462. * An error code is returned if there was a problem removing the
  1463. * subscription.
  1464. */
  1465. LIBMQTT_API int MQTTAsync_unsubscribe(MQTTAsync handle, const char* topic, MQTTAsync_responseOptions* response);
  1466. /**
  1467. * This function attempts to remove existing subscriptions to a list of topics
  1468. * made by the specified client.
  1469. * @param handle A valid client handle from a successful call to
  1470. * MQTTAsync_create().
  1471. * @param count The number subscriptions to be removed.
  1472. * @param topic An array (of length <i>count</i>) of pointers to the topics of
  1473. * the subscriptions to be removed, each of which may include wildcards.
  1474. * @param response A pointer to a response options structure. Used to set callback functions.
  1475. * @return ::MQTTASYNC_SUCCESS if the subscriptions are removed.
  1476. * An error code is returned if there was a problem removing the subscriptions.
  1477. */
  1478. LIBMQTT_API int MQTTAsync_unsubscribeMany(MQTTAsync handle, int count, char* const* topic, MQTTAsync_responseOptions* response);
  1479. /**
  1480. * This function attempts to publish a message to a given topic (see also
  1481. * ::MQTTAsync_sendMessage()). An ::MQTTAsync_token is issued when
  1482. * this function returns successfully if the QoS is greater than 0.
  1483. * If the client application needs to
  1484. * test for successful delivery of messages, a callback should be set
  1485. * (see ::MQTTAsync_onSuccess() and ::MQTTAsync_deliveryComplete()).
  1486. * @param handle A valid client handle from a successful call to
  1487. * MQTTAsync_create().
  1488. * @param destinationName The topic associated with this message.
  1489. * @param payloadlen The length of the payload in bytes.
  1490. * @param payload A pointer to the byte array payload of the message.
  1491. * @param qos The @ref qos of the message.
  1492. * @param retained The retained flag for the message.
  1493. * @param response A pointer to an ::MQTTAsync_responseOptions structure. Used to set callback functions.
  1494. * This is optional and can be set to NULL.
  1495. * @return ::MQTTASYNC_SUCCESS if the message is accepted for publication.
  1496. * An error code is returned if there was a problem accepting the message.
  1497. */
  1498. LIBMQTT_API int MQTTAsync_send(MQTTAsync handle, const char* destinationName, int payloadlen, const void* payload, int qos,
  1499. int retained, MQTTAsync_responseOptions* response);
  1500. /**
  1501. * This function attempts to publish a message to a given topic (see also
  1502. * MQTTAsync_publish()). An ::MQTTAsync_token is issued when
  1503. * this function returns successfully if the QoS is greater than 0.
  1504. * If the client application needs to
  1505. * test for successful delivery of messages, a callback should be set
  1506. * (see ::MQTTAsync_onSuccess() and ::MQTTAsync_deliveryComplete()).
  1507. * @param handle A valid client handle from a successful call to
  1508. * MQTTAsync_create().
  1509. * @param destinationName The topic associated with this message.
  1510. * @param msg A pointer to a valid MQTTAsync_message structure containing
  1511. * the payload and attributes of the message to be published.
  1512. * @param response A pointer to an ::MQTTAsync_responseOptions structure. Used to set callback functions.
  1513. * @return ::MQTTASYNC_SUCCESS if the message is accepted for publication.
  1514. * An error code is returned if there was a problem accepting the message.
  1515. */
  1516. LIBMQTT_API int MQTTAsync_sendMessage(MQTTAsync handle, const char* destinationName, const MQTTAsync_message* msg, MQTTAsync_responseOptions* response);
  1517. /**
  1518. * This function sets a pointer to an array of tokens for
  1519. * messages that are currently in-flight (pending completion).
  1520. *
  1521. * <b>Important note:</b> The memory used to hold the array of tokens is
  1522. * malloc()'d in this function. The client application is responsible for
  1523. * freeing this memory when it is no longer required.
  1524. * @param handle A valid client handle from a successful call to
  1525. * MQTTAsync_create().
  1526. * @param tokens The address of a pointer to an ::MQTTAsync_token.
  1527. * When the function returns successfully, the pointer is set to point to an
  1528. * array of tokens representing messages pending completion. The last member of
  1529. * the array is set to -1 to indicate there are no more tokens. If no tokens
  1530. * are pending, the pointer is set to NULL.
  1531. * @return ::MQTTASYNC_SUCCESS if the function returns successfully.
  1532. * An error code is returned if there was a problem obtaining the list of
  1533. * pending tokens.
  1534. */
  1535. LIBMQTT_API int MQTTAsync_getPendingTokens(MQTTAsync handle, MQTTAsync_token **tokens);
  1536. /**
  1537. * Tests whether a request corresponding to a token is complete.
  1538. *
  1539. * @param handle A valid client handle from a successful call to
  1540. * MQTTAsync_create().
  1541. * @param token An ::MQTTAsync_token associated with a request.
  1542. * @return 1 if the request has been completed, 0 if not.
  1543. */
  1544. #define MQTTASYNC_TRUE 1
  1545. LIBMQTT_API int MQTTAsync_isComplete(MQTTAsync handle, MQTTAsync_token token);
  1546. /**
  1547. * Waits for a request corresponding to a token to complete. This only works for
  1548. * messages with QoS greater than 0. A QoS 0 message has no MQTT token.
  1549. * This function will always return ::MQTTASYNC_SUCCESS for a QoS 0 message.
  1550. *
  1551. * @param handle A valid client handle from a successful call to
  1552. * MQTTAsync_create().
  1553. * @param token An ::MQTTAsync_token associated with a request.
  1554. * @param timeout the maximum time to wait for completion, in milliseconds
  1555. * @return ::MQTTASYNC_SUCCESS if the request has been completed in the time allocated,
  1556. * ::MQTTASYNC_FAILURE or ::MQTTASYNC_DISCONNECTED if not.
  1557. */
  1558. LIBMQTT_API int MQTTAsync_waitForCompletion(MQTTAsync handle, MQTTAsync_token token, unsigned long timeout);
  1559. /**
  1560. * This function frees memory allocated to an MQTT message, including the
  1561. * additional memory allocated to the message payload. The client application
  1562. * calls this function when the message has been fully processed. <b>Important
  1563. * note:</b> This function does not free the memory allocated to a message
  1564. * topic string. It is the responsibility of the client application to free
  1565. * this memory using the MQTTAsync_free() library function.
  1566. * @param msg The address of a pointer to the ::MQTTAsync_message structure
  1567. * to be freed.
  1568. */
  1569. LIBMQTT_API void MQTTAsync_freeMessage(MQTTAsync_message** msg);
  1570. /**
  1571. * This function frees memory allocated by the MQTT C client library, especially the
  1572. * topic name. This is needed on Windows when the client library and application
  1573. * program have been compiled with different versions of the C compiler. It is
  1574. * thus good policy to always use this function when freeing any MQTT C client-
  1575. * allocated memory.
  1576. * @param ptr The pointer to the client library storage to be freed.
  1577. */
  1578. LIBMQTT_API void MQTTAsync_free(void* ptr);
  1579. /**
  1580. * This function is used to allocate memory to be used or freed by the MQTT C client library,
  1581. * especially the data in the ::MQTTPersistence_afterRead and ::MQTTPersistence_beforeWrite
  1582. * callbacks. This is needed on Windows when the client library and application
  1583. * program have been compiled with different versions of the C compiler.
  1584. * @param size The size of the memory to be allocated.
  1585. */
  1586. LIBMQTT_API void* MQTTAsync_malloc(size_t size);
  1587. /**
  1588. * This function frees the memory allocated to an MQTT client (see
  1589. * MQTTAsync_create()). It should be called when the client is no longer
  1590. * required.
  1591. * @param handle A pointer to the handle referring to the ::MQTTAsync
  1592. * structure to be freed.
  1593. */
  1594. LIBMQTT_API void MQTTAsync_destroy(MQTTAsync* handle);
  1595. enum MQTTASYNC_TRACE_LEVELS
  1596. {
  1597. MQTTASYNC_TRACE_MAXIMUM = 1,
  1598. MQTTASYNC_TRACE_MEDIUM,
  1599. MQTTASYNC_TRACE_MINIMUM,
  1600. MQTTASYNC_TRACE_PROTOCOL,
  1601. MQTTASYNC_TRACE_ERROR,
  1602. MQTTASYNC_TRACE_SEVERE,
  1603. MQTTASYNC_TRACE_FATAL,
  1604. };
  1605. /**
  1606. * This function sets the level of trace information which will be
  1607. * returned in the trace callback.
  1608. * @param level the trace level required
  1609. */
  1610. LIBMQTT_API void MQTTAsync_setTraceLevel(enum MQTTASYNC_TRACE_LEVELS level);
  1611. /**
  1612. * This is a callback function prototype which must be implemented if you want
  1613. * to receive trace information. Do not invoke any other Paho API calls in this
  1614. * callback function - unpredictable behavior may result.
  1615. * @param level the trace level of the message returned
  1616. * @param message the trace message. This is a pointer to a static buffer which
  1617. * will be overwritten on each call. You must copy the data if you want to keep
  1618. * it for later.
  1619. */
  1620. typedef void MQTTAsync_traceCallback(enum MQTTASYNC_TRACE_LEVELS level, char* message);
  1621. /**
  1622. * This function sets the trace callback if needed. If set to NULL,
  1623. * no trace information will be returned. The default trace level is
  1624. * MQTTASYNC_TRACE_MINIMUM.
  1625. * @param callback a pointer to the function which will handle the trace information
  1626. */
  1627. LIBMQTT_API void MQTTAsync_setTraceCallback(MQTTAsync_traceCallback* callback);
  1628. /**
  1629. * This function returns version information about the library.
  1630. * no trace information will be returned. The default trace level is
  1631. * MQTTASYNC_TRACE_MINIMUM
  1632. * @return an array of strings describing the library. The last entry is a NULL pointer.
  1633. */
  1634. LIBMQTT_API MQTTAsync_nameValue* MQTTAsync_getVersionInfo(void);
  1635. /**
  1636. * Returns a pointer to a string representation of the error code, or NULL.
  1637. * Do not free after use. Returns NULL if the error code is unknown.
  1638. * @param code the MQTTASYNC_ return code.
  1639. * @return a static string representation of the error code.
  1640. */
  1641. LIBMQTT_API const char* MQTTAsync_strerror(int code);
  1642. /*!
  1643. * @cond MQTTAsync_main
  1644. * @page async Threading
  1645. * The client application runs on several threads.
  1646. * Processing of handshaking and maintaining
  1647. * the network connection is performed in the background.
  1648. * This API is thread safe: functions may be called by multiple application
  1649. * threads.
  1650. * Notifications of status and message reception are provided to the client
  1651. * application using callbacks registered with the library by the call to
  1652. * MQTTAsync_setCallbacks() (see MQTTAsync_messageArrived(),
  1653. * MQTTAsync_connectionLost() and MQTTAsync_deliveryComplete()).
  1654. * In addition, some functions allow success and failure callbacks to be set
  1655. * for individual requests, in the ::MQTTAsync_responseOptions structure. Applications
  1656. * can be written as a chain of callback functions.
  1657. *
  1658. * @page callbacks Callbacks
  1659. * Any function from this API may be used within a callback. It is not advisable to
  1660. * use ::MQTTAsync_waitForCompletion within a callback, however, as it is the only
  1661. * API call that may take some time to complete, which may cause unpredictable
  1662. * behaviour. All the other API calls are intended to complete quickly, starting
  1663. * a request in the background, with success or failure notified by other callbacks.
  1664. *
  1665. * If no callbacks are assigned, this will include the message arrived callback.
  1666. * This could be done if the application is a pure publisher, and does
  1667. * not subscribe to any topics. If however messages are received, and no message
  1668. * arrived callback is set, then those messages will accumulate
  1669. * and take up memory, as there is no place for them to be delivered.
  1670. * A log message will be written to highlight the issue, but it is up
  1671. * to the application to protect against this situation.
  1672. *
  1673. * @page auto_reconnect Automatic Reconnect
  1674. * The ability for the client library to reconnect automatically in the event
  1675. * of a connection failure was added in 1.1. The connection lost callback
  1676. * allows a flexible response to the loss of a connection, so almost any
  1677. * behaviour can be implemented in that way. Automatic reconnect does have the
  1678. * advantage of being a little simpler to use.
  1679. *
  1680. * To switch on automatic reconnect, the connect options field
  1681. * automaticReconnect should be set to non-zero. The minimum and maximum times
  1682. * before the next connection attempt can also be set, the defaults being 1 and
  1683. * 60 seconds. At each failure to reconnect, the retry interval is doubled until
  1684. * the maximum value is reached, and there it stays until the connection is
  1685. * successfully re-established whereupon it is reset.
  1686. *
  1687. * When a reconnection attempt is successful, the ::MQTTAsync_connected callback
  1688. * function is invoked, if set by calling ::MQTTAsync_setConnected. This allows
  1689. * the application to take any actions needed, such as amending subscriptions.
  1690. *
  1691. * @page offline_publish Publish While Disconnected
  1692. * This feature was not originally available because with persistence enabled,
  1693. * messages could be stored locally without ever knowing if they could be sent.
  1694. * The client application could have created the client with an erroneous broker
  1695. * address or port for instance.
  1696. *
  1697. * To enable messages to be published when the application is disconnected
  1698. * ::MQTTAsync_createWithOptions must be used instead of ::MQTTAsync_create to
  1699. * create the client object. The ::MQTTAsync_createOptions field sendWhileDisconnected
  1700. * must be set to non-zero, and the maxBufferedMessages field set as required -
  1701. * the default being 100.
  1702. *
  1703. * ::MQTTAsync_getPendingTokens can be called to return the ids of the messages
  1704. * waiting to be sent, or for which the sending process has not completed.
  1705. *
  1706. * @page wildcard Subscription wildcards
  1707. * Every MQTT message includes a topic that classifies it. MQTT servers use
  1708. * topics to determine which subscribers should receive messages published to
  1709. * the server.
  1710. *
  1711. * Consider the server receiving messages from several environmental sensors.
  1712. * Each sensor publishes its measurement data as a message with an associated
  1713. * topic. Subscribing applications need to know which sensor originally
  1714. * published each received message. A unique topic is thus used to identify
  1715. * each sensor and measurement type. Topics such as SENSOR1TEMP,
  1716. * SENSOR1HUMIDITY, SENSOR2TEMP and so on achieve this but are not very
  1717. * flexible. If additional sensors are added to the system at a later date,
  1718. * subscribing applications must be modified to receive them.
  1719. *
  1720. * To provide more flexibility, MQTT supports a hierarchical topic namespace.
  1721. * This allows application designers to organize topics to simplify their
  1722. * management. Levels in the hierarchy are delimited by the '/' character,
  1723. * such as SENSOR/1/HUMIDITY. Publishers and subscribers use these
  1724. * hierarchical topics as already described.
  1725. *
  1726. * For subscriptions, two wildcard characters are supported:
  1727. * <ul>
  1728. * <li>A '#' character represents a complete sub-tree of the hierarchy and
  1729. * thus must be the last character in a subscription topic string, such as
  1730. * SENSOR/#. This will match any topic starting with SENSOR/, such as
  1731. * SENSOR/1/TEMP and SENSOR/2/HUMIDITY.</li>
  1732. * <li> A '+' character represents a single level of the hierarchy and is
  1733. * used between delimiters. For example, SENSOR/+/TEMP will match
  1734. * SENSOR/1/TEMP and SENSOR/2/TEMP.</li>
  1735. * </ul>
  1736. * Publishers are not allowed to use the wildcard characters in their topic
  1737. * names.
  1738. *
  1739. * Deciding on your topic hierarchy is an important step in your system design.
  1740. *
  1741. * @page qos Quality of service
  1742. * The MQTT protocol provides three qualities of service for delivering
  1743. * messages between clients and servers: "at most once", "at least once" and
  1744. * "exactly once".
  1745. *
  1746. * Quality of service (QoS) is an attribute of an individual message being
  1747. * published. An application sets the QoS for a specific message by setting the
  1748. * MQTTAsync_message.qos field to the required value.
  1749. *
  1750. * A subscribing client can set the maximum quality of service a server uses
  1751. * to send messages that match the client subscriptions. The
  1752. * MQTTAsync_subscribe() and MQTTAsync_subscribeMany() functions set this
  1753. * maximum. The QoS of a message forwarded to a subscriber thus might be
  1754. * different to the QoS given to the message by the original publisher.
  1755. * The lower of the two values is used to forward a message.
  1756. *
  1757. * The three levels are:
  1758. *
  1759. * <b>QoS0, At most once:</b> The message is delivered at most once, or it
  1760. * may not be delivered at all. Its delivery across the network is not
  1761. * acknowledged. The message is not stored. The message could be lost if the
  1762. * client is disconnected, or if the server fails. QoS0 is the fastest mode of
  1763. * transfer. It is sometimes called "fire and forget".
  1764. *
  1765. * The MQTT protocol does not require servers to forward publications at QoS0
  1766. * to a client. If the client is disconnected at the time the server receives
  1767. * the publication, the publication might be discarded, depending on the
  1768. * server implementation.
  1769. *
  1770. * <b>QoS1, At least once:</b> The message is always delivered at least once.
  1771. * It might be delivered multiple times if there is a failure before an
  1772. * acknowledgment is received by the sender. The message must be stored
  1773. * locally at the sender, until the sender receives confirmation that the
  1774. * message has been published by the receiver. The message is stored in case
  1775. * the message must be sent again.
  1776. *
  1777. * <b>QoS2, Exactly once:</b> The message is always delivered exactly once.
  1778. * The message must be stored locally at the sender, until the sender receives
  1779. * confirmation that the message has been published by the receiver. The
  1780. * message is stored in case the message must be sent again. QoS2 is the
  1781. * safest, but slowest mode of transfer. A more sophisticated handshaking
  1782. * and acknowledgement sequence is used than for QoS1 to ensure no duplication
  1783. * of messages occurs.
  1784. * @page publish Publication example
  1785. @code
  1786. #include <stdio.h>
  1787. #include <stdlib.h>
  1788. #include <string.h>
  1789. #include "MQTTAsync.h"
  1790. #if !defined(_WIN32)
  1791. #include <unistd.h>
  1792. #else
  1793. #include <windows.h>
  1794. #endif
  1795. #if defined(_WRS_KERNEL)
  1796. #include <OsWrapper.h>
  1797. #endif
  1798. #define ADDRESS "tcp://mqtt.eclipseprojects.io:1883"
  1799. #define CLIENTID "ExampleClientPub"
  1800. #define TOPIC "MQTT Examples"
  1801. #define PAYLOAD "Hello World!"
  1802. #define QOS 1
  1803. #define TIMEOUT 10000L
  1804. int finished = 0;
  1805. void connlost(void *context, char *cause)
  1806. {
  1807. MQTTAsync client = (MQTTAsync)context;
  1808. MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
  1809. int rc;
  1810. printf("\nConnection lost\n");
  1811. printf(" cause: %s\n", cause);
  1812. printf("Reconnecting\n");
  1813. conn_opts.keepAliveInterval = 20;
  1814. conn_opts.cleansession = 1;
  1815. if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
  1816. {
  1817. printf("Failed to start connect, return code %d\n", rc);
  1818. finished = 1;
  1819. }
  1820. }
  1821. void onDisconnectFailure(void* context, MQTTAsync_failureData* response)
  1822. {
  1823. printf("Disconnect failed\n");
  1824. finished = 1;
  1825. }
  1826. void onDisconnect(void* context, MQTTAsync_successData* response)
  1827. {
  1828. printf("Successful disconnection\n");
  1829. finished = 1;
  1830. }
  1831. void onSendFailure(void* context, MQTTAsync_failureData* response)
  1832. {
  1833. MQTTAsync client = (MQTTAsync)context;
  1834. MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
  1835. int rc;
  1836. printf("Message send failed token %d error code %d\n", response->token, response->code);
  1837. opts.onSuccess = onDisconnect;
  1838. opts.onFailure = onDisconnectFailure;
  1839. opts.context = client;
  1840. if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS)
  1841. {
  1842. printf("Failed to start disconnect, return code %d\n", rc);
  1843. exit(EXIT_FAILURE);
  1844. }
  1845. }
  1846. void onSend(void* context, MQTTAsync_successData* response)
  1847. {
  1848. MQTTAsync client = (MQTTAsync)context;
  1849. MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
  1850. int rc;
  1851. printf("Message with token value %d delivery confirmed\n", response->token);
  1852. opts.onSuccess = onDisconnect;
  1853. opts.onFailure = onDisconnectFailure;
  1854. opts.context = client;
  1855. if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS)
  1856. {
  1857. printf("Failed to start disconnect, return code %d\n", rc);
  1858. exit(EXIT_FAILURE);
  1859. }
  1860. }
  1861. void onConnectFailure(void* context, MQTTAsync_failureData* response)
  1862. {
  1863. printf("Connect failed, rc %d\n", response ? response->code : 0);
  1864. finished = 1;
  1865. }
  1866. void onConnect(void* context, MQTTAsync_successData* response)
  1867. {
  1868. MQTTAsync client = (MQTTAsync)context;
  1869. MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
  1870. MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
  1871. int rc;
  1872. printf("Successful connection\n");
  1873. opts.onSuccess = onSend;
  1874. opts.onFailure = onSendFailure;
  1875. opts.context = client;
  1876. pubmsg.payload = PAYLOAD;
  1877. pubmsg.payloadlen = (int)strlen(PAYLOAD);
  1878. pubmsg.qos = QOS;
  1879. pubmsg.retained = 0;
  1880. if ((rc = MQTTAsync_sendMessage(client, TOPIC, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
  1881. {
  1882. printf("Failed to start sendMessage, return code %d\n", rc);
  1883. exit(EXIT_FAILURE);
  1884. }
  1885. }
  1886. int messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* m)
  1887. {
  1888. // not expecting any messages
  1889. return 1;
  1890. }
  1891. int main(int argc, char* argv[])
  1892. {
  1893. MQTTAsync client;
  1894. MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
  1895. int rc;
  1896. if ((rc = MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTASYNC_SUCCESS)
  1897. {
  1898. printf("Failed to create client object, return code %d\n", rc);
  1899. exit(EXIT_FAILURE);
  1900. }
  1901. if ((rc = MQTTAsync_setCallbacks(client, NULL, connlost, messageArrived, NULL)) != MQTTASYNC_SUCCESS)
  1902. {
  1903. printf("Failed to set callback, return code %d\n", rc);
  1904. exit(EXIT_FAILURE);
  1905. }
  1906. conn_opts.keepAliveInterval = 20;
  1907. conn_opts.cleansession = 1;
  1908. conn_opts.onSuccess = onConnect;
  1909. conn_opts.onFailure = onConnectFailure;
  1910. conn_opts.context = client;
  1911. if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
  1912. {
  1913. printf("Failed to start connect, return code %d\n", rc);
  1914. exit(EXIT_FAILURE);
  1915. }
  1916. printf("Waiting for publication of %s\n"
  1917. "on topic %s for client with ClientID: %s\n",
  1918. PAYLOAD, TOPIC, CLIENTID);
  1919. while (!finished)
  1920. #if defined(_WIN32)
  1921. Sleep(100);
  1922. #else
  1923. usleep(10000L);
  1924. #endif
  1925. MQTTAsync_destroy(&client);
  1926. return rc;
  1927. }
  1928. * @endcode
  1929. * @page subscribe Subscription example
  1930. @code
  1931. #include <stdio.h>
  1932. #include <stdlib.h>
  1933. #include <string.h>
  1934. #include "MQTTAsync.h"
  1935. #if !defined(_WIN32)
  1936. #include <unistd.h>
  1937. #else
  1938. #include <windows.h>
  1939. #endif
  1940. #if defined(_WRS_KERNEL)
  1941. #include <OsWrapper.h>
  1942. #endif
  1943. #define ADDRESS "tcp://mqtt.eclipseprojects.io:1883"
  1944. #define CLIENTID "ExampleClientSub"
  1945. #define TOPIC "MQTT Examples"
  1946. #define PAYLOAD "Hello World!"
  1947. #define QOS 1
  1948. #define TIMEOUT 10000L
  1949. int disc_finished = 0;
  1950. int subscribed = 0;
  1951. int finished = 0;
  1952. void connlost(void *context, char *cause)
  1953. {
  1954. MQTTAsync client = (MQTTAsync)context;
  1955. MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
  1956. int rc;
  1957. printf("\nConnection lost\n");
  1958. if (cause)
  1959. printf(" cause: %s\n", cause);
  1960. printf("Reconnecting\n");
  1961. conn_opts.keepAliveInterval = 20;
  1962. conn_opts.cleansession = 1;
  1963. if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
  1964. {
  1965. printf("Failed to start connect, return code %d\n", rc);
  1966. finished = 1;
  1967. }
  1968. }
  1969. int msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message)
  1970. {
  1971. printf("Message arrived\n");
  1972. printf(" topic: %s\n", topicName);
  1973. printf(" message: %.*s\n", message->payloadlen, (char*)message->payload);
  1974. MQTTAsync_freeMessage(&message);
  1975. MQTTAsync_free(topicName);
  1976. return 1;
  1977. }
  1978. void onDisconnectFailure(void* context, MQTTAsync_failureData* response)
  1979. {
  1980. printf("Disconnect failed, rc %d\n", response->code);
  1981. disc_finished = 1;
  1982. }
  1983. void onDisconnect(void* context, MQTTAsync_successData* response)
  1984. {
  1985. printf("Successful disconnection\n");
  1986. disc_finished = 1;
  1987. }
  1988. void onSubscribe(void* context, MQTTAsync_successData* response)
  1989. {
  1990. printf("Subscribe succeeded\n");
  1991. subscribed = 1;
  1992. }
  1993. void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
  1994. {
  1995. printf("Subscribe failed, rc %d\n", response->code);
  1996. finished = 1;
  1997. }
  1998. void onConnectFailure(void* context, MQTTAsync_failureData* response)
  1999. {
  2000. printf("Connect failed, rc %d\n", response->code);
  2001. finished = 1;
  2002. }
  2003. void onConnect(void* context, MQTTAsync_successData* response)
  2004. {
  2005. MQTTAsync client = (MQTTAsync)context;
  2006. MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
  2007. int rc;
  2008. printf("Successful connection\n");
  2009. printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
  2010. "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
  2011. opts.onSuccess = onSubscribe;
  2012. opts.onFailure = onSubscribeFailure;
  2013. opts.context = client;
  2014. if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS)
  2015. {
  2016. printf("Failed to start subscribe, return code %d\n", rc);
  2017. finished = 1;
  2018. }
  2019. }
  2020. int main(int argc, char* argv[])
  2021. {
  2022. MQTTAsync client;
  2023. MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
  2024. MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
  2025. int rc;
  2026. int ch;
  2027. if ((rc = MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL))
  2028. != MQTTASYNC_SUCCESS)
  2029. {
  2030. printf("Failed to create client, return code %d\n", rc);
  2031. rc = EXIT_FAILURE;
  2032. goto exit;
  2033. }
  2034. if ((rc = MQTTAsync_setCallbacks(client, client, connlost, msgarrvd, NULL)) != MQTTASYNC_SUCCESS)
  2035. {
  2036. printf("Failed to set callbacks, return code %d\n", rc);
  2037. rc = EXIT_FAILURE;
  2038. goto destroy_exit;
  2039. }
  2040. conn_opts.keepAliveInterval = 20;
  2041. conn_opts.cleansession = 1;
  2042. conn_opts.onSuccess = onConnect;
  2043. conn_opts.onFailure = onConnectFailure;
  2044. conn_opts.context = client;
  2045. if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
  2046. {
  2047. printf("Failed to start connect, return code %d\n", rc);
  2048. rc = EXIT_FAILURE;
  2049. goto destroy_exit;
  2050. }
  2051. while (!subscribed && !finished)
  2052. #if defined(_WIN32)
  2053. Sleep(100);
  2054. #else
  2055. usleep(10000L);
  2056. #endif
  2057. if (finished)
  2058. goto exit;
  2059. do
  2060. {
  2061. ch = getchar();
  2062. } while (ch!='Q' && ch != 'q');
  2063. disc_opts.onSuccess = onDisconnect;
  2064. disc_opts.onFailure = onDisconnectFailure;
  2065. if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
  2066. {
  2067. printf("Failed to start disconnect, return code %d\n", rc);
  2068. rc = EXIT_FAILURE;
  2069. goto destroy_exit;
  2070. }
  2071. while (!disc_finished)
  2072. {
  2073. #if defined(_WIN32)
  2074. Sleep(100);
  2075. #else
  2076. usleep(10000L);
  2077. #endif
  2078. }
  2079. destroy_exit:
  2080. MQTTAsync_destroy(&client);
  2081. exit:
  2082. return rc;
  2083. }
  2084. * @endcode
  2085. * @page tracing Tracing
  2086. *
  2087. * Runtime tracing can be controlled by environment variables or API calls.
  2088. *
  2089. * #### Environment variables
  2090. *
  2091. * Tracing is switched on by setting the MQTT_C_CLIENT_TRACE environment variable.
  2092. * A value of ON, or stdout, prints to stdout, any other value is interpreted as a file name to use.
  2093. *
  2094. * The amount of trace detail is controlled with the MQTT_C_CLIENT_TRACE_LEVEL environment
  2095. * variable - valid values are ERROR, PROTOCOL, MINIMUM, MEDIUM and MAXIMUM
  2096. * (from least to most verbose).
  2097. *
  2098. * The variable MQTT_C_CLIENT_TRACE_MAX_LINES limits the number of lines of trace that are output
  2099. * to a file. Two files are used at most, when they are full, the last one is overwritten with the
  2100. * new trace entries. The default size is 1000 lines.
  2101. *
  2102. * #### Trace API calls
  2103. *
  2104. * MQTTAsync_traceCallback() is used to set a callback function which is called whenever trace
  2105. * information is available. This will be the same information as that printed if the
  2106. * environment variables were used to control the trace.
  2107. *
  2108. * The MQTTAsync_setTraceLevel() calls is used to set the maximum level of trace entries that will be
  2109. * passed to the callback function. The levels are:
  2110. * 1. ::MQTTASYNC_TRACE_MAXIMUM
  2111. * 2. ::MQTTASYNC_TRACE_MEDIUM
  2112. * 3. ::MQTTASYNC_TRACE_MINIMUM
  2113. * 4. ::MQTTASYNC_TRACE_PROTOCOL
  2114. * 5. ::MQTTASYNC_TRACE_ERROR
  2115. * 6. ::MQTTASYNC_TRACE_SEVERE
  2116. * 7. ::MQTTASYNC_TRACE_FATAL
  2117. *
  2118. * Selecting ::MQTTASYNC_TRACE_MAXIMUM will cause all trace entries at all levels to be returned.
  2119. * Choosing ::MQTTASYNC_TRACE_ERROR will cause ERROR, SEVERE and FATAL trace entries to be returned
  2120. * to the callback function.
  2121. *
  2122. * ### MQTT Packet Tracing
  2123. *
  2124. * A feature that can be very useful is printing the MQTT packets that are sent and received. To
  2125. * achieve this, use the following environment variable settings:
  2126. * @code
  2127. MQTT_C_CLIENT_TRACE=ON
  2128. MQTT_C_CLIENT_TRACE_LEVEL=PROTOCOL
  2129. * @endcode
  2130. * The output you should see looks like this:
  2131. * @code
  2132. 20130528 155936.813 3 stdout-subscriber -> CONNECT cleansession: 1 (0)
  2133. 20130528 155936.813 3 stdout-subscriber <- CONNACK rc: 0
  2134. 20130528 155936.813 3 stdout-subscriber -> SUBSCRIBE msgid: 1 (0)
  2135. 20130528 155936.813 3 stdout-subscriber <- SUBACK msgid: 1
  2136. 20130528 155941.818 3 stdout-subscriber -> DISCONNECT (0)
  2137. * @endcode
  2138. * where the fields are:
  2139. * 1. date
  2140. * 2. time
  2141. * 3. socket number
  2142. * 4. client id
  2143. * 5. direction (-> from client to server, <- from server to client)
  2144. * 6. packet details
  2145. *
  2146. * ### Default Level Tracing
  2147. *
  2148. * This is an extract of a default level trace of a call to connect:
  2149. * @code
  2150. 19700101 010000.000 (1152206656) (0)> MQTTClient_connect:893
  2151. 19700101 010000.000 (1152206656) (1)> MQTTClient_connectURI:716
  2152. 20130528 160447.479 Connecting to serverURI localhost:1883
  2153. 20130528 160447.479 (1152206656) (2)> MQTTProtocol_connect:98
  2154. 20130528 160447.479 (1152206656) (3)> MQTTProtocol_addressPort:48
  2155. 20130528 160447.479 (1152206656) (3)< MQTTProtocol_addressPort:73
  2156. 20130528 160447.479 (1152206656) (3)> Socket_new:599
  2157. 20130528 160447.479 New socket 4 for localhost, port 1883
  2158. 20130528 160447.479 (1152206656) (4)> Socket_addSocket:163
  2159. 20130528 160447.479 (1152206656) (5)> Socket_setnonblocking:73
  2160. 20130528 160447.479 (1152206656) (5)< Socket_setnonblocking:78 (0)
  2161. 20130528 160447.479 (1152206656) (4)< Socket_addSocket:176 (0)
  2162. 20130528 160447.479 (1152206656) (4)> Socket_error:95
  2163. 20130528 160447.479 (1152206656) (4)< Socket_error:104 (115)
  2164. 20130528 160447.479 Connect pending
  2165. 20130528 160447.479 (1152206656) (3)< Socket_new:683 (115)
  2166. 20130528 160447.479 (1152206656) (2)< MQTTProtocol_connect:131 (115)
  2167. * @endcode
  2168. * where the fields are:
  2169. * 1. date
  2170. * 2. time
  2171. * 3. thread id
  2172. * 4. function nesting level
  2173. * 5. function entry (>) or exit (<)
  2174. * 6. function name : line of source code file
  2175. * 7. return value (if there is one)
  2176. *
  2177. * ### Memory Allocation Tracing
  2178. *
  2179. * Setting the trace level to maximum causes memory allocations and frees to be traced along with
  2180. * the default trace entries, with messages like the following:
  2181. * @code
  2182. 20130528 161819.657 Allocating 16 bytes in heap at file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c line 177 ptr 0x179f930
  2183. 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
  2184. * @endcode
  2185. * When the last MQTT client object is destroyed, if the trace is being recorded
  2186. * and all memory allocated by the client library has not been freed, an error message will be
  2187. * written to the trace. This can help with fixing memory leaks. The message will look like this:
  2188. * @code
  2189. 20130528 163909.208 Some memory not freed at shutdown, possible memory leak
  2190. 20130528 163909.208 Heap scan start, total 880 bytes
  2191. 20130528 163909.208 Heap element size 32, line 354, file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c, ptr 0x260cb00
  2192. 20130528 163909.208 Content
  2193. 20130528 163909.209 Heap scan end
  2194. * @endcode
  2195. * @endcond
  2196. *
  2197. √* @page HTTP_proxies HTTP Proxies
  2198. * The use of HTTP proxies can be controlled by environment variables or API calls.
  2199. *
  2200. * The ::MQTTAsync_connectOptions.httpProxy and ::MQTTAsync_connectOptions.httpsProxy fields
  2201. * of the ::MQTTAsync_connectOptions structure override any settings in the environment.
  2202. *
  2203. * If the environment variable PAHO_C_CLIENT_USE_HTTP_PROXY is set to TRUE, then the
  2204. * http_proxy or https_proxy (lower case only) environment variables are used, for plain
  2205. * TCP and TLS-secured connections respectively.
  2206. *
  2207. * The no_proxy environment variable can be used to exclude certain hosts from using an
  2208. * environment variable chosen proxy. This does not apply to a proxy selected through the API.
  2209. * The no_proxy environment variable is lower case only, and is a list of comma-separated
  2210. * hostname:port values. Suffixes are matched (e.g. example.com will match test.example.com).
  2211. */
  2212. #if defined(__cplusplus)
  2213. }
  2214. #endif
  2215. #endif