Add missing files so base MQTT project builds.

This commit is contained in:
Richard Barry 2019-07-19 00:37:33 +00:00
parent d708efe997
commit 5dd6cf1295
18 changed files with 14266 additions and 0 deletions

View file

@ -0,0 +1,823 @@
/*
* Amazon FreeRTOS MQTT V2.0.0
* Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file iot_mqtt.h
* @brief User-facing functions of the MQTT 3.1.1 library.
*/
#ifndef IOT_MQTT_H_
#define IOT_MQTT_H_
/* The config header is always included first. */
#include "iot_config.h"
/* MQTT types include. */
#include "types/iot_mqtt_types.h"
/*------------------------- MQTT library functions --------------------------*/
/**
* @functionspage{mqtt,MQTT library}
* - @functionname{mqtt_function_init}
* - @functionname{mqtt_function_cleanup}
* - @functionname{mqtt_function_receivecallback}
* - @functionname{mqtt_function_connect}
* - @functionname{mqtt_function_disconnect}
* - @functionname{mqtt_function_subscribe}
* - @functionname{mqtt_function_timedsubscribe}
* - @functionname{mqtt_function_unsubscribe}
* - @functionname{mqtt_function_timedunsubscribe}
* - @functionname{mqtt_function_publish}
* - @functionname{mqtt_function_timedpublish}
* - @functionname{mqtt_function_wait}
* - @functionname{mqtt_function_strerror}
* - @functionname{mqtt_function_operationtype}
* - @functionname{mqtt_function_issubscribed}
*/
/**
* @functionpage{IotMqtt_Init,mqtt,init}
* @functionpage{IotMqtt_Cleanup,mqtt,cleanup}
* @functionpage{IotMqtt_ReceiveCallback,mqtt,receivecallback}
* @functionpage{IotMqtt_Connect,mqtt,connect}
* @functionpage{IotMqtt_Disconnect,mqtt,disconnect}
* @functionpage{IotMqtt_Subscribe,mqtt,subscribe}
* @functionpage{IotMqtt_TimedSubscribe,mqtt,timedsubscribe}
* @functionpage{IotMqtt_Unsubscribe,mqtt,unsubscribe}
* @functionpage{IotMqtt_TimedUnsubscribe,mqtt,timedunsubscribe}
* @functionpage{IotMqtt_Publish,mqtt,publish}
* @functionpage{IotMqtt_TimedPublish,mqtt,timedpublish}
* @functionpage{IotMqtt_Wait,mqtt,wait}
* @functionpage{IotMqtt_strerror,mqtt,strerror}
* @functionpage{IotMqtt_OperationType,mqtt,operationtype}
* @functionpage{IotMqtt_IsSubscribed,mqtt,issubscribed}
*/
/**
* @brief One-time initialization function for the MQTT library.
*
* This function performs setup of the MQTT library. <b>It must be called
* once (and only once) before calling any other MQTT function.</b> Calling this
* function more than once without first calling @ref mqtt_function_cleanup
* may result in a crash.
*
* @return One of the following:
* - #IOT_MQTT_SUCCESS
* - #IOT_MQTT_INIT_FAILED
*
* @warning No thread-safety guarantees are provided for this function.
*
* @see @ref mqtt_function_cleanup
*/
/* @[declare_mqtt_init] */
IotMqttError_t IotMqtt_Init( void );
/* @[declare_mqtt_init] */
/**
* @brief One-time deinitialization function for the MQTT library.
*
* This function frees resources taken in @ref mqtt_function_init. It should be
* called after [closing all MQTT connections](@ref mqtt_function_disconnect) to
* clean up the MQTT library. After this function returns, @ref mqtt_function_init
* must be called again before calling any other MQTT function.
*
* @warning No thread-safety guarantees are provided for this function. Do not
* call this function if any MQTT connections are open!
*
* @see @ref mqtt_function_init
*/
/* @[declare_mqtt_cleanup] */
void IotMqtt_Cleanup( void );
/* @[declare_mqtt_cleanup] */
/**
* @brief Network receive callback for the MQTT library.
*
* This function should be called by the system whenever data is available for
* the MQTT library.
*
* @param[in] pNetworkConnection The network connection associated with the MQTT
* connection, passed by the network stack.
* @param[in] pReceiveContext A pointer to the MQTT connection handle for which
* the packet was received.
*/
/* @[declare_mqtt_receivecallback] */
void IotMqtt_ReceiveCallback( void * pNetworkConnection,
void * pReceiveContext );
/* @[declare_mqtt_receivecallback] */
/**
* @brief Establish a new MQTT connection.
*
* This function opens a connection between a new MQTT client and an MQTT server
* (also called a <i>broker</i>). MQTT connections are established on top of transport
* layer protocols (such as TCP/IP), and optionally, application layer security
* protocols (such as TLS). The MQTT packet that establishes a connection is called
* the MQTT CONNECT packet. After @ref mqtt_function_init, this function must be
* called before any other MQTT library function.
*
* If [pConnectInfo->cleanSession](@ref IotMqttConnectInfo_t.cleanSession) is `true`,
* this function establishes a clean MQTT session. Subscriptions and unacknowledged
* PUBLISH messages will be discarded when the connection is closed.
*
* If [pConnectInfo->cleanSession](@ref IotMqttConnectInfo_t.cleanSession) is `false`,
* this function establishes (or re-establishes) a persistent MQTT session. The parameters
* [pConnectInfo->pPreviousSubscriptions](@ref IotMqttConnectInfo_t.pPreviousSubscriptions)
* and [pConnectInfo->previousSubscriptionCount](@ref IotMqttConnectInfo_t.previousSubscriptionCount)
* may be used to restore subscriptions present in a re-established persistent session.
* Any restored subscriptions <b>MUST</b> have been present in the persistent session;
* <b>this function does not send an MQTT SUBSCRIBE packet!</b>
*
* This MQTT library is network agnostic, meaning it has no knowledge of the
* underlying network protocol carrying the MQTT packets. It interacts with the
* network through a network abstraction layer, allowing it to be used with many
* different network stacks. The network abstraction layer is established
* per-connection, allowing every #IotMqttConnection_t to use a different network
* stack. The parameter `pNetworkInterface` sets up the network abstraction layer
* for an MQTT connection; see the documentation on #IotMqttNetworkInfo_t for details
* on its members.
*
* The `pConnectInfo` parameter provides the contents of the MQTT CONNECT packet.
* Most members [are defined by the MQTT spec.](@ref IotMqttConnectInfo_t). The
* [pConnectInfo->pWillInfo](@ref IotMqttConnectInfo_t.pWillInfo) member provides
* information on a Last Will and Testament (LWT) message to be published if the
* MQTT connection is closed without [sending a DISCONNECT packet]
* (@ref mqtt_function_disconnect). Unlike other PUBLISH
* messages, a LWT message payload is limited to 65535 bytes in length. Additionally,
* the retry [interval](@ref IotMqttPublishInfo_t.retryMs) and [limit]
* (@ref IotMqttPublishInfo_t.retryLimit) members of #IotMqttPublishInfo_t
* are ignored for LWT messages. The LWT message is optional; `pWillInfo` may be NULL.
*
* Unlike @ref mqtt_function_publish, @ref mqtt_function_subscribe, and
* @ref mqtt_function_unsubscribe, this function is always blocking. Additionally,
* because the MQTT connection acknowledgement packet (CONNACK packet) does not
* contain any information on <i>which</i> CONNECT packet it acknowledges, only one
* CONNECT operation may be in progress at any time. This means that parallel
* threads making calls to @ref mqtt_function_connect will be serialized to send
* their CONNECT packets one-by-one.
*
* @param[in] pNetworkInfo Information on the transport-layer network connection
* to use with the MQTT connection.
* @param[in] pConnectInfo MQTT connection setup parameters.
* @param[in] timeoutMs If the MQTT server does not accept the connection within
* this timeout, this function returns #IOT_MQTT_TIMEOUT.
* @param[out] pMqttConnection Set to a newly-initialized MQTT connection handle
* if this function succeeds.
*
* @return One of the following:
* - #IOT_MQTT_SUCCESS
* - #IOT_MQTT_BAD_PARAMETER
* - #IOT_MQTT_NO_MEMORY
* - #IOT_MQTT_NETWORK_ERROR
* - #IOT_MQTT_SCHEDULING_ERROR
* - #IOT_MQTT_BAD_RESPONSE
* - #IOT_MQTT_TIMEOUT
* - #IOT_MQTT_SERVER_REFUSED
*
* <b>Example</b>
* @code{c}
* // An initialized and connected network connection.
* IotNetworkConnection_t pNetworkConnection;
*
* // Parameters to MQTT connect.
* IotMqttConnection_t mqttConnection = IOT_MQTT_CONNECTION_INITIALIZER;
* IotMqttNetworkInfo_t networkInfo = IOT_MQTT_NETWORK_INFO_INITIALIZER;
* IotMqttConnectInfo_t connectInfo = IOT_MQTT_CONNECT_INFO_INITIALIZER;
* IotMqttPublishInfo_t willInfo = IOT_MQTT_PUBLISH_INFO_INITIALIZER;
*
* // Example network abstraction types.
* IotNetworkServerInfo_t serverInfo = { ... };
* IotNetworkCredentialInfo_t credentialInfo = { ... };
* IotNetworkInterface_t networkInterface = { ... };
*
* // Example using a generic network implementation.
* networkInfo.createNetworkConnection = true;
* networkInfo.pNetworkServerInfo = &serverInfo;
* networkInfo.pNetworkCredentialInfo = &credentialInfo;
* networkInfo.pNetworkInterface = &networkInterface;
*
* // Set the members of the connection info (password and username not used).
* connectInfo.cleanSession = true;
* connectInfo.keepAliveSeconds = 30;
* connectInfo.pClientIdentifier = "uniqueclientidentifier";
* connectInfo.clientIdentifierLength = 22;
*
* // Set the members of the will info (retain and retry not used).
* willInfo.qos = IOT_MQTT_QOS_1;
* willInfo.pTopicName = "will/topic/name";
* willInfo.topicNameLength = 15;
* willInfo.pPayload = "MQTT client unexpectedly disconnected.";
* willInfo.payloadLength = 38;
*
* // Set the pointer to the will info.
* connectInfo.pWillInfo = &willInfo;
*
* // Call CONNECT with a 5 second block time. Should return
* // IOT_MQTT_SUCCESS when successful.
* IotMqttError_t result = IotMqtt_Connect( &networkInfo,
* &connectInfo,
* 5000,
* &mqttConnection );
*
* if( result == IOT_MQTT_SUCCESS )
* {
* // Do something with the MQTT connection...
*
* // Clean up and close the MQTT connection once it's no longer needed.
* IotMqtt_Disconnect( mqttConnection, 0 );
* }
* @endcode
*/
/* @[declare_mqtt_connect] */
IotMqttError_t IotMqtt_Connect( const IotMqttNetworkInfo_t * pNetworkInfo,
const IotMqttConnectInfo_t * pConnectInfo,
uint32_t timeoutMs,
IotMqttConnection_t * const pMqttConnection );
/* @[declare_mqtt_connect] */
/**
* @brief Closes an MQTT connection and frees resources.
*
* This function closes an MQTT connection and should only be called once
* the MQTT connection is no longer needed. Its exact behavior depends on the
* `flags` parameter.
*
* Normally, `flags` should be `0`. This gracefully shuts down an MQTT
* connection by sending an MQTT DISCONNECT packet. Any [network close function]
* (@ref IotNetworkInterface_t::close) provided [when the connection was established]
* (@ref mqtt_function_connect) will also be called. Note that because the MQTT server
* will not acknowledge a DISCONNECT packet, the client has no way of knowing if
* the server received the DISCONNECT packet. In the case where the DISCONNECT
* packet is lost in transport, any Last Will and Testament (LWT) message established
* with the connection may be published. However, if the DISCONNECT reaches the
* MQTT server, the LWT message will be discarded and not published.
*
* Should the underlying network connection become unusable, this function should
* be called with `flags` set to #IOT_MQTT_FLAG_CLEANUP_ONLY. In this case, no
* DISCONNECT packet will be sent, though the [network close function](@ref IotNetworkInterface_t::close)
* will still be called. This function will only free the resources used by the MQTT
* connection; it still must be called even if the network is offline to avoid leaking
* resources.
*
* Once this function is called, its parameter `mqttConnection` should no longer
* be used.
*
* @param[in] mqttConnection The MQTT connection to close and clean up.
* @param[in] flags Flags which modify the behavior of this function. See @ref mqtt_constants_flags.
*/
/* @[declare_mqtt_disconnect] */
void IotMqtt_Disconnect( IotMqttConnection_t mqttConnection,
uint32_t flags );
/* @[declare_mqtt_disconnect] */
/**
* @brief Subscribes to the given array of topic filters and receive an asynchronous
* notification when the subscribe completes.
*
* This function transmits an MQTT SUBSCRIBE packet to the server. A SUBSCRIBE
* packet notifies the server to send any matching PUBLISH messages to this client.
* A single SUBSCRIBE packet may carry more than one topic filter, hence the
* parameters to this function include an array of [subscriptions]
* (@ref IotMqttSubscription_t).
*
* An MQTT subscription has two pieces:
* 1. The subscription topic filter registered with the MQTT server. The MQTT
* SUBSCRIBE packet sent from this client to server notifies the server to send
* messages matching the given topic filters to this client.
* 2. The [callback function](@ref IotMqttCallbackInfo_t.function) that this
* client will invoke when an incoming message is received. The callback function
* notifies applications of an incoming PUBLISH message.
*
* The helper function @ref mqtt_function_issubscribed can be used to check if a
* [callback function](@ref IotMqttCallbackInfo_t.function) is registered for
* a particular topic filter.
*
* To modify an already-registered subscription callback, call this function with
* a new `pSubscriptionList`. Any topic filters in `pSubscriptionList` that already
* have a registered callback will be replaced with the new values in `pSubscriptionList`.
*
* @attention QoS 2 subscriptions are currently unsupported. Only 0 or 1 are valid
* for subscription QoS.
*
* @param[in] mqttConnection The MQTT connection to use for the subscription.
* @param[in] pSubscriptionList Pointer to the first element in the array of
* subscriptions.
* @param[in] subscriptionCount The number of elements in pSubscriptionList.
* @param[in] flags Flags which modify the behavior of this function. See @ref mqtt_constants_flags.
* @param[in] pCallbackInfo Asynchronous notification of this function's completion.
* @param[out] pSubscribeOperation Set to a handle by which this operation may be
* referenced after this function returns. This reference is invalidated once
* the subscription operation completes.
*
* @return This function will return #IOT_MQTT_STATUS_PENDING upon success.
* @return Upon completion of the subscription (either through an
* #IotMqttCallbackInfo_t or @ref mqtt_function_wait), the status will be one of:
* - #IOT_MQTT_SUCCESS
* - #IOT_MQTT_NETWORK_ERROR
* - #IOT_MQTT_SCHEDULING_ERROR
* - #IOT_MQTT_BAD_RESPONSE
* - #IOT_MQTT_SERVER_REFUSED
* @return If this function fails before queuing a subscribe operation, it will return
* one of:
* - #IOT_MQTT_BAD_PARAMETER
* - #IOT_MQTT_NO_MEMORY
*
* @see @ref mqtt_function_timedsubscribe for a blocking variant of this function.
* @see @ref mqtt_function_unsubscribe for the function that removes subscriptions.
*
* <b>Example</b>
* @code{c}
* #define NUMBER_OF_SUBSCRIPTIONS ...
*
* // Subscription callback function.
* void subscriptionCallback( void * pArgument, IotMqttCallbackParam_t * pPublish );
*
* // An initialized and connected MQTT connection.
* IotMqttConnection_t mqttConnection;
*
* // Subscription information.
* pSubscriptions[ NUMBER_OF_SUBSCRIPTIONS ] = { IOT_MQTT_SUBSCRIPTION_INITIALIZER };
* IotMqttOperation_t lastOperation = IOT_MQTT_OPERATION_INITIALIZER;
*
* // Set the subscription information.
* for( int i = 0; i < NUMBER_OF_SUBSCRIPTIONS; i++ )
* {
* pSubscriptions[ i ].qos = IOT_MQTT_QOS_1;
* pSubscriptions[ i ].pTopicFilter = "some/topic/filter";
* pSubscriptions[ i ].topicLength = ( uint16_t ) strlen( pSubscriptions[ i ].pTopicFilter );
* pSubscriptions[ i ].callback.function = subscriptionCallback;
* }
*
* IotMqttError_t result = IotMqtt_Subscribe( mqttConnection,
* pSubscriptions,
* NUMBER_OF_SUBSCRIPTIONS,
* IOT_MQTT_FLAG_WAITABLE,
* NULL,
* &lastOperation );
*
* // Subscribe returns IOT_MQTT_STATUS_PENDING when successful. Wait up to
* // 5 seconds for the operation to complete.
* if( result == IOT_MQTT_STATUS_PENDING )
* {
* result = IotMqtt_Wait( subscriptionRef, 5000 );
* }
*
* // Check that the subscriptions were successful.
* if( result == IOT_MQTT_SUCCESS )
* {
* // Wait for messages on the subscription topic filters...
*
* // Unsubscribe once the subscriptions are no longer needed.
* result = IotMqtt_Unsubscribe( mqttConnection,
* pSubscriptions,
* NUMBER_OF_SUBSCRIPTIONS,
* IOT_MQTT_FLAG_WAITABLE,
* NULL,
* &lastOperation );
*
* // UNSUBSCRIBE returns IOT_MQTT_STATUS_PENDING when successful.
* // Wait up to 5 seconds for the operation to complete.
* if( result == IOT_MQTT_STATUS_PENDING )
* {
* result = IotMqtt_Wait( lastOperation, 5000 );
* }
* }
* // Check which subscriptions were rejected by the server.
* else if( result == IOT_MQTT_SERVER_REFUSED )
* {
* for( int i = 0; i < NUMBER_OF_SUBSCRIPTIONS; i++ )
* {
* if( IotMqtt_IsSubscribed( mqttConnection,
* pSubscriptions[ i ].pTopicFilter,
* pSubscriptions[ i ].topicFilterLength,
* NULL ) == false )
* {
* // This subscription was rejected.
* }
* }
* }
* @endcode
*/
/* @[declare_mqtt_subscribe] */
IotMqttError_t IotMqtt_Subscribe( IotMqttConnection_t mqttConnection,
const IotMqttSubscription_t * pSubscriptionList,
size_t subscriptionCount,
uint32_t flags,
const IotMqttCallbackInfo_t * pCallbackInfo,
IotMqttOperation_t * pSubscribeOperation );
/* @[declare_mqtt_subscribe] */
/**
* @brief Subscribes to the given array of topic filters with a timeout.
*
* This function transmits an MQTT SUBSCRIBE packet to the server, then waits for
* a server response to the packet. Internally, this function is a call to @ref
* mqtt_function_subscribe followed by @ref mqtt_function_wait. See @ref
* mqtt_function_subscribe for more information about the MQTT SUBSCRIBE operation.
*
* @attention QoS 2 subscriptions are currently unsupported. Only 0 or 1 are valid
* for subscription QoS.
*
* @param[in] mqttConnection The MQTT connection to use for the subscription.
* @param[in] pSubscriptionList Pointer to the first element in the array of
* subscriptions.
* @param[in] subscriptionCount The number of elements in pSubscriptionList.
* @param[in] flags Flags which modify the behavior of this function. See @ref mqtt_constants_flags.
* Currently, flags are ignored by this function; this parameter is for
* future-compatibility.
* @param[in] timeoutMs If the MQTT server does not acknowledge the subscriptions within
* this timeout, this function returns #IOT_MQTT_TIMEOUT.
*
* @return One of the following:
* - #IOT_MQTT_SUCCESS
* - #IOT_MQTT_BAD_PARAMETER
* - #IOT_MQTT_NO_MEMORY
* - #IOT_MQTT_NETWORK_ERROR
* - #IOT_MQTT_SCHEDULING_ERROR
* - #IOT_MQTT_BAD_RESPONSE
* - #IOT_MQTT_TIMEOUT
* - #IOT_MQTT_SERVER_REFUSED
*/
/* @[declare_mqtt_timedsubscribe] */
IotMqttError_t IotMqtt_TimedSubscribe( IotMqttConnection_t mqttConnection,
const IotMqttSubscription_t * pSubscriptionList,
size_t subscriptionCount,
uint32_t flags,
uint32_t timeoutMs );
/* @[declare_mqtt_timedsubscribe] */
/**
* @brief Unsubscribes from the given array of topic filters and receive an asynchronous
* notification when the unsubscribe completes.
*
* This function transmits an MQTT UNSUBSCRIBE packet to the server. An UNSUBSCRIBE
* packet removes registered topic filters from the server. After unsubscribing,
* the server will no longer send messages on these topic filters to the client.
*
* Corresponding [subscription callback functions](@ref IotMqttCallbackInfo_t.function)
* are also removed from the MQTT connection. These subscription callback functions
* will be removed even if the MQTT UNSUBSCRIBE packet fails to send.
*
* @param[in] mqttConnection The MQTT connection used for the subscription.
* @param[in] pSubscriptionList Pointer to the first element in the array of
* subscriptions.
* @param[in] subscriptionCount The number of elements in pSubscriptionList.
* @param[in] flags Flags which modify the behavior of this function. See @ref mqtt_constants_flags.
* @param[in] pCallbackInfo Asynchronous notification of this function's completion.
* @param[out] pUnsubscribeOperation Set to a handle by which this operation may be
* referenced after this function returns. This reference is invalidated once
* the unsubscribe operation completes.
*
* @return This function will return #IOT_MQTT_STATUS_PENDING upon success.
* @return Upon completion of the unsubscribe (either through an
* #IotMqttCallbackInfo_t or @ref mqtt_function_wait), the status will be one of:
* - #IOT_MQTT_SUCCESS
* - #IOT_MQTT_NETWORK_ERROR
* - #IOT_MQTT_SCHEDULING_ERROR
* - #IOT_MQTT_BAD_RESPONSE
* @return If this function fails before queuing an unsubscribe operation, it will return
* one of:
* - #IOT_MQTT_BAD_PARAMETER
* - #IOT_MQTT_NO_MEMORY
*
* @see @ref mqtt_function_timedsubscribe for a blocking variant of this function.
* @see @ref mqtt_function_subscribe for the function that adds subscriptions.
*/
/* @[declare_mqtt_unsubscribe] */
IotMqttError_t IotMqtt_Unsubscribe( IotMqttConnection_t mqttConnection,
const IotMqttSubscription_t * pSubscriptionList,
size_t subscriptionCount,
uint32_t flags,
const IotMqttCallbackInfo_t * pCallbackInfo,
IotMqttOperation_t * pUnsubscribeOperation );
/* @[declare_mqtt_unsubscribe] */
/**
* @brief Unsubscribes from a given array of topic filters with a timeout.
*
* This function transmits an MQTT UNSUBSCRIBE packet to the server, then waits
* for a server response to the packet. Internally, this function is a call to
* @ref mqtt_function_unsubscribe followed by @ref mqtt_function_wait. See @ref
* mqtt_function_unsubscribe for more information about the MQTT UNSUBSCRIBE
* operation.
*
* @param[in] mqttConnection The MQTT connection used for the subscription.
* @param[in] pSubscriptionList Pointer to the first element in the array of
* subscriptions.
* @param[in] subscriptionCount The number of elements in pSubscriptionList.
* @param[in] flags Flags which modify the behavior of this function. See @ref mqtt_constants_flags.
* Currently, flags are ignored by this function; this parameter is for
* future-compatibility.
* @param[in] timeoutMs If the MQTT server does not acknowledge the UNSUBSCRIBE within
* this timeout, this function returns #IOT_MQTT_TIMEOUT.
*
* @return One of the following:
* - #IOT_MQTT_SUCCESS
* - #IOT_MQTT_BAD_PARAMETER
* - #IOT_MQTT_NO_MEMORY
* - #IOT_MQTT_NETWORK_ERROR
* - #IOT_MQTT_SCHEDULING_ERROR
* - #IOT_MQTT_BAD_RESPONSE
*/
/* @[declare_mqtt_timedunsubscribe] */
IotMqttError_t IotMqtt_TimedUnsubscribe( IotMqttConnection_t mqttConnection,
const IotMqttSubscription_t * pSubscriptionList,
size_t subscriptionCount,
uint32_t flags,
uint32_t timeoutMs );
/* @[declare_mqtt_timedunsubscribe] */
/**
* @brief Publishes a message to the given topic name and receive an asynchronous
* notification when the publish completes.
*
* This function transmits an MQTT PUBLISH packet to the server. A PUBLISH packet
* contains a payload and a topic name. Any clients with a subscription on a
* topic filter matching the PUBLISH topic name will receive a copy of the
* PUBLISH packet from the server.
*
* If a PUBLISH packet fails to reach the server and it is not a QoS 0 message,
* it will be retransmitted. See #IotMqttPublishInfo_t for a description
* of the retransmission strategy.
*
* @attention QoS 2 messages are currently unsupported. Only 0 or 1 are valid
* for message QoS.
*
* @param[in] mqttConnection The MQTT connection to use for the publish.
* @param[in] pPublishInfo MQTT publish parameters.
* @param[in] flags Flags which modify the behavior of this function. See @ref mqtt_constants_flags.
* @param[in] pCallbackInfo Asynchronous notification of this function's completion.
* @param[out] pPublishOperation Set to a handle by which this operation may be
* referenced after this function returns. This reference is invalidated once
* the publish operation completes.
*
* @return This function will return #IOT_MQTT_STATUS_PENDING upon success for
* QoS 1 publishes. For a QoS 0 publish it returns #IOT_MQTT_SUCCESS upon
* success.
* @return Upon completion of a QoS 1 publish (either through an
* #IotMqttCallbackInfo_t or @ref mqtt_function_wait), the status will be one of:
* - #IOT_MQTT_SUCCESS
* - #IOT_MQTT_NETWORK_ERROR
* - #IOT_MQTT_SCHEDULING_ERROR
* - #IOT_MQTT_BAD_RESPONSE
* - #IOT_MQTT_RETRY_NO_RESPONSE (if [pPublishInfo->retryMs](@ref IotMqttPublishInfo_t.retryMs)
* and [pPublishInfo->retryLimit](@ref IotMqttPublishInfo_t.retryLimit) were set).
* @return If this function fails before queuing an publish operation (regardless
* of QoS), it will return one of:
* - #IOT_MQTT_BAD_PARAMETER
* - #IOT_MQTT_NO_MEMORY
*
* @note The parameters `pCallbackInfo` and `pPublishOperation` should only be used for QoS
* 1 publishes. For QoS 0, they should both be `NULL`.
*
* @see @ref mqtt_function_timedpublish for a blocking variant of this function.
*
* <b>Example</b>
* @code{c}
* // An initialized and connected MQTT connection.
* IotMqttConnection_t mqttConnection;
*
* // Publish information.
* IotMqttPublishInfo_t publishInfo = IOT_MQTT_PUBLISH_INFO_INITIALIZER;
*
* // Set the publish information. QoS 0 example (retain not used):
* publishInfo.qos = IOT_MQTT_QOS_0;
* publishInfo.pTopicName = "some/topic/name";
* publishInfo.topicNameLength = 15;
* publishInfo.pPayload = "payload";
* publishInfo.payloadLength = 8;
*
* // QoS 0 publish should return IOT_MQTT_SUCCESS upon success.
* IotMqttError_t qos0Result = IotMqtt_Publish( mqttConnection,
* &publishInfo,
* 0,
* NULL,
* NULL );
*
* // QoS 1 with retry example (using same topic name and payload as QoS 0 example):
* IotMqttOperation_t qos1Operation = IOT_MQTT_OPERATION_INITIALIZER;
* publishInfo.qos = IOT_MQTT_QOS_1;
* publishInfo.retryMs = 1000; // Retry if no response is received in 1 second.
* publishInfo.retryLimit = 5; // Retry up to 5 times.
*
* // QoS 1 publish should return IOT_MQTT_STATUS_PENDING upon success.
* IotMqttError_t qos1Result = IotMqtt_Publish( mqttConnection,
* &publishInfo,
* IOT_MQTT_FLAG_WAITABLE,
* NULL,
* &qos1Operation );
*
* // Wait up to 5 seconds for the publish to complete.
* if( qos1Result == IOT_MQTT_STATUS_PENDING )
* {
* qos1Result = IotMqtt_Wait( qos1Operation, 5000 );
* }
* @endcode
*/
/* @[declare_mqtt_publish] */
IotMqttError_t IotMqtt_Publish( IotMqttConnection_t mqttConnection,
const IotMqttPublishInfo_t * pPublishInfo,
uint32_t flags,
const IotMqttCallbackInfo_t * pCallbackInfo,
IotMqttOperation_t * pPublishOperation );
/* @[declare_mqtt_publish] */
/**
* @brief Publish a message to the given topic name with a timeout.
*
* This function transmits an MQTT PUBLISH packet to the server, then waits for
* a server response to the packet. Internally, this function is a call to @ref
* mqtt_function_publish followed by @ref mqtt_function_wait. See @ref
* mqtt_function_publish for more information about the MQTT PUBLISH operation.
*
* @attention QoS 2 messages are currently unsupported. Only 0 or 1 are valid
* for message QoS.
*
* @param[in] mqttConnection The MQTT connection to use for the publish.
* @param[in] pPublishInfo MQTT publish parameters.
* @param[in] flags Flags which modify the behavior of this function. See @ref mqtt_constants_flags.
* Currently, flags are ignored by this function; this parameter is for
* future-compatibility.
* @param[in] timeoutMs If the MQTT server does not acknowledge a QoS 1 PUBLISH
* within this timeout, this function returns #IOT_MQTT_TIMEOUT. This parameter
* is ignored for QoS 0 PUBLISH messages.
*
* @return One of the following:
* - #IOT_MQTT_SUCCESS
* - #IOT_MQTT_BAD_PARAMETER
* - #IOT_MQTT_NO_MEMORY
* - #IOT_MQTT_NETWORK_ERROR
* - #IOT_MQTT_SCHEDULING_ERROR
* - #IOT_MQTT_BAD_RESPONSE
* - #IOT_MQTT_RETRY_NO_RESPONSE (if [pPublishInfo->retryMs](@ref IotMqttPublishInfo_t.retryMs)
* and [pPublishInfo->retryLimit](@ref IotMqttPublishInfo_t.retryLimit) were set).
*/
/* @[declare_mqtt_timedpublish] */
IotMqttError_t IotMqtt_TimedPublish( IotMqttConnection_t mqttConnection,
const IotMqttPublishInfo_t * pPublishInfo,
uint32_t flags,
uint32_t timeoutMs );
/* @[declare_mqtt_timedpublish] */
/**
* @brief Waits for an operation to complete.
*
* This function blocks to wait for a [subscribe](@ref mqtt_function_subscribe),
* [unsubscribe](@ref mqtt_function_unsubscribe), or [publish]
* (@ref mqtt_function_publish) to complete. These operations are by default
* asynchronous; the function calls queue an operation for processing, and a
* callback is invoked once the operation is complete.
*
* To use this function, the flag #IOT_MQTT_FLAG_WAITABLE must have been
* set in the operation's function call. Additionally, this function must always
* be called with any waitable operation to clean up resources.
*
* Regardless of its return value, this function always clean up resources used
* by the waitable operation. This means `reference` is invalidated as soon as
* this function returns, even if it returns #IOT_MQTT_TIMEOUT or another error.
*
* @param[in] operation Reference to the operation to wait for. The flag
* #IOT_MQTT_FLAG_WAITABLE must have been set for this operation.
* @param[in] timeoutMs How long to wait before returning #IOT_MQTT_TIMEOUT.
*
* @return The return value of this function depends on the MQTT operation associated
* with `reference`. See #IotMqttError_t for possible return values.
*
* <b>Example</b>
* @code{c}
* // Operation reference and timeout.
* IotMqttOperation_t publishOperation = IOT_MQTT_OPERATION_INITIALIZER;
* uint32_t timeoutMs = 5000; // 5 seconds
*
* // MQTT operation to wait for.
* IotMqttError_t result = IotMqtt_Publish( mqttConnection,
* &publishInfo,
* IOT_MQTT_FLAG_WAITABLE,
* NULL,
* &publishOperation );
*
* // Publish should have returned IOT_MQTT_STATUS_PENDING. The call to wait
* // returns once the result of the publish is available or the timeout expires.
* if( result == IOT_MQTT_STATUS_PENDING )
* {
* result = IotMqtt_Wait( publishOperation, timeoutMs );
*
* // After the call to wait, the result of the publish is known
* // (not IOT_MQTT_STATUS_PENDING).
* assert( result != IOT_MQTT_STATUS_PENDING );
* }
* @endcode
*/
/* @[declare_mqtt_wait] */
IotMqttError_t IotMqtt_Wait( IotMqttOperation_t operation,
uint32_t timeoutMs );
/* @[declare_mqtt_wait] */
/*-------------------------- MQTT helper functions --------------------------*/
/**
* @brief Returns a string that describes an #IotMqttError_t.
*
* Like the POSIX's `strerror`, this function returns a string describing a
* return code. In this case, the return code is an MQTT library error code,
* `status`.
*
* The string returned by this function <b>MUST</b> be treated as read-only: any
* attempt to modify its contents may result in a crash. Therefore, this function
* is limited to usage in logging.
*
* @param[in] status The status to describe.
*
* @return A read-only string that describes `status`.
*
* @warning The string returned by this function must never be modified.
*/
/* @[declare_mqtt_strerror] */
const char * IotMqtt_strerror( IotMqttError_t status );
/* @[declare_mqtt_strerror] */
/**
* @brief Returns a string that describes an #IotMqttOperationType_t.
*
* This function returns a string describing an MQTT operation type, `operation`.
*
* The string returned by this function <b>MUST</b> be treated as read-only: any
* attempt to modify its contents may result in a crash. Therefore, this function
* is limited to usage in logging.
*
* @param[in] operation The operation to describe.
*
* @return A read-only string that describes `operation`.
*
* @warning The string returned by this function must never be modified.
*/
/* @[declare_mqtt_operationtype] */
const char * IotMqtt_OperationType( IotMqttOperationType_t operation );
/* @[declare_mqtt_operationtype] */
/**
* @brief Check if an MQTT connection has a subscription for a topic filter.
*
* This function checks whether an MQTT connection `mqttConnection` has a
* subscription callback registered for a topic filter `pTopicFilter`. If a
* subscription callback is found, its details are copied into the output parameter
* `pCurrentSubscription`. This subscription callback will be invoked for incoming
* PUBLISH messages on `pTopicFilter`.
*
* <b>The check for a matching subscription is only performed client-side</b>;
* therefore, this function should not be relied upon for perfect accuracy. For
* example, this function may return an incorrect result if the MQTT server
* crashes and drops subscriptions without informing the client.
*
* Note that an MQTT connection's subscriptions might change between the time this
* function checks the subscription list and its caller tests the return value.
* This function certainly should not be used concurrently with any pending SUBSCRIBE
* or UNSUBSCRIBE operations.
*
* One suitable use of this function is to check <i>which</i> subscriptions were rejected
* if @ref mqtt_function_subscribe returns #IOT_MQTT_SERVER_REFUSED; that return
* code only means that <i>at least one</i> subscription was rejected.
*
* @param[in] mqttConnection The MQTT connection to check.
* @param[in] pTopicFilter The topic filter to check.
* @param[in] topicFilterLength Length of `pTopicFilter`.
* @param[out] pCurrentSubscription If a subscription is found, its details are
* copied here. This output parameter is only valid if this function returns `true`.
* Pass `NULL` to ignore.
*
* @return `true` if a subscription was found; `false` otherwise.
*
* @note The subscription QoS is not stored by the MQTT library; therefore,
* `pCurrentSubscription->qos` will always be set to #IOT_MQTT_QOS_0.
*/
/* @[declare_mqtt_issubscribed] */
bool IotMqtt_IsSubscribed( IotMqttConnection_t mqttConnection,
const char * pTopicFilter,
uint16_t topicFilterLength,
IotMqttSubscription_t * pCurrentSubscription );
/* @[declare_mqtt_issubscribed] */
#endif /* ifndef IOT_MQTT_H_ */

