TI's MQTT Demo with freertos CM4F

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers server_pkts.h Source File

server_pkts.h

Go to the documentation of this file.
00001 /******************************************************************************
00002 *
00003 *   Copyright (C) 2014 Texas Instruments Incorporated
00004 *
00005 *   All rights reserved. Property of Texas Instruments Incorporated.
00006 *   Restricted rights to use, duplicate or disclose this code are
00007 *   granted through contract.
00008 *
00009 *   The program may not be used without the written permission of
00010 *   Texas Instruments Incorporated or against the terms and conditions
00011 *   stipulated in the agreement under which this program has been supplied,
00012 *   and under no circumstances can it be used with non-TI connectivity device.
00013 *
00014 ******************************************************************************/
00015 
00016 #ifndef __SERVER_PKTS_H__
00017 #define __SERVER_PKTS_H__
00018 
00019 #include "mqtt_common.h"
00020 
00021 #ifdef __cplusplus
00022 extern "C"
00023 {
00024 #endif
00025 
00026 namespace mbed_mqtt {
00027 
00028 /*-----------------------------------------------------------------------------
00029  * Note: Do not create additional dependency of this file on any header other
00030  * than mqtt_common.h. Specifically, server_pkts.[hc] in conjunction with the
00031  * mqtt_common.[hc] files must be facilitated to create a stand-alone library.
00032  *-----------------------------------------------------------------------------
00033  */
00034 
00035 /**@file server_pkts.h
00036    The C library provisions the interface / API(s) for the MQTT Server Packet LIB.
00037 
00038    This is a light-weight library that enables the services of the MQTT protcol
00039    for user's server application(s) to exchange the MQTT packets with one or
00040    more remote clients. The Server Packet LIB is a simple and easy-to-use
00041    implementation to support both un-packing of the messages received from the
00042    remote clients and formation of packets to be sent to the remote clients. 
00043 
00044    The library is targeted to conform to MQTT 3.1.1 specification.
00045 
00046    The Server Packet LIB is a highly portable software and implies a very limited
00047    set of dependencies on a platform. Importantly, these limited dependencies are
00048    common features used in the embedded and the networking world, and can be
00049    easily adapted to the target platforms. The services of the library are
00050    multi-task safe. Platform specific atomicity constructs are used, through
00051    abstractions, by the library to maintain data coherency and synchronization.
00052    In addition, the library can be configured to support several in-flight
00053    messages.
00054 
00055    The Server Packet LIB can support multiple and simultaneous MQTT connections
00056    from clients. However, the responsibility of managing the clients and topics,
00057    authentication and approval for connections and supporting any other needs
00058    that specific to the deployment remains with the user application.
00059 
00060    The number of the network connections that the Server Packet LIB can support
00061    is configurable through the compile line option / flag <b> -DCFG_SR_MQTT_CTXS
00062    </b>. In addition, the maximum length of the RX buffer used by the server is
00063    also configurable through the compile line option / flag <b>
00064    -DCFG_SR_MAX_MQP_RX_LEN </b>.
00065 
00066    @note Any future extensions & development must follow the following guidelines.
00067    A new API or an extension to the existing API
00068    a) must be rudimentary
00069    b) must not imply a rule or policy (including a state machine)
00070    b) must ensure simple design and implementation
00071 */
00072 
00073 
00074 /** @defgroup server_pktlib The Server Library API(s)
00075     @{
00076 */
00077 
00078 /** @defgroup conn_utf8_help_group Helper Macros for RX CONNECT
00079     @{
00080 */
00081 
00082 /** Yields pointer to the UTF8 content */
00083 #define MQ_CONN_UTF8_BUF(utf8)      ((utf8)? (utf8)->buffer : NULL)
00084 
00085 /** Length or size of the UTF8 content */
00086 #define MQ_CONN_UTF8_LEN(utf8)      ((utf8)? (utf8)->length : 0)
00087 
00088 #define MQC_UTF8_CLIENTID(utf8_vec) (utf8_vec[0]) /**< Returns Client ID  */
00089 #define MQC_UTF8_WILL_TOP(utf8_vec) (utf8_vec[1]) /**< Returns Will Topic */
00090 #define MQC_UTF8_WILL_MSG(utf8_vec) (utf8_vec[2]) /**< Returns Will Data  */
00091 #define MQC_UTF8_USERNAME(utf8_vec) (utf8_vec[3]) /**< Returns User Name  */
00092 #define MQC_UTF8_PASSWORD(utf8_vec) (utf8_vec[4]) /**< Returns Pass Word  */
00093 
00094 #define MQC_CLIENTID_BUF(utf8_vec)  MQ_CONN_UTF8_BUF(MQC_UTF8_CLIENTID(utf8_vec))
00095 #define MQC_CLIENTID_LEN(utf8_vec)  MQ_CONN_UTF8_LEN(MQC_UTF8_CLIENTID(utf8_vec))
00096 
00097 #define MQC_WILL_TOP_BUF(utf8_vec)  MQ_CONN_UTF8_BUF(MQC_UTF8_WILL_TOP(utf8_vec))
00098 #define MQC_WILL_TOP_LEN(utf8_vec)  MQ_CONN_UTF8_LEN(MQC_UTF8_WILL_TOP(utf8_vec))
00099 
00100 #define MQC_WILL_MSG_BUF(utf8_vec)  MQ_CONN_UTF8_BUF(MQC_UTF8_WILL_MSG(utf8_vec))
00101 #define MQC_WILL_MSG_LEN(utf8_vec)  MQ_CONN_UTF8_LEN(MQC_UTF8_WILL_MSG(utf8_vec))
00102 
00103 #define MQC_USERNAME_BUF(utf8_vec)  MQ_CONN_UTF8_BUF(MQC_UTF8_USERNAME(utf8_vec))
00104 #define MQC_USERNAME_LEN(utf8_vec)  MQ_CONN_UTF8_LEN(MQC_UTF8_USERNAME(utf8_vec))
00105 
00106 #define MQC_PASSWORD_BUF(utf8_vec)  MQ_CONN_UTF8_BUF(MQC_UTF8_PASSWORD(utf8_vec))
00107 #define MQC_PASSWORD_LEN(utf8_vec)  MQ_CONN_UTF8_LEN(MQC_UTF8_PASSWORD(utf8_vec))
00108 
00109 /** @} */
00110 
00111 #ifndef CFG_SR_MAX_MQP_RX_LEN
00112 #define MQP_SERVER_RX_LEN  1024  /**< Max size(B) of RX Buffer for MQTT Server */
00113 #else
00114 #define MQP_SERVER_RX_LEN  CFG_SR_MAX_MQP_RX_LEN
00115 #endif
00116 
00117 /** Send a Variable Header only message to the client.
00118     Application should this routine to send PUBREL and PUBCOMP messages.
00119 
00120     @param[in] ctx_cl handle to the underlying network context in the LIB. This
00121     handle is provided to the application by the LIB in the CONNECT callback.
00122     @param[in] msg_type message type that has to be sent to the client
00123     @param[in] qos QoS with which the message needs to send to server
00124     @param[in] has_vh does this message has data in the variable header?
00125     @param[in] vh_data data <MSB:LSB> to be included in the variable header
00126     @return on success, the number of bytes transferred. Otherwise, errors
00127     defined in @ref lib_err_group
00128 */
00129 int32_t mqtt_vh_msg_send(void *ctx_cl, uint8_t msg_type, enum mqtt_qos qos,
00130                      bool has_vh, uint16_t vh_data);
00131 
00132 /** mqtt_vh_msg_send() with mutual exclusion (in multi-task application).
00133     This routine ensures that the LIB sends the specified VH MSG onto the network
00134     in a manner that excludes execution of any other control. This API has been
00135     enabled to support the scenarios, where the multi-tasked user application has
00136     chosen to use a mutex object other than the one provisioned in the packet LIB
00137     to streamline / serialize accesses to the services of the packet LIB.
00138 
00139     Refer to @ref mqtt_vh_msg_send for details
00140 */
00141 int32_t mqtt_vh_msg_send_locked(void *ctx_cl, uint8_t msg_type, enum mqtt_qos qos,
00142                             bool has_vh, uint16_t vh_data);
00143 
00144 /** Dispatch application constructed PUBLISH message to the client. 
00145     Prior to sending the message to the client, this routine shall update the
00146     fixed-header to account for the duplicate flag that has been indicated by
00147     the caller.
00148 
00149     The caller must populate the payload information of topic and data before
00150     invoking this service. In addition, the application must prepare, for the
00151     packet, the fix header leaving aside the duplicate flag - this flag shall
00152     be included in the fix heder by the LIB.
00153 
00154     This service facilitates the application to re-use, iteratively, a single
00155     PUBLISH packet for multiple remote clients that have subscribed to the
00156     same topic for which the data is being published. The LIB does not free-up
00157     the MQTT packet after sending the packet to the remote client and the
00158     application is responsible for managing the packet container / memory
00159 
00160     @param[in] ctx_cl handle to the underlying network context in the LIB. This
00161     handle is provided to the application by the LIB in the CONNECT callback.
00162     @param[in] mqp app created PUBLISH message alongwith the fixed header
00163     @param[in] dup is this a duplicate message that is being sent to client?
00164     @return on success, the number of bytes transferred. Otherwise, error
00165     defined in @ref lib_err_group
00166 */
00167 int32_t mqtt_server_pub_dispatch(void *ctx_cl, struct mqtt_packet *mqp, bool dup);
00168 
00169 /** mqtt_server_pub_dispatch() with mutual exclusion (in multi-task application).
00170     This routine ensures that the LIB sends the specified packet onto the network
00171     in a manner that excludes execution of any other control. This API has been
00172     enabled to support the scenarios, where the multi-tasked user application has
00173     chosen to use a mutex object other than the one provisioned in the packet LIB
00174     to streamline / serialize accesses to the services of the packet LIB.
00175 
00176     Refer to @ref mqtt_server_pub_dispatch for other details.
00177 */
00178 int32_t mqtt_server_pub_dispatch_locked(void *ctx_cl, struct mqtt_packet *mqp,
00179                                     bool dup);
00180 
00181 /** Run the server packet LIB for the specified wait time.
00182     This routine yields the control back to the application after the specified
00183     duration of wait time. Such an arrangement enable the application to make
00184     overall progress to meet it intended functionality. 
00185 
00186     The wait time implies the maximum intermediate duration between the reception
00187     of two successive messages from the server. If no message is received before
00188     the expiry of the wait time, the routine returns. However, the routine would
00189     continue to block, in case, messages are being received within the successive
00190     period of wait time.
00191 
00192     @param[in] wait_secs maximum time to wait for a message from the server
00193 
00194     @note if the value of MQP_ERR_LIBQUIT is returned, then system must be
00195     restarted.
00196 */
00197 int32_t mqtt_server_run(uint32_t wait_secs);
00198 
00199 /** Abstraction for the device specific network services
00200     Network services for communication with the clients
00201 
00202     @param[in] net refers to network services supported by the platform
00203     @return on success, 0, otherwise -1
00204 
00205     @ref net_ops_group
00206     @note all entries in net must be supported by the platform.
00207 */
00208 int32_t mqtt_server_register_net_svc(const struct device_net_services *net);
00209 
00210 
00211 /** <b> Working Principle </b> for implementing the call-back services:
00212     Implementation of the call-back services should report in return value, only
00213     about errors found in the RX processing. Specifically, the status of TX as a
00214     follow-up to RX message (represented as a call-back service) need not be
00215     reported to the server packet library.
00216 
00217     Error observed in TX (supported by appropriate API(s) / services in the
00218     service packet library) is recorded in the 'context' and shall be dealt in
00219     the next iteration of RX loop.
00220 */
00221 struct mqtt_server_msg_cbs {
00222 
00223         /** Indicate the CONNECT Message from the client
00224             This routine provides, to the application, information about the
00225             connection request that a remote client has made. The application
00226             should utilize the credential and other data presented by the LIB
00227             to authenticate, analyze and finally, approve or deny the request.
00228 
00229             Application at its discretion can also imply deployment specific
00230             policies to make decision about allowing or refusing the request.
00231 
00232             The return value of this routine is a 16bit value that commensurates
00233             with the 'variable header' of the CONNACK message. Specifically, the
00234             LSB of the 16bit return value corresponds to the 8bit 'return code'
00235             parameter in the CONNACK message and the MSB to the 'acknowledge
00236             flags'. The application must set a valid return value.
00237 
00238             The LIB uses the return value to compose the CONNACK message to the
00239             remote client. If the LSB of return value is a 'non zero' value,
00240             then the LIB, after sending the CONNACK message to the remote client,
00241             will terminate the network connection.
00242 
00243             @param[in] ctx_cl handle to the underlying network context in the LIB
00244             @param[in] conn_flags options received in CONNECT message from server
00245             @param[in] utf8_vec vector / array of pointers to UTF8 information.
00246             The order of UTF8 information is client-id, will topic, will-message,
00247             user-name and pass-word. A NULL in vector element indicates absence
00248             of that particular UTF8 information.
00249             @param[out] usr place holder for application to provide connection
00250             specific handle. In subsequent calls from the implementation this
00251             handle will be passed as a parameter to enable application to refer
00252             to the particular active connection.
00253 
00254             @return 16bit value for the variable header of the CONNACK message,
00255             MSB is CONNACK-Flags, LSB is CONNACK-RC
00256         */
00257         uint16_t  (*connect_rx)(void *ctx_cl, uint8_t conn_flags,
00258                            struct utf8_string * const *utf8_vec, void **usr);
00259 
00260         /** Indicate the SUBSCRIBE Message from the client
00261             This routine provides, to the application, information about the
00262             topics that the remote client intends to subscribe to.
00263 
00264             On return from this routine, if the application has found a problem
00265             in the processing of message, then the LIB will simply terminate the
00266             associated network connection.
00267 
00268             @param[in] usr_cl handle to connection context in the application
00269             @param[in] qos_topics an array of topic along-with its qos
00270             @param[in] n_topics the count / number of elements in the array
00271             @param[in] msg_id the associated message ID provided by the client
00272             @param[in] acks place holder array for the application to provide
00273             finalized qos for each of the subscribed topic. The order of ack
00274             is same as that of qos_topics
00275 
00276             @return The application should return false, if it encounters any
00277             problem in the processing of topic. Otherwise, true.
00278 
00279             @note The memory space pointed by the 'buffer' field in the elements
00280             of 'qos_topics' array has an additional byte available beyond the
00281             size of memory indicated by the 'length' field. This extra byte can
00282             be used by the application to NUL terminate the buffer. <b> This
00283             quirk is applicable to this routine only. </b>
00284         */
00285         bool (*sub_msg_rx)(void *usr_cl, const struct utf8_strqos *qos_topics,
00286                           uint32_t n_topics, uint16_t msg_id, uint8_t *acks);
00287 
00288         /** Indicate the UNSUBSCRIBE Message from the client
00289             This routine provides, to the application, information about the
00290             topics that the remote client intends to unsubscribe.
00291 
00292             On return from this routine, if the application has found a problem
00293             in the processing of message, then the LIB will simply terminate the
00294             associated network connection.
00295 
00296             @param[in] usr_cl handle to connection context in the application
00297             @param[in] topics an array of topic in the message
00298             @param[in] n_topics the count / number of elements in the array
00299             @param[in] msg_id the associated message ID provided by the client
00300 
00301             @return The application should return false, if it encounters any
00302             problem in the processing of topic. Otherwise, true.
00303         */
00304         bool (*un_sub_msg)(void *usr_cl, const struct utf8_string *topics,
00305                            uint32_t n_topics, uint16_t msg_id);
00306 
00307         /** Indicate the PUBLISH Message from the client.
00308             This routine provides, to the application, the binary data along-with
00309             its qualifiers and the topic to which a remote client has published
00310             data.
00311 
00312             On return from this routine, if the application has found a problem
00313             in processing of the contents of the PUBLISH message, the LIB will
00314             simply terminate the associated network connection. Otherwise,
00315             depending upon the QoS level of the PUBLISH message, the LIB shall
00316             dispatch the ACK (PUBACK or PUBREC) to the client, thereby,
00317             relieveing the application from this support.
00318 
00319             @param[in] usr_cl handle to connection context in the application
00320             @param[in] topic UTF8 Topic Name for which data has been published
00321             @param[in] data_buf the published binary data for the topic
00322             @param[in] data_len the length of the binary data
00323             @param[in] msg_id the associated message ID provided by the client
00324             @param[in] dup has client indicated this as a duplicate message
00325             @param[in] qos quality of service of the message
00326             @param[in] retain should the server retain the data?
00327 
00328             @return The application should return false, if it encounters any
00329             problem in the processing of data, topic and related resources.
00330             Otherwise, true.
00331         */
00332         bool (*pub_msg_rx)(void *usr_cl, const struct utf8_string *topic,
00333                            const uint8_t *data_buf, uint32_t data_len, uint16_t msg_id,
00334                            bool dup, enum mqtt_qos qos, bool retain);
00335 
00336         /** Notify the acknowledgement that was received from the remote client.
00337             Following are the messages that are notified by the server LIB.
00338 
00339             PUBACK, PUBREC, PUBREL, PUBCOMP
00340 
00341             On return from this routine, if the application has found problem
00342             in processing the ACK message, then the LIB will simply terminate
00343             the associated network connection
00344 
00345             @param[in] usr_cl handle to connection context in the application
00346             @param[in] msg_type refers to the type of ACK message
00347             @param[in] msg_id the associated message ID provided by the client
00348             @return application should return false if the ACK was not expected
00349             by it or no reference was found for it. Otherwise true.
00350         */
00351         bool (*ack_notify)(void *usr_cl, uint8_t msg_type, uint16_t msg_id);
00352 
00353         /** Notify that network connection to client has been closed.
00354             This routine is invoked by the LIB to declare to the application that
00355             the network connection to a particular client has been terminated and
00356             follow-up, if needed, can now commence. If configured, removal of the
00357             client session and / or dispatch of the WILL message, will be typical
00358             aspects, among others, to follow-up. The routine aids the application
00359             by indicating if an error condition had caused the closure.
00360 
00361             This routine is invoked by the LIB irrespective of the source entity,
00362             server or client, that has caused the closure of the network.
00363 
00364             @param[in] usr_cl handle to connection context in the application
00365             @param[in] due2err has the connection been closed due to an error?
00366         */
00367         void (*on_cl_net_close)(void *usr_cl, bool due2err);
00368 
00369         /** Notify that CONNACK has been sent to the specified client.
00370             This routine is invoked by the LIB to enable the application to make
00371             progress and follow-up on the session information for the particular
00372             client. Specifically, this routine facilitates the application to
00373             either delete the session or re-send / sync-up the pending messages
00374             associated with the client. The follow-up action is depenedent upon
00375             the 'clean_session' option in the CONNECT message from the client.
00376             @param[in] usr_cl handle to connection context in the application
00377             @param[in] clean_session was a clean session requested in CONNECT?
00378         */
00379         void (*on_connack_send)(void *usr_cl, bool clean_session);
00380 };
00381 
00382 struct mqtt_server_lib_cfg {
00383 
00384         /** Port to listen to incoming network connections from the clients */
00385         uint16_t   listener_port;
00386 
00387         /** If the server application has more than one task and / or supports
00388             at-least one plug-in, then a non-zero value must be provided.
00389             Otherwise, this parameter must be set to zero. This parameter is
00390             used by the implementation to synchronize multiple tasks for the
00391             network connection.
00392         */
00393         uint16_t   loopback_port;
00394 
00395         /** For a multi-task enviroment, provide a handle to platform mutex */
00396         void  *mutex;
00397         void (*mutex_lockin)(void *mutex);
00398         void (*mutex_unlock)(void *mutex);
00399 
00400         int32_t  (*debug_printf)(const char *format, ...);  /**< Debug, mandatory */
00401         bool   aux_debug_en;  /**< Assert to indicate additional debug info */
00402 
00403 };
00404 
00405 /** Initialize the MQTT Server Packet library
00406     This routine initializes the packet and network constructs that are required
00407     to manage the multiple network connetions. The server packet LIB must be
00408     initialized prior to invoking of any other routine or service.
00409 
00410     @note This routine must be invoked only once in an run of the system.
00411 
00412     If there are more than one application (tasks) that utilize the services
00413     of the server packet library, then certain configuration must be set in
00414     the LIB @see struct mqtt_server_lib_cfg
00415 
00416     The application should also provision the platform network specific network
00417     services into the packet library @see mqtt_server_register_net_svc.
00418 
00419     Once, the server LIB has been intialized successfully, it must be put into
00420     action, to listen to requests for incoming connections, by invoking the API
00421     @ref mqtt_server_run.
00422 
00423     @param[in] cfg configuration information for the MQTT server packet library
00424     @param[in] cbs callback routines that LIB will invoke into the application
00425 
00426     @return 0 on success otherwise -1.
00427 */
00428 int32_t mqtt_server_lib_init(const struct mqtt_server_lib_cfg *cfg,
00429                          const struct mqtt_server_msg_cbs *cbs);
00430 
00431 /** @} */ /* End of server_pktlib */
00432 
00433 }//namespace mbed_mqtt 
00434 
00435 #ifdef __cplusplus  
00436 }
00437 #endif 
00438 
00439 #endif
00440