Part of TI's mqtt

Dependents:   mqtt_V1 cc3100_Test_mqtt_CM3

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers mqtt_client.h Source File

mqtt_client.h

Go to the documentation of this file.
00001 
00002 /******************************************************************************
00003 *
00004 *   Copyright (C) 2014 Texas Instruments Incorporated
00005 *
00006 *   All rights reserved. Property of Texas Instruments Incorporated.
00007 *   Restricted rights to use, duplicate or disclose this code are
00008 *   granted through contract.
00009 *
00010 *   The program may not be used without the written permission of
00011 *   Texas Instruments Incorporated or against the terms and conditions
00012 *   stipulated in the agreement under which this program has been supplied,
00013 *   and under no circumstances can it be used with non-TI connectivity device.
00014 *
00015 ******************************************************************************/
00016 
00017 /*
00018   mqtt_client.h
00019   
00020   This module enumerates the public interfaces / API of the MQTT Client
00021   Library.
00022 */
00023 
00024 
00025 #ifndef __MQTT_CLIENT_H__
00026 #define __MQTT_CLIENT_H__
00027 
00028 /**@file mqtt_client.h
00029    This C library provisions the interface / API(s) for the MQTT Client.
00030 
00031    This is a light-weight library to enable the services of the MQTT protocol
00032    for one or more client applications (that would typically run on a resource
00033    constrained system). The key consideration in the design of small footprint
00034    library has been the abstraction of the low level details of the message
00035    transactions with the server and yet, provide rudimentary API(s), such that,
00036    the capabilities and features of the protocol are availalbe to be utilized
00037    by existing and new applications in an un-restrictive manner.
00038 
00039    The library is targeted to conform to MQTT 3.1.1 specification.
00040 
00041    The MQTT Client library is a highly portable software and implies a very
00042    limited set of dependencies on a platform. Importantly, these limited
00043    dependencies are the commonly used features used in the embedded and the
00044    networking world, and can be easily adapted to the target platforms.
00045 
00046    The services of the library are multi-task safe. Platform specific atomicity
00047    constructs are used, through abstractions, by the library to maintain data 
00048    coherency and synchronization. In addition, the library can be configured to
00049    support several in-flight messages.
00050 
00051    The client library supports multiple and simultaneous MQTT connections to one
00052    or more servers. In this client LIB, the reference to an individual connection
00053    in conjunction with the associated configuration parameters has been termed as
00054    a 'context'. Therefore, the client library supports multiple 'contexts'. An
00055    application that intends to make use of the client library must set-up or
00056    create a 'context' prior to establishing a connection with the server. The
00057    application can choose to destroy the 'context' after the connection with the
00058    server has been terminated. The client LIB can only support a finite set of
00059    'contexts' and the number can be configured by using a compiler line option /
00060    flag <b> -DCFG_CL_MQTT_CTXS </b>.
00061 
00062    Once, the 'context' is set-up, the application can send and receive the MQTT
00063    packets to / from the server. Among several features supported by the client
00064    LIB, the 'context' manages the keep-alive mechanism by automatically sending
00065    PING request to the server, if there has been no other packet send to the
00066    server with the keep-alive duration. 
00067    
00068    @note Any future extensions & development must follow the following guidelines.
00069    A new API or an extension to the existing API
00070    a) must be rudimentary
00071    b) must not imply a rule or policy (including a state machine)
00072    b) must ensure simple design and implementation
00073    
00074 */
00075 
00076 #include "mqtt_common.h"
00077 
00078 #ifdef __cplusplus
00079 extern "C"
00080 {
00081 #endif
00082 
00083 namespace mbed_mqtt {
00084 
00085 /*------------------------------------------------------------------------------
00086  *  MQTT Client Messaging Routines / Services
00087  *------------------------------------------------------------------------------
00088  */
00089 
00090 /** @defgroup client_api The Client Library API(s)
00091     @{
00092 */
00093 
00094 #define MQTT_CLIENT_VERSTR "1.0.3" /**< Version of Client LIB */
00095 
00096 void createMutex(void);
00097 
00098 static int32_t grp_net_setup_create(void);
00099 
00100 /** Provides a new MSG Identifier for a packet dispatch to server
00101 
00102     @return MSG / PKT Transaction identifier
00103 */
00104 uint16_t mqtt_client_new_msg_id(void);
00105 
00106 /** Ascertain whether connection / session with the server is active or not.
00107     Prior to sending out any information any message to server, the application
00108     can use this routine to check the status of the connection. If connection
00109     does not exist, then client should first CONNECT to the broker. 
00110 
00111     A connection to server could have been closed unsolicitedly either due to
00112     keep alive time-out or due to error in RX / TX transactions.
00113     
00114     @note this API does not refer to network layer connection
00115 
00116     @param[in] ctx handle to the underlying network context in the LIB
00117     @see mqtt_client_ctx_create
00118 
00119     @return true if connection is active otherwise false.
00120 */
00121 bool mqtt_client_is_connected(void *ctx);
00122 
00123 /** Send the CONNECT message to the server (and don't wait for CONNACK).
00124     This routine accomplishes multiple sequences. As a first step, it tries
00125     to establish a network connection with the server. Then, it populates
00126     an internaly allocated packet buffer with all the previously provided
00127     payload data information, prepares the requisite headers and finally,
00128     dispatches the constructed message to the server.
00129 
00130     Prior to invoking this service, the client application should provision the
00131     intended payload contents of the CONNECT message by using the API(s) @ref
00132     mqtt_client_ctx_info_register and @ref mqtt_client_ctx_will_register. And
00133     information about the server of interest must be provided in the client LIB
00134     'context' creation (@ref mqtt_client_ctx_create).
00135 
00136     The client application must invoke an appropriate receive routine to know
00137     about the corresponding response CONNACK from the server. The client LIB will
00138     close the network connection to the server, if the server happens to refuse
00139     the CONNECT request.
00140 
00141     @param[in] ctx handle to the underlying network context in the LIB
00142     @see mqtt_client_ctx_create
00143     @param[in] clean_session asserted to delete references to previous session
00144     at both server and client
00145     @param[in] ka_secs Keep Alive Time
00146     @return number of bytes sent or LIB defined errors (@ref lib_err_group)
00147 */
00148 int32_t mqtt_connect_msg_send(void *ctx, bool clean_session, uint16_t ka_secs);
00149 
00150 /** Send a PUBLISH message to the server (don't wait for PUBACK / PUBREC).
00151     This routine creates a PUBLISH message in an internally allocated packet
00152     buffer by embedding the 'topic' and 'data' contents, then prepares the
00153     packet header and finally, dispatches the message to the server.
00154 
00155     After the packet has been sent to the server, if the associated QoS of the
00156     dispatched packet is ether level 1 or 2, the client LIB 'context' will then
00157     store the packet until the time, a corresponding PUB-ACK (for QoS1) or
00158     PUB-REC (QoS2) message is received from the server.
00159 
00160     If the client LIB 'context' has been configured to assert 'clean session',
00161     then the references to all the stored and unacknowledged PUBLISH messages
00162     are dropped at the time of MQTT disconnection (or network disconnection).
00163     Otherwise, these unacknowledged packets continue to be availalbe for the
00164     next iteration of the MQTT connection. However, if the client application
00165     asserts the 'clean session' parameter in the next iteration of the CONNECT
00166     operation, then references to all the stored PUBLISH messages, if any, are
00167     dropped.
00168 
00169     @param[in] ctx handle to the underlying network context in the LIB
00170     @see mqtt_client_ctx_create
00171     @param[in] topic UTF8 based Topic Name for which data is being published.
00172     @param[in] data_buf The binary data that is being published for the topic.
00173     @param[in] data_len The length of the binary data.
00174     @param[in] qos quality of service of the message
00175     @param[in] retain should the server retain the message.
00176     @return on success, a transaction message id otherwise, LIB defined errors
00177     (@ref lib_err_group)
00178 */
00179 int32_t mqtt_client_pub_msg_send(void *ctx,
00180                              const  struct utf8_string *topic,
00181                              const uint8_t *data_buf, uint32_t data_len,
00182                              enum mqtt_qos qos,  bool retain);
00183 
00184 /** Dispatch application constructed PUBLISH message to the server.
00185     Prior to sending the message to the server, this routine will prepare a fixed
00186     header to account for the size of the contents and the flags that have been
00187     indicated by the caller. 
00188 
00189     After the packet has been sent to the server, if the associated QoS of the
00190     dispatched packet is ether level 1 or 2, the client LIB 'context' will then
00191     store the packet until the time, a corresponding PUB-ACK (for QoS1) or
00192     PUB-REC (QoS2) message is received from the server.
00193 
00194     If the client LIB 'context' has been configured to assert 'clean session',
00195     then the references to all the stored and unacknowledged PUBLISH messages
00196     are dropped at the time of MQTT disconnection (or network disconnection).
00197     Otherwise, these unacknowledged packets continue to be availalbe for the
00198     next iteration of the MQTT connection. However, if the client application
00199     asserts the 'clean session' parameter in the next iteration of the CONNECT
00200     operation, then references to all the stored PUBLISH messages, if any, are
00201     dropped.
00202 
00203     The caller must populate the payload information with topic and data before
00204     invoking this service. 
00205 
00206     This service facilitates direct writing of topic and (real-time) payload data
00207     into the buffer, thereby, avoiding power consuming and wasteful intermediate
00208     data copies.
00209 
00210     In case, the routine returns an error, the caller is responsbile for freeing
00211     up or re-using the packet buffer. For all other cases, the client library
00212     will manage the return of the packet buffer to the pool.
00213 
00214     @param[in] ctx handle to the underlying network context in the LIB
00215     @see mqtt_client_ctx_create
00216     @param[in] mqp app created PUBLISH message without the fixed header
00217     @param[in] qos QoS with which the message needs to send to server
00218     @param[in] retain Asserted if the message is to be retained by server.
00219     @return on success, the transaction Message ID, otherwise LIB defined errors
00220     (@ref lib_err_group)
00221 */
00222 int32_t mqtt_client_pub_dispatch(void *ctx, struct mqtt_packet *mqp,
00223                              enum mqtt_qos qos, bool retain);
00224 
00225 /** Send a SUBSCRIBE message to the server (and don't wait for SUBACK).
00226     This routine creates a SUBSCRIBE message in an internally allocated packet
00227     buffer by embedding the 'qos_topics', then prepares the message header and
00228     finally, dispatches the packet to the server. 
00229 
00230     After the packet has been dispatched to the server, the library will store
00231     the packet until the time, a corresponding SUB-ACK has been received from
00232     the server. This mechanism enables the client LIB 'context' to trace the
00233     sequence of the message-ID and / or resend the SUB packets to the server.
00234 
00235     The client LIB 'context', if configured to operate in the MQTT 3.1.1 mode
00236     will drop or remove the un-acknowledged SUB messages at the time of the
00237     termination of the network connection.
00238 
00239     In the MQTT 3.1 mode, the client LIB 'context' will remove the unacknowledged
00240     SUB messages at the time of the termination of the network connection, if the
00241     'clean session' has been asserted. In case, the 'clean session' has not been
00242     asserted, the stored SUB messages will continue to be available for the next
00243     iteration of the MQTT connection. However, if the client application asserts
00244     the 'clean session' parameter in the next iteration of the CONNECT operation,
00245     then references to all the stored SUBSCRIBE messages, if any, are dropped.
00246 
00247     @param[in] ctx handle to the underlying network context in the LIB
00248     @see mqtt_client_ctx_create
00249     @param[in] qos_topics an array of topic along-with its qos
00250     @param[in] count the number of elements in the array
00251     @return on success, the transaction Message ID, otherwise Lib defined errors
00252     (@ref lib_err_group)
00253 */
00254 int32_t mqtt_sub_msg_send(void *ctx, const struct utf8_strqos *qos_topics, uint32_t count);
00255 
00256 /** Dispatch application constructed SUSBSCRIBE message to the server.
00257     Prior to sending the message to the server, this routine will prepare a fixed
00258     header to account for the size of the size of the contents. 
00259 
00260     After the packet has been dispatched to the server, the library will store
00261     the packet until the time, a corresponding SUB-ACK has been received from
00262     the server. This mechanism enables the client LIB 'context' to trace the
00263     sequence of the message-ID and / or resend the SUB packets to the server.
00264 
00265     The client LIB 'context', if configured to operate in the MQTT 3.1.1 mode
00266     will drop or remove the un-acknowledged SUB messages at the time of the
00267     termination of the network connection.
00268 
00269     In the MQTT 3.1 mode, the client LIB 'context' will remove the unacknowledged
00270     SUB messages at the time of the termination of the network connection, if the
00271     'clean session' has been asserted. In case, the 'clean session' has not been
00272     asserted, the stored SUB messages will continue to be available for the next
00273     iteration of the MQTT connection. However, if the client application asserts
00274     the 'clean session' parameter in the next iteration of the CONNECT operation,
00275     then references to all the stored SUBSCRIBE messages, if any, are dropped.
00276 
00277     The caller must populate the payload information of topic along with qos
00278     before invoking this service. 
00279 
00280     This service facilitates direct writing of topic and (real-time) payload data
00281     into the buffer, thereby, avoiding power consuming and wasteful intermediate
00282     data copies.
00283 
00284     In case, the routine returns an error, the caller is responsbile for freeing
00285     up or re-using the packet buffer. For all other cases, the client library
00286     will manage the return of the packet buffer to the pool.
00287 
00288     @param[in] ctx handle to the underlying network context in the LIB
00289     @see mqtt_client_ctx_create
00290     @param[in] mqp app created SUBSCRIBE message without the fixed header.
00291     @return on success, the transaction Message ID, otherwise Lib defined errors
00292     (@ref lib_err_group)
00293 */
00294 int32_t mqtt_sub_dispatch(void *ctx, struct mqtt_packet *mqp);
00295 
00296 /** Send an UNSUBSCRIBE message to the server (and don't wait for UNSUBACK).
00297     This routine creates an UNSUBSCRIBE message in an internally allocated packet
00298     buffer by embedding the 'topics', then prepares the message header and 
00299     finally, dispatches the packet to the server.
00300 
00301     After the packet has been dispatched to the server, the library will store
00302     the packet until the time, a corresponding UNSUB-ACK has been received from
00303     the server. This mechanism enables the client LIB 'context' to trace the
00304     sequence of the message-ID and / or resend the UNSUB packets to the server.
00305 
00306     The client LIB 'context', if configured to operate in the MQTT 3.1.1 mode
00307     will drop or remove the un-acknowledged SUB messages at the time of the
00308     termination of the network connection.
00309 
00310     In the MQTT 3.1 mode, the client LIB 'context' will remove the unacknowledged
00311     UNSUB messages at the time of the termination of the network connection, if
00312     the 'clean session' has been asserted. In case, the 'clean session' has not
00313     been asserted, the stored UNSUB messages will continue to be available for
00314     the next iteration of the MQTT connection. However, if the client application
00315     asserts the 'clean session' parameter in the next iteration of the CONNECT
00316     operation, then references to all the stored UNSUBSCRIBE messages, if any,
00317     are dropped.
00318 
00319     @param[in] ctx handle to the underlying network context in the LIB
00320     @see mqtt_client_ctx_create
00321     @param[in] topics an array of topic to unsubscribe
00322     @param[in] count the number of elements in the array
00323     @return on success, the transaction Message ID, otherwise Lib defined errors
00324     (@ref lib_err_group)
00325 */
00326 int32_t mqtt_unsub_msg_send(void *ctx, const struct utf8_string *topics, uint32_t count);
00327 
00328 /** Dispatch application constructed UNSUSBSCRIBE message to the server. 
00329     Prior to sending the message to the server, this routine will prepare a fixed
00330     header to account for the size of the size of the contents. 
00331 
00332     After the packet has been dispatched to the server, the library will store
00333     the packet until the time, a corresponding UNSUB-ACK has been received from
00334     the server. This mechanism enables the client LIB 'context' to trace the
00335     sequence of the message-ID and / or resend the UNSUB packets to the server.
00336 
00337     The client LIB 'context', if configured to operate in the MQTT 3.1.1 mode
00338     will drop or remove the un-acknowledged SUB messages at the time of the
00339     termination of the network connection.
00340 
00341     In the MQTT 3.1 mode, the client LIB 'context' will remove the unacknowledged
00342     UNSUB messages at the time of the termination of the network connection, if
00343     the 'clean session' has been asserted. In case, the 'clean session' has not
00344     been asserted, the stored UNSUB messages will continue to be available for
00345     the next iteration of the MQTT connection. However, if the client application
00346     asserts the 'clean session' parameter in the next iteration of the CONNECT
00347     operation, then references to all the stored UNSUBSCRIBE messages, if any,
00348     are dropped.
00349 
00350     The caller must populate the payload information of topics before invoking
00351     this service. 
00352 
00353     This service facilitates direct writing of topic and (real-time) payload data
00354     into the buffer, thereby, avoiding power consuming and wasteful intermediate
00355     data copies.
00356 
00357     In case, the routine returns an error, the caller is responsbile for freeing
00358     up or re-using the packet buffer. For all other cases, the client library
00359     will manage the return of the packet buffer to the pool.
00360 
00361     @param[in] ctx handle to the underlying network context in the LIB
00362     @see mqtt_client_ctx_create
00363     @param[in] Packet Buffer that holds UNSUBSCRIBE message without a fixed header
00364     @return on success, the transaction Message ID, otherwise LIB defined errors
00365     (@ref lib_err_group)
00366 */
00367 int32_t mqtt_unsub_dispatch(void *ctx, struct mqtt_packet *mqp);
00368 
00369 /** Send a PINGREQ message to the server (and don't wait for PINGRSP).
00370 
00371     @param[in] ctx handle to the underlying network context in the LIB
00372     @see mqtt_client_ctx_create
00373     @return number of bytes sent or Lib define errors (@ref lib_err_group)
00374 */
00375 
00376 int32_t mqtt_pingreq_send(void *ctx);
00377 
00378 /** Send a DISCONNECT message to the server.
00379 
00380     @param[in] ctx handle to the underlying network context in the LIB
00381     @see mqtt_client_ctx_create
00382     @return number of bytes sent or Lib define errors (@ref lib_err_group)
00383 */
00384 int32_t mqtt_disconn_send(void *ctx);
00385 
00386 
00387 /** Send remaining data or contents of the scheduled message to the server.
00388     This routine tries to send the remaining data in an active transfer of a
00389     message to the server. This service is valid, only if the network layer of
00390     the platform is not able to send out the entire message in one TCP packet
00391     and has to "back-off" or "give up the control" before it can schedule or
00392     dispatch the next packet. In such a scenario, the network layer sends the
00393     first part (segment) of the scheduled message in the mqtt_xxx_send() API and
00394     the subsequent parts or the segments are sent using this routine.
00395     
00396     This routine is not applicable to the platforms or the scenarios, where the
00397     implementation of the platform can segment the MQTT message in a manner to
00398     schedule consercutive or back-to-back blocking socket transactions.
00399     Specifically, this API must be used by an application, only if the network
00400     layer can indicate in an asynchronous manner, its readiness to send the next
00401     packet to the server. And the mechanism to indicate readiness of the network
00402     layer for the next send transaction is out of band and out of scope for the
00403     Client LIB and depends on the platform.
00404 
00405     A platform that resorts to partial send of a message and has to back-off from
00406     transmission implies the following the considerations on to the application.
00407     (a) The next segment / part of the currently active MQTT packet can be sent
00408     or scheduled only after receiving the indication, to do so, from the network
00409     layer.
00410     (b) The next or new MQTT message (or its first segment) can be scheduled for
00411     transmission only after receiving the indication for completion of handling
00412     of the last segment of currently active message.
00413 
00414     @note The application developer should refer to the platform specific network
00415     implementation for details.
00416 
00417     The routine returns the number of remaining bytes in the message to be sent.
00418     However, as described earlier, the application is expected to wait for an
00419     indication about the readiness of the network layer prior to sending or
00420     scheduling another segment, if so available, to the server. Now, the new
00421     segment can be a next part of the currently active message or it can be the
00422     first segment of a new message. A return value of zero means that there is
00423     no more data left in the scheduled message to be sent to the server and the
00424     application should wait for an appropriate event to indicate the transmission
00425     of the last segment.
00426 
00427     In case of an error, the transfer of the remaining segments or parts of the
00428     scheduled message is aborted. Depending on the configuration of the 'clean
00429     session' in-conjunction with the revision of the MQTT protocol, the active
00430     message would be stored for re-transmission, MQTT connection is established
00431     again. To store a message for re-transmission, at least one segment of the
00432     message must have been successfully sent to the server.
00433 
00434     @note This API must be used by the application only if the platform has the
00435     capability to indicate the completion of the sending of an active segment.
00436 
00437     @param[in] ctx handle to the underlying network context in the LIB
00438     @see mqtt_client_ctx_create
00439     @return the number of bytes remaining to be sent in the message. Otherwise,
00440     LIB defined errors (@ref lib_err_group)
00441 */
00442 int32_t mqtt_client_send_progress(void *ctx);
00443 
00444 /** Block on the 'context' to receive a message type with-in specified wait time.
00445     This service is valid only for the configuration, where the application has
00446     not provided the callbacks to the client LIB 'context'. The caller must
00447     provide a packet buffer of adequate size to hold the expected message from
00448     the server. 
00449 
00450     The wait time implies the maximum intermediate duration between the reception
00451     of two successive messages from the server. If no message is received before
00452     the expiry of the wait time, the routine returns. However, the routine would
00453     continue to block, in case, messages are being received within the successive
00454     period of wait time and these messages are not the one that client is waiting
00455     for.
00456 
00457     For platforms that can receive a MQTT message over multiple TCP packets or in
00458     segments, it is neccessary for the application to provide the same packet
00459     packet buffer 'mqp' across all iterations of this routine that returns with a
00460     value of MQP_ERR_TIMEOUT. Such an arrangement enables the implementation to
00461     iteratively build from consecutive multiple RX network packets / segements, a
00462     MQTT message into the packet buffer 'mqp. The application can always choose
00463     to assign a new 'mqp' once, a complete MQTT message has been received.
00464 
00465     @param[in] ctx handle to the underlying network context in the LIB
00466     @see mqtt_client_ctx_create
00467     @param[in] msg_type message type to receive. A value of 0 would imply that
00468     caller is ready to receive the next message, whatsoever, from the  server.
00469     @param[out] mqp packet buffer to hold the message received from the server.
00470     @param[in] wait_secs maximum Time to wait for a message from the server.
00471     @return On success, the number of bytes received for 'msg_type' from server,
00472     otherwise LIB defined error values (@ref lib_err_group)
00473 */
00474 int32_t mqtt_client_ctx_await_msg(void *ctx, uint8_t msg_type, struct mqtt_packet *mqp,
00475                               uint32_t wait_secs);
00476 
00477 /** Helper function to receive any message from the server.
00478     Refer to mqtt_client_ctx_await_msg for the details.
00479     @see mqtt_client_ctx_await_msg
00480 */
00481 static inline
00482 int32_t mqtt_client_ctx_recv(void *ctx, struct mqtt_packet *mqp, uint32_t wait_secs)
00483 {
00484         /* Receive next and any MQTT Message from the broker */
00485         return mqtt_client_ctx_await_msg(ctx, 0x00, mqp, wait_secs);
00486 }
00487 
00488 /** Run the context for the specificed wait time.
00489     This service is valid only for the configuration, where the application has
00490     populated the callbacks that can be invoked by the client LIB 'context'.
00491 
00492     This routine yields the control back to the application after the duration
00493     of the wait time. Such an arrangement enable the application to make overall
00494     progress to meet its intended functionality. 
00495 
00496     The wait time implies the maximum intermediate duration between the reception
00497     of two successive messages from the server. If no message is received before
00498     the expiry of the wait time, the routine returns. However, the routine would
00499     continue to block, in case, messages are being received within the successive
00500     period of the wait time.
00501 
00502     @param[in] ctx handle to the underlying network context in the LIB
00503     @see mqtt_client_ctx_create
00504     @param[in] wait_secs maximum time to wait for a message from the server
00505 
00506     @return MQP_ERR_NOTCONN if MQTT connection is closed by the application, 
00507     MQP_ERR_TIMEOUT if there was no MQTT transaction in the interval of wait time
00508     and other values (@ref lib_err_group)
00509 */
00510 int32_t mqtt_client_ctx_run(void *ctx, uint32_t wait_secs);
00511 
00512 /** Block to receive any message for the grouped contexts within specified time.
00513     This service is valid only for the set-up, where the applicatiion has not
00514     configured the grouped contexts in the callback mode. The caller must provide
00515     a packet buffer of adequate size to hold the expected message from the server.
00516 
00517     The wait time implies the maximum intermediate duration between the reception
00518     of two successive messages from the server. If no message is received before
00519     the expiry of the wait time, the routine returns. However, the routine would
00520     continue to block, in case, messages are being received within the successive
00521     period of wait time.
00522 
00523     In this revision of the LIB, the underlying implementation will be provide a
00524     valid value in the 'app' field for the all returned values, including errors,
00525     other than the cases of 'MQP_ERR_TIMEOUT' and 'MQP_ERR_LIBQUIT'. The value in
00526     'app', when valid refers to a previously configured handle to an application
00527     and idenitifies the 'context' for which the routine has been returned.
00528 
00529     @param[out] mqp packet buffer to hold the message received from the server.
00530     @param[in]  wait_secs Maximum Time to wait for a message from the server.
00531     @param[out] app place holder to indicate application handle for the packet.
00532     @return On success, the number of bytes received for 'msg_type' from server,
00533     otherwise LIB defined error values (@ref lib_err_group)
00534 
00535     @note if the value of MQP_ERR_LIBQUIT is returned, then system must be
00536     restarted.
00537 */
00538 int32_t mqtt_client_await_msg(struct mqtt_packet *mqp, uint32_t wait_secs, void **app);
00539 
00540 /** Run the LIB for the specified wait time.
00541     This service is valid only for the set-up of grouped contexts, where the
00542     application has populated the callbacks that can be invoked by the LIB.
00543 
00544     This routine yields the control back to the application after the specified
00545     duration of wait time. Such an arrangement enable the application to
00546     make overall progress to meet it intended functionality. 
00547 
00548     The wait time implies the maximum intermediate duration between the reception
00549     of two successive messages from the server. If no message is received before
00550     the expiry of the wait time, the routine returns. However, the routine would
00551     continue to block, in case, messages are being received within the successive
00552     period of wait time.
00553 
00554     @param[in] wait_secs maximum time to wait for a message from the server
00555 
00556     @return on connection close by client app, number of bytes received for the
00557     last msg from broker, otherwise LIB defined error values.
00558 
00559     @note if the value of MQP_ERR_LIBQUIT is returned, then system must be
00560     restarted.
00561 */
00562 int32_t mqtt_client_run(uint32_t wait_secs);
00563 
00564 /*------------------------------------------------------------------------------
00565  *  MQTT Client Library: Packet Buffer Pool and its management
00566  *------------------------------------------------------------------------------
00567  */
00568 
00569 /** Allocates a free MQTT Packet Buffer.
00570     The pool that will be used by the library to allocate a free MQP buffer
00571     must be configured (i.e. registered) a-priori by the app.
00572 
00573     The parameter 'offset' is used to specify the number of bytes that are
00574     reserved for the header in the buffer
00575 
00576     @param[in] msg_type Message Type for which MQP buffer is being assigned.
00577     @param[in] offset Number of bytes to be reserved for MQTT headers.
00578     @return A NULL on error, otherwise a reference to a valid packet holder.
00579 
00580     @see mqtt_client_register_buffers
00581 */
00582 struct mqtt_packet *mqp_client_alloc(uint8_t msg_type, uint8_t offset);
00583 
00584 /** Helper function to allocate a MQTT Packet Buffer for a message to be
00585     dispatched to server.
00586 
00587     @see to mqp_client_alloc( ) for details.
00588 */
00589 static inline struct mqtt_packet *mqp_client_send_alloc(uint8_t msg_type)
00590 {
00591         return mqp_client_alloc(msg_type, MAX_FH_LEN);
00592 }
00593 
00594 /** Helper function to allocate a MQTT Packet Buffer for a message to be
00595     received from the server.
00596 
00597     @see to mqp_client_alloc( ) for details.
00598 */
00599 static inline struct mqtt_packet *mqp_client_recv_alloc(uint8_t msg_type)
00600 {
00601         return mqp_client_alloc(msg_type, 0);
00602 }
00603 
00604 /** Create a pool of MQTT Packet Buffers for the client library. 
00605     This routine creates a pool of free MQTT Packet Buffers by attaching a buffer
00606     (buf) to a packet holder (mqp). The count of mqp elements and buf elements in
00607     the routine are same. And the size of the buffer in constant across all the
00608     elements.
00609 
00610     The MQTT Packet Buffer pool should support (a) certain number of in-flight and
00611     stored packets that await ACK(s) from the server (b) certain number of packets
00612     from server whose processing would be deferred by the client app (to another
00613     context) (c) a packet to create a CONNECT message to re-establish transaction
00614     with the server.
00615 
00616     A meaningful size of the pool is very much application specific and depends
00617     on the target functionality. For example, an application that intends to have
00618     only one in-flight message to the server would need atmost three MQP buffers
00619     (1 for TX (for Qos1 or 2 store), 1 for RX and 1 for CONNECT message). If the
00620     application sends only QoS0 messages to the server, then the number of MQP
00621     buffers would reduce to two (i.e. 1 Tx to support CONNECT / PUB out and 1 RX)
00622 
00623     @param[in] num_mqp Number or count of elements in mqp_vec and buf_vec.
00624     @param[in] mqp_vec An array of MQTT Packet Holder without a buffer.
00625     @param[in] buf_len The size or length of the buffer element in the 'buf_vec'
00626     @param[in] buf_vec An array of buffers.
00627     @retun  0 on success otherwise -1 on error.
00628 
00629     @note The parameters mqp_vec and buf_vec should be peristent entities.
00630 
00631     @see mqtt_client_await_msg
00632     @see mqtt_client_run
00633 */
00634 int32_t mqtt_client_buffers_register(uint32_t num_mqp, struct mqtt_packet *mqp_vec,
00635                                  uint32_t buf_len, uint8_t *buf_vec);
00636 
00637 /*------------------------------------------------------------------------------
00638  *  MQTT Client Library: Register application, platform information and services.
00639  *------------------------------------------------------------------------------
00640  */
00641 
00642 /** Register application info and its credentials with the client library.
00643     This routine registers information for all the specificed parameters,
00644     therefore, an upate to single element would imply re-specification of
00645     the other paramters, as well.
00646 
00647     @note Contents embedded in the parameters is not copied by the routine,
00648     and instead a reference to the listed constructs is retained. Therefore,
00649     the app must enable the parameter contents for persistency.
00650 
00651     @param[in] ctx handle to the underlying network context in the LIB
00652     @see mqtt_client_ctx_create
00653     @param[in] client_id MQTT UTF8 identifier of the client. If set to NULL,
00654     then the client will be treated as zero length entity.
00655     @param[in] user_name MQTT UTF8 user name for the client. If not used,
00656     set it to NULL. If used, then it can't be of zero length.
00657     @param[in] pass_word MQTT UTF8 pass word for the client. If not used, set
00658     it to NULL, If used, then it can't be of zero length.
00659     @return 0 on success otherwise -1
00660 
00661     User name without a pass word is a valid configuration. A pass word won't
00662     be processed if it is not associated with a valid user name.
00663 */
00664 int32_t mqtt_client_ctx_info_register(void *ctx,
00665                                   const struct utf8_string *client_id,
00666                                   const struct utf8_string *user_name,
00667                                   const struct utf8_string *pass_word);
00668 
00669 /** Register WILL information of the client application.
00670     This routine registers information for all the specificed parameters,
00671     therefore, an update to single element would imply re-specification
00672     of the other paramters, as well.
00673 
00674     @note Contents embedded in the parameters is not copied by the routine,
00675     and instead a reference to the listed constructs is retained. Therefore,
00676     the app must enable the parameter contents for persistency.
00677 
00678     @param[in] ctx handle to the underlying network context in the LIB
00679     @see mqtt_client_ctx_create
00680     @param[in] will_top UTF8 WILL Topic on which WILL message is to be published.
00681     @param[in] will_msg UTF8 WILL message.
00682     @param[in] will_qos QOS for the WILL message
00683     @param[in] retain asserted to indicate that published WILL must be retained
00684     @return 0 on success otherwise -1.
00685 
00686     Both will_top and will_msg should be either present or should be NULL.
00687     will_qos and retain are relevant only for a valid Topic and Message combo.
00688 */
00689 int32_t mqtt_client_ctx_will_register(void *ctx,
00690                                   const struct utf8_string  *will_top,
00691                                   const struct utf8_string  *will_msg,
00692                                   enum mqtt_qos will_qos, bool retain);
00693 
00694 /** Abstraction for the device specific network services.
00695     Network services for communication with the server
00696 
00697     @param[in] net refers to network services supported by the platform
00698     @return on success, 0, otherwise -1
00699 
00700     @ref net_ops_group
00701     @note all entries in net must be supported by the platform.
00702 */
00703 int32_t mqtt_client_net_svc_register(const struct device_net_services *net);
00704 
00705 /** Helper functions & macros to derive 16 bit CONNACK Return Code from broker.
00706  */
00707 #define VHB_CONNACK_RC(vh_buf) (vh_buf[1])     /**< CONNACK  VH:: Return Code */
00708 #define MQP_CONNACK_RC(mqp)    (mqp->buffer[3])/**< CONNACK MQP:: Return Code */
00709 
00710 #define VHB_CONNACK_SP(vh_buf) (vh_buf[0] & 0x1)/**< CONNACK VH:: Session Bit */
00711 #define MQP_CONNACK_SP(mqp)    (mqp->buffer[2] & 0x1) /**< CONNACK MQP:: \
00712                                                          Session Bit */
00713 
00714 #define VHB_CONNACK_VH16(vh_buf)((vh_buf[0] << 8) | vh_buf[1]) 
00715 #define MQP_CONNACK_VH16(mqp)   ((mqp->buffer[2] << 8) | mqp->buffer[3])
00716 
00717 /** Callbacks to be invoked by MQTT Client library onto Client application */
00718 struct mqtt_client_ctx_cbs {
00719 
00720         /** Provides a PUBLISH message from server to the client application.
00721             The application can utilize the associated set of helper macros to
00722             get references to the topic and the data information contained in
00723             the message. @ref rxpub_help_group
00724 
00725             Depending upon the QoS level of the message, the MQTT client library
00726             shall dispatch the correponding acknowlegement (PUBACK or PUBREC) to
00727             the server, thereby, relieving application of this support.
00728 
00729             If the application completes the processing of the packet within the
00730             implementation of this callback routine, then a value of 'true' must
00731             be returned to the client LIB 'context'. The library, in this case,
00732             does not handover the packet to application and instead, frees it up
00733             on return from this routine.
00734 
00735             If the application intends to defer the processing of the PUBLISH
00736             message to a different execution task, then it must takeover the
00737             owernship of the packet by returning a value of 'false' to the client
00738             LIB 'context. In this arrangement, the client LIB 'context' hands
00739             over the packet to the application. The responsibility of storing,
00740             managing and eventually freeing up the packet back to the pool, now,
00741             lies with the app.
00742 
00743             @param[in] app application to which this PUBLISH message is targeted
00744             @see mqtt_client_ctx_create
00745             @param[in] dup asserted to indicate a DUPLICATE PUBLISH
00746             @param[in] qos quality of Service of the PUBLISH message
00747             @param[in] retain Asserted to indicate message at new subscription
00748             @param[in] mqp Packet Buffer that holds the PUBLISH message
00749 
00750             @return true to indicate that processing of the packet has been
00751             completed and it can freed-up and returned back to the pool by
00752             the library. Otherwise, false.
00753         */
00754         bool (*publish_rx)(void *app,
00755                            bool dup, enum mqtt_qos qos, bool retain, 
00756                            struct mqtt_packet *mqp);
00757 
00758         /** Notifies the client application about an ACK or a response from the
00759             server. Following are the messages that are notified by the client
00760             LIB to the application.
00761 
00762             CONNACK, PINGRSP, PUBACK, PUBCOMP, SUBACK, UNSUBACK
00763 
00764             @param[in] app application to which this ACK message is targeted
00765             @see mqtt_client_ctx_create
00766             @param[in] msg_type Type of the MQTT messsage 
00767             @param[in] msg_id transaction identity of the message
00768             @param[in] buf refers to contents of message and depends on msg_type
00769             @param[in] len length of the buf
00770             @return none
00771 
00772             @note The size of the buf parameter i.e len is non-zero for the
00773             SUBACK and CONNACK messages. For SUBACK the buf carries an array of
00774             QOS responses provided by the server. For CONNACK, the buf carries
00775             variable header contents. Helper macro VHB_CONNACK_RC( ) and 
00776             VHB_CONNACK_SP( ) can be used to access contents provided by the 
00777             server. For all other messages, the value of len parameter is zero.
00778 
00779             @note The parameter msg_id is not relevant for the messages CONNACK
00780             and PINGRSP and is set to zero.
00781         */
00782         void (*ack_notify)(void *app, uint8_t msg_type, uint16_t msg_id, uint8_t *buf, uint32_t len);
00783 
00784         /** Notifies the client application about the termination of connection
00785             with the server. After servicing this callback, the application can
00786             destroy associated context if it no longer required 
00787 
00788             @param[in] app application whose connection got terminated
00789             @see mqtt_client_ctx_create
00790             @param[in] cause reason that created disconnection
00791             (@ref lib_err_group)
00792         */
00793         void (*disconn_cb)(void *app, int32_t cause);
00794 };
00795 
00796 struct mqtt_client_ctx_cfg {
00797 
00798         /** @defgroup mqtt_ctx_cfg_opt_grp Options for application to config CTX
00799             @{
00800         */
00801 #define MQTT_CFG_PROTOCOL_V31  0x0001 /**< Assert for ver3.1, default is 3.1.1 */
00802 #define MQTT_CFG_APP_HAS_RTSK  0x0002 /**< Assert if APP has dedicated RX Task */
00803 #define MQTT_CFG_MK_GROUP_CTX  0x0004 /**< Assert if task manages > 1 contexts */
00804         /** @} */
00805 
00806         uint16_t   config_opts;  /**< Context config Opt, @ref mqtt_ctx_cfg_opt_grp */
00807 
00808         /** @defgroup mqtt_netconn_opt_grp Options for App to configure network
00809             @{
00810         */
00811 #define MQTT_NETCONN_OPT_IP6  DEV_NETCONN_OPT_IP6 /**<@ref dev_netconn_opt_grp */
00812 #define MQTT_NETCONN_OPT_URL  DEV_NETCONN_OPT_URL /**<@ref dev_netconn_opt_grp */
00813 #define MQTT_NETCONN_OPT_SEC  DEV_NETCONN_OPT_SEC /**<@ref dev_netconn_opt_grp */
00814         /** @} */
00815 
00816         uint32_t   nwconn_opts;  /**< Network Options,  @ref mqtt_netconn_opt_grp */
00817 
00818         char   *server_addr;  /**< Reference to '\0' terminated address string */
00819         uint16_t   port_number;  /**< Network Listening Port number of the server */
00820         struct secure_conn *nw_security;  /**< Refer to @ref mqtt_netsec_grp */
00821 };
00822 
00823 /** Create a Network Connection Context.
00824     This routine sets-up the parameters that are required to operate and manage
00825     the network connection with a MQTT server / broker. As part of the creation
00826     of a context, the implementation also records the handle, if provided, by
00827     the application. In addition, the invoker of the routine must facilitate a
00828     place holder to enable the client LIB to provision the reference to the 
00829     'context', so created.
00830 
00831     Specifically, this routine associates or ties-up, in an one-to-one manner,
00832     the caller provided handle 'app' and the client LIB provisioned handle 'ctx'.
00833     The parameter 'app' is returned by the client LIB in certain other routines
00834     to indicate the underlying 'context' with which network transaction or event
00835     is associated. Similarly, the caller must specify the context handle 'ctx'
00836     for which the services are being invoked.
00837 
00838     A user or a task prior to utilizing the services of the library to schedule
00839     MQTT transactions must create a 'context'. A client LIB 'context' can be
00840     operated in two modes: (a) sync-wait or explicit receive mode and (b) the
00841     callback mode. Provisioning or absence of the callback parameter in this
00842     routine defines the mode of operation of the 'context'.
00843 
00844     Explicit receive mode is analogous to the paradigm of the socket programming
00845     in which an application utilize the recv() function call. It is anticipated
00846     that applications which would make use of limited set of MQTT messages may
00847     find this mode of operation useful. Applications which intend to operate the
00848     'context' in this mode must not provision any callbacks.
00849 
00850     On the other hand, certain applications, may prefer an asynchronous mode of
00851     operation and would want the client LIB 'context' to raise callbacks into
00852     the application, as and when, packets arrive from the server. And such
00853     applications must provide the callback routines.
00854 
00855     @param[in] ctx_cfg configuration information for the Network Context. 
00856     @param[in] ctx_cbs callback routines. Must be set to NULL, if the application
00857     intends to operate the context in the sync-wait / explicit receive mode.
00858     @param[in] app     handle to application. Returned by LIB in other routines
00859     to refer to the underlying context.
00860     @param[out] ctx reference to the context created and is provisioned by the
00861     implementation. (Valid only if routine returns a success)
00862 
00863     @return 0 on success otherwise -1.
00864 */
00865 int32_t mqtt_client_ctx_create(const struct mqtt_client_ctx_cfg *ctx_cfg,
00866                            const struct mqtt_client_ctx_cbs *ctx_cbs,
00867                            void *app, void **ctx);
00868 
00869 /** Delete a Network Connection Context.
00870     This routines destroys the previously created network 'context' and releases
00871     resources that would be assigned for maintaining the information about the
00872     'context'.
00873 
00874     A user or a task prior to deleting the 'context' must ensure that there is no
00875     active MQTT connection on this context.
00876 
00877     @param[in] ctx handle to network context to be deleted. The context must
00878     have been previously created.
00879 
00880     @return 0 on success otherwise -1
00881 */
00882 
00883 int32_t mqtt_client_ctx_delete(void *ctx);
00884 
00885 /** Contruct / Data to initialize MQTT Client Library */
00886 struct mqtt_client_lib_cfg {
00887 
00888         /** If an application has more than one contexts (i.e. grouped contexts)
00889             to manage in a single task, then a non-zero value must be provided.
00890             Otherwise, this parameter must be set to zero.
00891         */
00892         uint16_t   loopback_port;
00893         bool  grp_uses_cbfn;  /**< Assert if grouped contexts use call-backs */
00894 
00895         /** For a multi-task environment, provide a handle to platform mutex */
00896         void  *mutex;
00897         void (*mutex_lockin)(void *mutex); /**< Take platform mutex function */
00898         void (*mutex_unlock)(void *mutex); /**< Give platform mutex function */
00899 
00900         int32_t  (*debug_printf)(const char *format, ...);   /**< Debug, mandatory */
00901         bool  aux_debug_en;    /**< Assert to indicate additional debug info */
00902 };
00903 
00904 /** Initialize the MQTT client library.
00905     This routine initializes all the common constructs that are required to
00906     manage the multiple network connetions. The client LIB must be initialized
00907     prior to invoking of any other routine or service.
00908 
00909     @note This routine must be invoked only once in an run of the system.
00910 
00911     Depending upon the deployment needs, this routine can be invoked either as
00912     part of the platform initialization sequence or as part of the application.
00913     Deployments that have more than one application utilizing the services of
00914     the client LIB should try to invoke the routine from the initialization
00915     sequence of the platform.
00916 
00917     In addition, if an application has to manage more than one network
00918     connections (i.e. in other words, if the application has to handle
00919     a group of connections), then certain configuration must be set in
00920     the LIB @see struct mqtt_client_lib_cfg
00921 
00922     @note There must be only one group of network connetions in the system.
00923 
00924     @param[in] cfg Configuration information for the MQTT client Library.
00925 
00926     @return 0 on success otherwise -1.
00927 */
00928 
00929 int32_t mqtt_client_lib_init(const struct mqtt_client_lib_cfg  *cfg);
00930 
00931 /** Exit the MQTT client library.
00932     @return 0 on success otherwise -1.
00933 */
00934 int32_t mqtt_client_lib_exit(void);
00935 
00936 /** @} */ /* End group client_api */
00937 
00938 }//namespace mbed_mqtt 
00939 
00940 #ifdef __cplusplus  
00941 }
00942 #endif 
00943 
00944 #endif
00945