View file

@ -0,0 +1,358 @@
/*
* Amazon FreeRTOS MQTT V2.0.0
* Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file iot_mqtt_agent.h
* @brief MQTT Agent Interface.
*/
#ifndef _AWS_MQTT_AGENT_H_
#define _AWS_MQTT_AGENT_H_
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* MQTT lib includes. */
#include "iot_mqtt_lib.h"
/* Library initialization definition include */
#include "iot_lib_init.h"
/**
* @brief Opaque handle to represent an MQTT client.
*
* The MQTT library is capable of creating multiple MQTT clients, maximum number of which
* is controlled by mqttconfigMAX_BROKERS macro. Each client is identified by an opaque
* handle which is returned by the MQTT_AGENT_Create API call and later used in all
* the subsequent API calls.
*/
typedef void * MQTTAgentHandle_t;
/**
* @brief Return codes.
*
* Each API returns a value of this type.
*/
typedef enum
{
eMQTTAgentSuccess, /**< The operation was successful. */
eMQTTAgentFailure, /**< The operation failed. */
eMQTTAgentTimeout, /**< The operation timed out. */
eMQTTAgentAPICalledFromCallback /**< The MQTT agent APIs must not be called from MQTT callbacks as callbacks run
* in the context of MQTT agent task and therefore can result in deadlock. This
* error code is returned if any MQTT agent API is invoked from any callback. */
} MQTTAgentReturnCode_t;
/**
* @brief Various events reported by the library in the callback.
*
* The user can register an optional callback with the MQTT library to
* get notified of various events including Publish messages received
* from the broker. This enum identifies the event received in the
* callback.
*/
typedef enum
{
eMQTTAgentPublish, /**< A Publish message was received from the broker. */
eMQTTAgentDisconnect /**< The connection to the broker got disconnected. */
} MQTTAgentEvent_t;
/**
* @brief Passed by the library in the callback to inform the user of various events.
*
* If the user has registered a callback to get notified of various events, a pointer
* to this structure is passed in the callback function.
* @see MQTTAgentEvent_t.
*/
typedef struct MQTTAgentCallbackParams
{
MQTTAgentEvent_t xMQTTEvent; /**< Type of the event received. */
/* This union is here for future support. */
union
{
MQTTPublishData_t xPublishData; /**< Publish data. Meaningful only in case of eMQTTAgentPublish event. */
} u;
} MQTTAgentCallbackParams_t;
/**
* @brief Signature of the callback registered by the user to get notified of various events.
*
* The user can register an optional callback to get notified of various events.
*
* @param[in] pvUserData The user data as provided in the connect parameters while connecting.
* @param[in] pxCallbackParams The event and related data.
*
* @return The return value is ignored in all other cases except publish (i.e. eMQTTAgentPublish
* event):
* 1. If pdTRUE is returned - The ownership of the buffer passed in the callback (xBuffer
* in MQTTPublishData_t) lies with the user.
* 2. If pdFALSE is returned - The ownership of the buffer passed in the callback (xBuffer
* in MQTTPublishData_t) remains with the library and it is recycled as soon as
* the callback returns.<br>
* The user should take the ownership of the buffer containing the received message from the
* broker by returning pdTRUE from the callback if the user wants to use the buffer after
* the callback is over. The user should return the buffer whenever done by calling the
* MQTT_AGENT_ReturnBuffer API.
*
* @see MQTTAgentCallbackParams_t.
*/
typedef BaseType_t ( * MQTTAgentCallback_t )( void * pvUserData,
const MQTTAgentCallbackParams_t * const pxCallbackParams );
/**
* @brief Flags for the MQTT agent connect params.
*/
#define mqttagentURL_IS_IP_ADDRESS 0x00000001 /**< Set this bit in xFlags if the provided URL is an IP address. */
#define mqttagentREQUIRE_TLS 0x00000002 /**< Set this bit in xFlags to use TLS. */
#define mqttagentUSE_AWS_IOT_ALPN_443 0x00000004 /**< Set this bit in xFlags to use AWS IoT support for MQTT over TLS port 443. */
/**
* @brief Parameters passed to the MQTT_AGENT_Connect API.
*/
typedef struct MQTTAgentConnectParams
{
const char * pcURL; /**< The URL of the MQTT broker to connect to. */
BaseType_t xFlags; /**< Flags to control the behavior of MQTT connect. */
BaseType_t xURLIsIPAddress; /**< Deprecated. Set the mqttagentURL_IS_IP_ADDRESS bit in xFlags instead. */
uint16_t usPort; /**< Port number at which MQTT broker is listening. This field is ignored if the mqttagentUSE_AWS_IOT_ALPN_443 flag is set. */
const uint8_t * pucClientId; /**< Client Identifier of the MQTT client. It should be unique per broker. */
uint16_t usClientIdLength; /**< The length of the client Id. */
BaseType_t xSecuredConnection; /**< Deprecated. Set the mqttagentREQUIRE_TLS bit in xFlags instead. */
void * pvUserData; /**< User data supplied back as it is in the callback. Can be NULL. */
MQTTAgentCallback_t pxCallback; /**< Callback used to report various events. In addition to other events, this callback is invoked for the publish
* messages received on the topics for which the user has not registered any subscription callback. Can be NULL. */
char * pcCertificate; /**< Certificate used for secure connection. Can be NULL. If it is NULL, the one specified in the aws_credential_keys.h is used. */
uint32_t ulCertificateSize; /**< Size of certificate used for secure connection. */
} MQTTAgentConnectParams_t;
/**
* @brief Parameters passed to the MQTT_AGENT_Subscribe API.
*/
typedef struct MQTTAgentSubscribeParams
{
const uint8_t * pucTopic; /**< The topic to subscribe to. This can be a topic filter containing wild cards as permitted by the MQTT protocol. */
uint16_t usTopicLength; /**< The length of the topic. */
MQTTQoS_t xQoS; /**< Requested Quality of Service. */
#if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 )
void * pvPublishCallbackContext; /**< Passed as it is in the publish callback. Can be NULL. */
MQTTPublishCallback_t pxPublishCallback; /**< Callback function to be called whenever a publish message is received on this topic or on a topic which matches this
* topic filter. If a publish message is received on a topic which matches more than one topic filters, the order in which
* the callbacks are invoked is undefined. This can be NULL if the user does not want to register a topic specific callback,
* in which case the generic callback ( if registered during connect ) is invoked. */
#endif /* mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT */
} MQTTAgentSubscribeParams_t;
/**
* @brief Parameters passed to the MQTT_AGENT_Unsubscribe API.
*/
typedef struct MQTTAgentUnsubscribeParams
{
const uint8_t * pucTopic; /**< The topic to unsubscribe from. */
uint16_t usTopicLength; /**< The length of the topic. */
} MQTTAgentUnsubscribeParams_t;
/**
* @brief Parameters passed to the MQTT_AGENT_Publish API.
*/
typedef struct MQTTAgentPublishParams
{
const uint8_t * pucTopic; /**< The topic string on which the message should be published. */
uint16_t usTopicLength; /**< The length of the topic. */
MQTTQoS_t xQoS; /**< Quality of Service (qos). */
const void * pvData; /**< The data to publish. This data is copied into the MQTT buffers and therefore the user can free the buffer after the MQTT_AGENT_Publish call returns. */
uint32_t ulDataLength; /**< Length of the data. */
} MQTTAgentPublishParams_t;
/**
* @brief MQTT library Init function.
*
* This function does general initialization and setup. It must be called once
* and only once before calling any other function.
*
* @return pdPASS if everything succeeds, pdFAIL otherwise.
*/
lib_initDECLARE_LIB_INIT( MQTT_AGENT_Init );
/**
* @brief Creates a new MQTT client.
*
* The MQTT library is capable of creating multiple MQTT clients, maximum number of which
* is controlled by mqttconfigMAX_BROKERS macro. If mqttconfigMAX_BROKERS clients are already
* in use, this function will fail immediately. Otherwise a new client is setup and the handle
* to the created client is returned in the pxMQTTHandle parameter which should be used in all
* the subsequent API calls. Note that the returned handled is only valid if the return value
* of the API is eMQTTAgentSuccess.
*
* @param[out] pxMQTTHandle Output parameter to return the opaque client handle.
*
* @return eMQTTAgentSuccess if a new client is successfully created, otherwise an error code
* explaining the reason of the failure is returned.
*/
MQTTAgentReturnCode_t MQTT_AGENT_Create( MQTTAgentHandle_t * const pxMQTTHandle );
/**
* @brief Deletes the already created MQTT client.
*
* This function just frees up the internal resources and does not disconnect. The user must
* call MQTT_AGENT_Disconnect API to make sure that the client is disconnected before
* deleting it.
*
* @param[in] xMQTTHandle The opaque handle as returned from MQTT_AGENT_Create.
*
* @return eMQTTAgentSuccess if the client is successfully deleted, otherwise an
* error code explaining the reason of the failure is returned.
*/
MQTTAgentReturnCode_t MQTT_AGENT_Delete( MQTTAgentHandle_t xMQTTHandle );
/**
* @brief Establishes a connection with the MQTT broker.
*
* @note This function alters the calling task's notification state and value. If xTimeoutTicks
* is short the calling task's notification state and value may be updated after MQTT_AGENT_Connect()
* has returned.
*
* @param[in] xMQTTHandle The opaque handle as returned from MQTT_AGENT_Create.
* @param[in] pxConnectParams Connect parameters.
* @param[in] xTimeoutTicks Maximum time in ticks after which the operation should fail. Use pdMS_TO_TICKS
* macro to convert milliseconds to ticks.
*
* @return eMQTTAgentSuccess if the connect operation succeeds, otherwise an error code explaining the
* reason of the failure is returned.
*/
MQTTAgentReturnCode_t MQTT_AGENT_Connect( MQTTAgentHandle_t xMQTTHandle,
const MQTTAgentConnectParams_t * const pxConnectParams,
TickType_t xTimeoutTicks );
/**
* @brief Disconnects the connection with the MQTT broker.
*
* @note This function alters the calling task's notification state and value. If xTimeoutTicks
* is short the calling task's notification state and value may be updated after MQTT_AGENT_Disconnect()
* has returned.
*
* @param[in] xMQTTHandle The opaque handle as returned from MQTT_AGENT_Create.
* @param[in] xTimeoutTicks Maximum time in ticks after which the operation should fail. Use pdMS_TO_TICKS
* macro to convert milliseconds to ticks.
*
* @return eMQTTAgentSuccess if the disconnect operation succeeds, otherwise an error code explaining
* the reason of the failure is returned.
*/
MQTTAgentReturnCode_t MQTT_AGENT_Disconnect( MQTTAgentHandle_t xMQTTHandle,
TickType_t xTimeoutTicks );
/**
* @brief Subscribes to a given topic.
*
* @note This function alters the calling task's notification state and value. If xTimeoutTicks
* is short the calling task's notification state and value may be updated after MQTT_AGENT_Subscribe()
* has returned.
*
* Whenever a publish message is received on a topic, the registered callbacks are invoked
* in the following order:
* * If we have an exact matching entry in the subscription manager, the corresponding
* callback is invoked.
* * Then the wild card topic filters are checked for match and the corresponding callbacks
* are invoked for the ones which match the topic.
*
* @note If a publish message is received on a topic which matches more than one topic
* filters, the order in which the registered callbacks are invoked is undefined.
*
* @warning If the user takes the ownership of the MQTT buffer by returning eMQTTTrue from the
* callback, no further callbacks are invoked. The user should make sure not to take the ownership
* of the MQTT buffer if they want all the callbacks to get invoked. For example:
* * Subscriptions: a/b/c, a/b/#, a/b/+
* * Publish message received on topic: a/b/c --> First the callback corresponding to a/b/c
* subscription is invoked. Then the callbacks for topic filters a/b/# and a/b/+ are invoked
* in no particular order. If the user decides to take the ownership of the MQTT buffer in
* any of the callback by returning eMQTTTrue, no further callbacks are invoked.
*
* @param[in] xMQTTHandle The opaque handle as returned from MQTT_AGENT_Create.
* @param[in] pxSubscribeParams Subscribe parameters.
* @param[in] xTimeoutTicks Maximum time in ticks after which the operation should fail. Use pdMS_TO_TICKS
* macro to convert milliseconds to ticks.
*
* @return eMQTTAgentSuccess if the subscribe operation succeeds, otherwise an error code explaining
* the reason of the failure is returned.
*/
MQTTAgentReturnCode_t MQTT_AGENT_Subscribe( MQTTAgentHandle_t xMQTTHandle,
const MQTTAgentSubscribeParams_t * const pxSubscribeParams,
TickType_t xTimeoutTicks );
/**
* @brief Unsubscribes from a given topic.
*
* @note This function alters the calling task's notification state and value. If xTimeoutTicks
* is short the calling task's notification state and value may be updated after MQTT_AGENT_Unsubscribe()
* has returned.
*
* @param[in] xMQTTHandle The opaque handle as returned from MQTT_AGENT_Create.
* @param[in] pxUnsubscribeParams Unsubscribe parameters.
* @param[in] xTimeoutTicks Maximum time in ticks after which the operation should fail. Use pdMS_TO_TICKS
* macro to convert milliseconds to ticks.
*
* @return eMQTTAgentSuccess if the unsubscribe operation succeeds, otherwise an error code explaining
* the reason of the failure is returned.
*/
MQTTAgentReturnCode_t MQTT_AGENT_Unsubscribe( MQTTAgentHandle_t xMQTTHandle,
const MQTTAgentUnsubscribeParams_t * const pxUnsubscribeParams,
TickType_t xTimeoutTicks );
/**
* @brief Publishes a message to a given topic.
*
* @note This function alters the calling task's notification state and value. If xTimeoutTicks
* is short the calling task's notification state and value may be updated after MQTT_AGENT_Publish()
* has returned.
*
* @param[in] xMQTTHandle The opaque handle as returned from MQTT_AGENT_Create.
* @param[in] pxPublishParams Publish parameters.
* @param[in] xTimeoutTicks Maximum time in ticks after which the operation should fail. Use pdMS_TO_TICKS
* macro to convert milliseconds to ticks.
*
* @return eMQTTAgentSuccess if the publish operation succeeds, otherwise an error code explaining
* the reason of the failure is returned.
*/
MQTTAgentReturnCode_t MQTT_AGENT_Publish( MQTTAgentHandle_t xMQTTHandle,
const MQTTAgentPublishParams_t * const pxPublishParams,
TickType_t xTimeoutTicks );
/**
* @brief Returns the buffer provided in the publish callback.
*
* When a publish message is received from the broker, the buffer containing the message
* is returned in the user supplied callback (xBuffer in MQTTPublishData_t) and the user
* can take the ownership by returning pdTRUE from the callback. The user should later
* return the buffer whenever done by calling the MQTT_AGENT_ReturnBuffer API.
*
* @param[in] xMQTTHandle The opaque handle as returned from MQTT_AGENT_Create.
* @param[in] xBufferHandle The buffer to return.
*
* @return eMQTTAgentSuccess if the return buffer operation succeeds, otherwise an error
* code explaining the reason of the failure is returned.
*/
MQTTAgentReturnCode_t MQTT_AGENT_ReturnBuffer( MQTTAgentHandle_t xMQTTHandle,
MQTTBufferHandle_t xBufferHandle );
#endif /* _AWS_MQTT_AGENT_H_ */

View file

@ -0,0 +1,180 @@
/*
* Amazon FreeRTOS MQTT V2.0.0
* Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file iot_mqtt_agent_config_defaults.h
* @brief MQTT agent default config options.
*
* Ensures that the config options for MQTT agent are set to sensible
* default values if the user does not provide one.
*/
#ifndef _AWS_MQTT_AGENT_CONFIG_DEFAULTS_H_
#define _AWS_MQTT_AGENT_CONFIG_DEFAULTS_H_
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/**
* @brief Controls whether or not to report usage metrics to the
* AWS IoT broker.
*
* If mqttconfigENABLE_METRICS is set to 1, a string containing
* metric information will be included in the "username" field of
* the MQTT connect messages.
*/
#ifndef mqttconfigENABLE_METRICS
#define mqttconfigENABLE_METRICS ( 1 )
#endif
/**
* @brief The maximum time interval in seconds allowed to elapse between 2 consecutive
* control packets.
*/
#ifndef mqttconfigKEEP_ALIVE_INTERVAL_SECONDS
#define mqttconfigKEEP_ALIVE_INTERVAL_SECONDS ( 1200 )
#endif
/**
* @brief Defines the frequency at which the client should send Keep Alive messages.
*
* Even though the maximum time allowed between 2 consecutive control packets
* is defined by the mqttconfigKEEP_ALIVE_INTERVAL_SECONDS macro, the user
* can and should send Keep Alive messages at a slightly faster rate to ensure
* that the connection is not closed by the server because of network delays.
* This macro defines the interval of inactivity after which a keep alive messages
* is sent.
*/
#ifndef mqttconfigKEEP_ALIVE_ACTUAL_INTERVAL_TICKS
#define mqttconfigKEEP_ALIVE_ACTUAL_INTERVAL_TICKS ( 5000 )
#endif
/**
* @brief The maximum interval in ticks to wait for PINGRESP.
*
* If PINGRESP is not received within this much time after sending PINGREQ,
* the client assumes that the PINGREQ timed out.
*/
#ifndef mqttconfigKEEP_ALIVE_TIMEOUT_TICKS
#define mqttconfigKEEP_ALIVE_TIMEOUT_TICKS ( 1000 )
#endif
/**
* @brief The maximum time in ticks for which the MQTT task is permitted to block.
*
* The MQTT task blocks until the user initiates any action or until it receives
* any data from the broker. This macro controls the maximum time the MQTT task can
* block. It should be set to a small number for the platforms which do not have any
* mechanism to wake up the MQTT task whenever data is received on a connected socket.
* This ensures that the MQTT task keeps waking up frequently and processes the publish
* messages received from the broker, if any.
*
* If the platform's secure_sockets layer supports SOCKETS_SO_WAKEUP_CALLBACK i.e.
* the MQTT task can wake up whenever data is received on a connected socket, this
* value should be set to maximum value:
* #define #define mqttconfigMQTT_TASK_MAX_BLOCK_TICKS ( ~( ( uint32_t ) 0 ) )
*
* If the platform's secure_sockets layer does not support SOCKETS_SO_WAKEUP_CALLBACK
* i.e. the MQTT task cannot wake up whenever data is received on a connected socket,
* this value should be set to a small number:
* #define mqttconfigMQTT_TASK_MAX_BLOCK_TICKS ( 100 )
*/
#ifndef mqttconfigMQTT_TASK_MAX_BLOCK_TICKS
#error "mqttconfigMQTT_TASK_MAX_BLOCK_TICKS must be defined in iot_mqtt_agent_config.h."
#endif
/**
* @defgroup MQTTTask MQTT task configuration parameters.
*/
/** @{ */
#ifndef mqttconfigMQTT_TASK_STACK_DEPTH
#define mqttconfigMQTT_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE * 4 )
#endif
#ifndef mqttconfigMQTT_TASK_PRIORITY
#define mqttconfigMQTT_TASK_PRIORITY ( tskIDLE_PRIORITY )
#endif
/** @} */
/**
* @brief Maximum number of MQTT clients that can exist simultaneously.
*/
#ifndef mqttconfigMAX_BROKERS
#define mqttconfigMAX_BROKERS ( 1 )
#endif
/**
* @brief Maximum number of parallel operations per client.
*/
#ifndef mqttconfigMAX_PARALLEL_OPS
#define mqttconfigMAX_PARALLEL_OPS ( 5 )
#endif
/**
* @brief Time in milliseconds after which the TCP send operation should timeout.
*/
#ifndef mqttconfigTCP_SEND_TIMEOUT_MS
#define mqttconfigTCP_SEND_TIMEOUT_MS ( 2000 )
#endif
/**
* @brief Length of the buffer used to receive data.
*/
#ifndef mqttconfigRX_BUFFER_SIZE
#define mqttconfigRX_BUFFER_SIZE ( 1024 )
#endif
/**
* @defgroup BufferPoolInterface The functions used by the MQTT client to get and return buffers.
*
* The MQTT client needs buffers for both transmitting and receiving messages.
* Whenever it needs a buffer, it invokes mqttconfigGET_FREE_BUFFER_FXN function to get
* a buffer and after it is done it invokes mqttconfigRETURN_BUFFER_FXN to return the
* buffer. By default, BUFFERPOOL_GetFreeBuffer and BUFFERPOOL_ReturnBuffer functions are
* used to get and return buffers from the central buffer pool. The user can change the
* buffer management functions for MQTT client by defining mqttconfigGET_FREE_BUFFER_FXN
* and mqttconfigRETURN_BUFFER_FXN macros. The user should implement the two functions
* having signatures same as BUFFERPOOL_GetFreeBuffer and BUFFERPOOL_ReturnBuffer and then
* define the macros in BufferPoolConfig.h:
* @code
* uint8_t* UserDefined_GetFreeBuffer( uint32_t *pulBufferLength );
* void UserDefined_ReturnBuffer( uint8_t * const pucBuffer );
*
* #define mqttconfigGET_FREE_BUFFER_FXN UserDefined_GetFreeBuffer
* #define mqttconfigRETURN_BUFFER_FXN UserDefined_ReturnBuffer
* @endcode
*/
/** @{ */
#ifndef mqttconfigGET_FREE_BUFFER_FXN
#define mqttconfigGET_FREE_BUFFER_FXN BUFFERPOOL_GetFreeBuffer
#endif
#ifndef mqttconfigRETURN_BUFFER_FXN
#define mqttconfigRETURN_BUFFER_FXN BUFFERPOOL_ReturnBuffer
#endif
/** @} */
#endif /* _AWS_MQTT_AGENT_CONFIG_DEFAULTS_H_ */

View file

@ -0,0 +1,115 @@
/*
* Amazon FreeRTOS MQTT V2.0.0
* Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file iot_mqtt_config_defaults.h
* @brief MQTT default config options.
*
* Ensures that the config options for MQTT are set to sensible default
* values if the user does not provide one.
*/
#ifndef _AWS_MQTT_CONFIG_DEFAULTS_H_
#define _AWS_MQTT_CONFIG_DEFAULTS_H_
/**
* @brief Enable subscription management.
*
* Subscription management allows the user to register per subscription
* callback.
*/
#ifndef mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT
#define mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT ( 1 )
#endif
/**
* @brief Maximum length of the topic which can be stored in subscription
* manager.
*
* If the user has enabled subscription management (by defining the macro
* mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT to 1), then this macro must be defined
* to accommodate the maximum length topic which the user is going to subscribe.
* The subscribe operation will fail if the user tries to subscribe to a topic
* of length more than the maximum specified here.
*/
#ifndef mqttconfigSUBSCRIPTION_MANAGER_MAX_TOPIC_LENGTH
#define mqttconfigSUBSCRIPTION_MANAGER_MAX_TOPIC_LENGTH ( 128 )
#endif
/**
* @brief Maximum number of subscriptions which can be stored in subscription
* manager.
*
* If the user has enabled subscription management (by defining the macro
* mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT to 1), then this macro must be defined
* to the maximum number of topics which the user is going to subscribe
* simultaneously. The subscribe operation will fail is the user tries to
* subscribe to more topics than the maximum specified here.
*/
#ifndef mqttconfigSUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS
#define mqttconfigSUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS ( 8 )
#endif
/**
* @brief Define mqttconfigASSERT to enable asserts.
*
* mqttconfigASSERT should be defined to match the semantics of standard
* C assert() macro i.e. an assertion should trigger if the parameter
* passed is zero. If the standard C assert is available, the user might
* do the following:
* @code
* #define mqttconfigASSERT( x ) assert( x )
* @endcode
*
* Otherwise, a user can choose to implement a function which should be
* called when an assertion triggers and then define the mqttconfigASSERT
* to that function:
* @code
* extern void vAssertCalled( const char *pcFile, uint32_t ulLine );
* #define mqttconfigASSERT( x ) if( ( x ) == 0 ) vAssertCalled( __FILE__, __LINE__ )
* @endcode
*/
#ifndef mqttconfigASSERT
#define mqttconfigASSERT( x )
#endif
/**
* @brief Define mqttconfigENABLE_DEBUG_LOGS macro to 1 for enabling debug logs.
*
* If you choose to enable debug logs, the following function must be implemented
* which is called to print logs:
* @code
* void vLoggingPrintf( const char *pcFormatString, ... );
* @endcode
*/
#if ( mqttconfigENABLE_DEBUG_LOGS == 1 )
extern void vLoggingPrintf( const char * pcFormatString,
... );
#define mqttconfigDEBUG_LOG( x ) vLoggingPrintf x
#else
#define mqttconfigDEBUG_LOG( x )
#endif
#endif /* _AWS_MQTT_CONFIG_DEFAULTS_H_ */

View file

@ -0,0 +1,113 @@
/*
* Amazon FreeRTOS MQTT V2.0.0
* Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file iot_mqtt_lib.h
* @brief MQTT Core Library interface.
*/
#ifndef _AWS_MQTT_LIB_H_
#define _AWS_MQTT_LIB_H_
/* This ifndef enables the core MQTT library to be used without
* providing MQTTConfig.h. All the config values in this case are
* taken from MQTTConfigDefaults.h. */
#ifndef mqttDO_NOT_USE_CUSTOM_CONFIG
#include "aws_mqtt_config.h"
#endif
#include "iot_mqtt_config_defaults.h"
#include "iot_doubly_linked_list.h"
/**
* @brief Opaque handle to represent an MQTT buffer.
*/
typedef void * MQTTBufferHandle_t;
/**
* @brief Boolean type.
*/
typedef enum
{
eMQTTFalse = 0, /**< Boolean False. */
eMQTTTrue = 1 /**< Boolean True. */
} MQTTBool_t;
/**
* @brief Quality of Service (qos).
*/
typedef enum
{
eMQTTQoS0 = 0, /**< Quality of Service 0 - Fire and Forget. No ACK. */
eMQTTQoS1 = 1, /**< Quality of Service 1 - Wait till ACK or Timeout. */
eMQTTQoS2 = 2 /**< Quality of Service 2 - Not supported. */
} MQTTQoS_t;
/**
* @brief The data sent by the MQTT library in the user supplied callback
* when a publish message from the broker is received.
*/
typedef struct MQTTPublishData
{
MQTTQoS_t xQos; /**< Quality of Service (qos). */
const uint8_t * pucTopic; /**< The topic on which the message is received. */
uint16_t usTopicLength; /**< Length of the topic. */
const void * pvData; /**< The received message. */
uint32_t ulDataLength; /**< Length of the message. */
MQTTBufferHandle_t xBuffer; /**< The buffer containing the whole MQTT message. Both pcTopic and pvData are pointers to the locations in this buffer. */
} MQTTPublishData_t;
/**
* @brief Signature of the user supplied topic specific publish callback which gets called
* whenever a publish message is received on the topic this callback is registered for.
*
* The user can choose to register this optional topic specific callback while subscribing to
* a topic. Whenever a publish message is received on the topic, this callback is invoked. If
* the user chooses not to enable subscription management or chooses not to register a topic
* specific callback, the generic callback supplied during Init is invoked.
*
* @param[in] pvPublishCallbackContext The callback context as supplied by the user in the
* subscribe parameters.
* @param[in] pxPublishData The publish data.
*
* @return The return value is interpreted as follows:
* 1. If eMQTTTrue is returned - the ownership of the buffer passed in the callback (xBuffer
* in MQTTPublishData_t) lies with the user.
* 2. If eMQTTFalse is returned - the ownership of the buffer passed in the callback (xBuffer
* in MQTTPublishData_t) remains with the library and it is recycled as soon as the callback
* returns.<br>
* The user should take the ownership of the buffer containing the received message from the
* broker by returning eMQTTTrue from the callback if the user wants to use the buffer after
* the callback is over. The user should return the buffer whenever done by calling the
* MQTT_ReturnBuffer API.
*/
#if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 )
typedef MQTTBool_t ( * MQTTPublishCallback_t )( void * pvPublishCallbackContext,
const MQTTPublishData_t * const pxPublishData );
#endif /* mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT */
#endif /* _AWS_MQTT_LIB_H_ */