Rename \FreeRTOS-Plus\Source\FreeRTOS-Plus-IoT-SDK to \FreeRTOS-Plus\Source\FreeRTOS-IoT-Libraries.

This commit is contained in:
Gaurav Aggarwal 2019-07-23 03:41:27 +00:00
parent 7af8756c97
commit 9dd72d4b44
45 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,140 @@
/*
* Amazon FreeRTOS Platform V1.0.0
* Copyright (C) 2019 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_network_freertos.h
* @brief Declares the network stack functions specified in aws_iot_network.h for
* Amazon FreeRTOS Secure Sockets.
*/
#ifndef _IOT_NETWORK_AFR_H_
#define _IOT_NETWORK_AFR_H_
/* Standard includes. */
#include <stdbool.h>
/* Platform network include. */
#include "platform/iot_network.h"
/* Amazon FreeRTOS Secure Sockets include. */
#include "iot_secure_sockets.h"
/**
* @brief Represents a network connection that uses Amazon FreeRTOS Secure Sockets.
*
* This is an incomplete type. In application code, only pointers to this type
* should be used.
*/
typedef struct _networkConnection IotNetworkConnectionAfr_t;
/**
* @brief Provides a default value for an #IotNetworkConnectionAfr_t.
*
* All instances of #IotNetworkConnectionAfr_t should be initialized with
* this constant.
*
* @warning Failing to initialize an #IotNetworkConnectionAfr_t with this
* initializer may result in undefined behavior!
* @note This initializer may change at any time in future versions, but its
* name will remain the same.
*/
#define IOT_NETWORK_CONNECTION_AFR_INITIALIZER { 0 }
/**
* @brief Generic initializer for an #IotNetworkServerInfo_t.
*
* @note This initializer may change at any time in future versions, but its
* name will remain the same.
*/
#define IOT_NETWORK_SERVER_INFO_AFR_INITIALIZER { 0 }
/**
* @brief Generic initializer for an #IotNetworkCredentials_t.
*
* @note This initializer may change at any time in future versions, but its
* name will remain the same.
*/
#define IOT_NETWORK_CREDENTIALS_AFR_INITIALIZER { 0 }
/**
* @brief Provides a pointer to an #IotNetworkInterface_t that uses the functions
* declared in this file.
*/
#define IOT_NETWORK_INTERFACE_AFR ( &( IotNetworkAfr ) )
/**
* @brief An implementation of #IotNetworkInterface_t::create for Amazon FreeRTOS
* Secure Sockets.
*/
IotNetworkError_t IotNetworkAfr_Create( void * pConnectionInfo,
void * pCredentialInfo,
void ** const pConnection );
/**
* @brief An implementation of #IotNetworkInterface_t::setReceiveCallback for
* Amazon FreeRTOS Secure Sockets.
*/
IotNetworkError_t IotNetworkAfr_SetReceiveCallback( void * pConnection,
IotNetworkReceiveCallback_t receiveCallback,
void * pContext );
/**
* @brief An implementation of #IotNetworkInterface_t::send for Amazon FreeRTOS
* Secure Sockets.
*/
size_t IotNetworkAfr_Send( void * pConnection,
const uint8_t * pMessage,
size_t messageLength );
/**
* @brief An implementation of #IotNetworkInterface_t::receive for Amazon FreeRTOS
* Secure Sockets.
*/
size_t IotNetworkAfr_Receive( void * pConnection,
uint8_t * pBuffer,
size_t bytesRequested );
/**
* @brief An implementation of #IotNetworkInterface_t::close for Amazon FreeRTOS
* Secure Sockets.
*/
IotNetworkError_t IotNetworkAfr_Close( void * pConnection );
/**
* @brief An implementation of #IotNetworkInterface_t::destroy for Amazon FreeRTOS
* Secure Sockets.
*/
IotNetworkError_t IotNetworkAfr_Destroy( void * pConnection );
/**
* @cond DOXYGEN_IGNORE
* Doxygen should ignore this section.
*
* Declaration of a network interface struct using the functions in this file.
*/
extern const IotNetworkInterface_t IotNetworkAfr;
/** @endcond */
#endif /* ifndef _IOT_NETWORK_AFR_H_ */

View file

@ -0,0 +1,84 @@
/*
* Amazon FreeRTOS Platform V1.0.0
* Copyright (C) 2019 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_platform_types_posix.h
* @brief Definitions of platform layer types on POSIX systems.
*/
#ifndef _IOT_PLATFORM_TYPES_AFR_H_
#define _IOT_PLATFORM_TYPES_AFR_H_
#include "timers.h"
typedef struct iot_mutex_internal
{
StaticSemaphore_t xMutex; /**< FreeRTOS mutex. */
BaseType_t recursive; /**< Type; used for indicating if this is reentrant or normal. */
} iot_mutex_internal_t;
/**
* @brief The native mutex type on AFR systems.
*/
typedef iot_mutex_internal_t _IotSystemMutex_t;
typedef struct iot_sem_internal
{
StaticSemaphore_t xSemaphore; /**< FreeRTOS semaphore. */
} iot_sem_internal_t;
/**
* @brief The native semaphore type on AFR systems.
*/
typedef iot_sem_internal_t _IotSystemSemaphore_t;
/**
* @brief Holds information about an active detached thread so that we can
* delete the FreeRTOS task when it completes
*/
typedef struct threadInfo
{
void * pArgument; /**< @brief Argument to `threadRoutine`. */
void ( *threadRoutine )( void * );/**< @brief Thread function to run. */
} threadInfo_t;
/**
* @brief Holds information about an active timer.
*/
typedef struct timerInfo
{
TimerHandle_t timer; /**< @brief Underlying timer. */
void ( *threadRoutine )( void * ); /**< @brief Thread function to run on timer expiration. */
void * pArgument; /**< @brief First argument to threadRoutine. */
StaticTimer_t xTimerBuffer; /**< Memory that holds the FreeRTOS timer. */
TickType_t xTimerPeriod; /**< Period of this timer. */
} timerInfo_t;
/**
* @brief Represents an #IotTimer_t on AFR systems.
*/
typedef timerInfo_t _IotSystemTimer_t;
#endif /* ifndef _IOT_PLATFORM_TYPES_POSIX_H_ */

View file

@ -0,0 +1,224 @@
/*
* Amazon FreeRTOS Platform V1.0.0
* Copyright (C) 2019 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_clock_freertos.c
* @brief Implementation of the functions in iot_clock.h for Amazon FreeRTOS systems.
*/
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdio.h>
/* Platform clock include. */
#include "platform/iot_platform_types_freertos.h"
#include "platform/iot_clock.h"
#include "task.h"
/* Configure logs for the functions in this file. */
#ifdef IOT_LOG_LEVEL_PLATFORM
#define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_PLATFORM
#else
#ifdef IOT_LOG_LEVEL_GLOBAL
#define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_GLOBAL
#else
#define LIBRARY_LOG_LEVEL IOT_LOG_NONE
#endif
#endif
#define LIBRARY_LOG_NAME ( "CLOCK" )
#include "iot_logging_setup.h"
/*-----------------------------------------------------------*/
/*
* Time conversion constants.
*/
#define _MILLISECONDS_PER_SECOND ( 1000 ) /**< @brief Milliseconds per second. */
#define _MILLISECONDS_PER_TICK ( _MILLISECONDS_PER_SECOND / configTICK_RATE_HZ ) /**< Milliseconds per FreeRTOS tick. */
/*-----------------------------------------------------------*/
/* Private Callback function for timer expiry, delegate work to a Task to free
* up the timer task for managing other timers */
static void prvTimerCallback( TimerHandle_t xTimerHandle )
{
_IotSystemTimer_t * pxTimer = ( _IotSystemTimer_t * ) pvTimerGetTimerID( xTimerHandle );
/* The value of the timer ID, set in timer_create, should not be NULL. */
configASSERT( pxTimer != NULL );
/* Restart the timer if it is periodic. */
if( pxTimer->xTimerPeriod > 0 )
{
xTimerChangePeriod( xTimerHandle, pxTimer->xTimerPeriod, 0 );
}
/* Call timer Callback from this task */
pxTimer->threadRoutine( ( void * ) pxTimer->pArgument );
}
/*-----------------------------------------------------------*/
bool IotClock_GetTimestring( char * pBuffer,
size_t bufferSize,
size_t * pTimestringLength )
{
uint64_t milliSeconds = IotClock_GetTimeMs();
int timestringLength = 0;
configASSERT( pBuffer != NULL );
configASSERT( pTimestringLength != NULL );
/* Convert the localTime struct to a string. */
timestringLength = snprintf( pBuffer, bufferSize, "%llu", milliSeconds );
/* Check for error from no string */
if( timestringLength == 0 )
{
return false;
}
/* Set the output parameter. */
*pTimestringLength = timestringLength;
return true;
}
/*-----------------------------------------------------------*/
uint64_t IotClock_GetTimeMs( void )
{
TimeOut_t xCurrentTime = { 0 };
/* This must be unsigned because the behavior of signed integer overflow is undefined. */
uint64_t ullTickCount = 0ULL;
/* Get the current tick count and overflow count. vTaskSetTimeOutState()
* is used to get these values because they are both static in tasks.c. */
vTaskSetTimeOutState( &xCurrentTime );
/* Adjust the tick count for the number of times a TickType_t has overflowed. */
ullTickCount = ( uint64_t ) ( xCurrentTime.xOverflowCount ) << ( sizeof( TickType_t ) * 8 );
/* Add the current tick count. */
ullTickCount += xCurrentTime.xTimeOnEntering;
/* Return the ticks converted to Milliseconds */
return ullTickCount * _MILLISECONDS_PER_TICK;
}
/*-----------------------------------------------------------*/
void IotClock_SleepMs( uint32_t sleepTimeMs )
{
vTaskDelay( pdMS_TO_TICKS( sleepTimeMs ) );
}
/*-----------------------------------------------------------*/
bool IotClock_TimerCreate( IotTimer_t * pNewTimer,
IotThreadRoutine_t expirationRoutine,
void * pArgument )
{
_IotSystemTimer_t * pxTimer = ( _IotSystemTimer_t * ) pNewTimer;
configASSERT( pNewTimer != NULL );
configASSERT( expirationRoutine != NULL );
IotLogDebug( "Creating new timer %p.", pNewTimer );
/* Set the timer expiration routine, argument and period */
pxTimer->threadRoutine = expirationRoutine;
pxTimer->pArgument = pArgument;
pxTimer->xTimerPeriod = 0;
/* Create a new FreeRTOS timer. This call will not fail because the
* memory for it has already been allocated, so the output parameter is
* also set. */
pxTimer->timer = ( TimerHandle_t ) xTimerCreateStatic( "timer", /* Timer name. */
portMAX_DELAY, /* Initial timer period. Timers are created disarmed. */
pdFALSE, /* Don't auto-reload timer. */
( void * ) pxTimer, /* Timer id. */
prvTimerCallback, /* Timer expiration callback. */
&pxTimer->xTimerBuffer ); /* Pre-allocated memory for timer. */
return true;
}
/*-----------------------------------------------------------*/
void IotClock_TimerDestroy( IotTimer_t * pTimer )
{
_IotSystemTimer_t * pTimerInfo = ( _IotSystemTimer_t * ) pTimer;
configASSERT( pTimerInfo != NULL );
configASSERT( pTimerInfo->timer != NULL );
IotLogDebug( "Destroying timer %p.", pTimer );
if( xTimerIsTimerActive( pTimerInfo->timer ) == pdTRUE )
{
/* Stop the FreeRTOS timer. Because the timer is statically allocated, no call
* to xTimerDelete is necessary. The timer is stopped so that it's not referenced
* anywhere. xTimerStop will not fail when it has unlimited block time. */
( void ) xTimerStop( pTimerInfo->timer, portMAX_DELAY );
/* Wait until the timer stop command is processed. */
while( xTimerIsTimerActive( pTimerInfo->timer ) == pdTRUE )
{
vTaskDelay( 1 );
}
}
}
/*-----------------------------------------------------------*/
bool IotClock_TimerArm( IotTimer_t * pTimer,
uint32_t relativeTimeoutMs,
uint32_t periodMs )
{
_IotSystemTimer_t * pTimerInfo = ( _IotSystemTimer_t * ) pTimer;
configASSERT( pTimerInfo != NULL );
TimerHandle_t xTimerHandle = pTimerInfo->timer;
IotLogDebug( "Arming timer %p with timeout %llu and period %llu.",
pTimer,
relativeTimeoutMs,
periodMs );
/* Set the timer period in ticks */
pTimerInfo->xTimerPeriod = pdMS_TO_TICKS( periodMs );
/* Set the timer to expire after relativeTimeoutMs, and restart it. */
( void ) xTimerChangePeriod( xTimerHandle, pdMS_TO_TICKS( relativeTimeoutMs ), portMAX_DELAY );
return true;
}
/*-----------------------------------------------------------*/

View file

@ -0,0 +1,627 @@
/*
* Amazon FreeRTOS Platform V1.0.0
* Copyright (C) 2019 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_network_freertos.c
* @brief Implementation of the network-related functions from iot_network_freertos.h
* for Amazon FreeRTOS secure sockets.
*/
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <string.h>
/* FreeRTOS includes. */
#include "semphr.h"
#include "event_groups.h"
/* Error handling include. */
#include "private/iot_error.h"
/* Amazon FreeRTOS network include. */
#include "platform/iot_network_freertos.h"
/* Configure logs for the functions in this file. */
#ifdef IOT_LOG_LEVEL_NETWORK
#define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_NETWORK
#else
#ifdef IOT_LOG_LEVEL_GLOBAL
#define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_GLOBAL
#else
#define LIBRARY_LOG_LEVEL IOT_LOG_NONE
#endif
#endif
#define LIBRARY_LOG_NAME ( "NET" )
#include "iot_logging_setup.h"
/* Provide a default value for the number of milliseconds for a socket poll.
* This is a temporary workaround to deal with the lack of poll(). */
#ifndef IOT_NETWORK_SOCKET_POLL_MS
#define IOT_NETWORK_SOCKET_POLL_MS ( 1000 )
#endif
/**
* @brief The event group bit to set when a connection's socket is shut down.
*/
#define _FLAG_SHUTDOWN ( 1 )
/**
* @brief The event group bit to set when a connection's receive task exits.
*/
#define _FLAG_RECEIVE_TASK_EXITED ( 2 )
/**
* @brief The event group bit to set when the connection is destroyed from the
* receive task.
*/
#define _FLAG_CONNECTION_DESTROYED ( 4 )
/*-----------------------------------------------------------*/
typedef struct _networkConnection
{
Socket_t socket; /**< @brief Amazon FreeRTOS Secure Sockets handle. */
StaticSemaphore_t socketMutex; /**< @brief Prevents concurrent threads from sending on a socket. */
StaticEventGroup_t connectionFlags; /**< @brief Synchronizes with the receive task. */
TaskHandle_t receiveTask; /**< @brief Handle of the receive task, if any. */
IotNetworkReceiveCallback_t receiveCallback; /**< @brief Network receive callback, if any. */
void * pReceiveContext; /**< @brief The context for the receive callback. */
bool bufferedByteValid; /**< @brief Used to determine if the buffered byte is valid. */
uint8_t bufferedByte; /**< @brief A single byte buffered from a receive, since AFR Secure Sockets does not have poll(). */
} _networkConnection_t;
/*-----------------------------------------------------------*/
/**
* @brief An #IotNetworkInterface_t that uses the functions in this file.
*/
const IotNetworkInterface_t IotNetworkAfr =
{
.create = IotNetworkAfr_Create,
.setReceiveCallback = IotNetworkAfr_SetReceiveCallback,
.send = IotNetworkAfr_Send,
.receive = IotNetworkAfr_Receive,
.close = IotNetworkAfr_Close,
.destroy = IotNetworkAfr_Destroy
};
/*-----------------------------------------------------------*/
/**
* @brief Destroys a network connection.
*
* @param[in] pNetworkConnection The connection to destroy.
*/
static void _destroyConnection( _networkConnection_t * pNetworkConnection )
{
/* Call Secure Sockets close function to free resources. */
int32_t socketStatus = SOCKETS_Close( pNetworkConnection->socket );
if( socketStatus != SOCKETS_ERROR_NONE )
{
IotLogWarn( "Failed to destroy connection." );
}
/* Free the network connection. */
vPortFree( pNetworkConnection );
}
/*-----------------------------------------------------------*/
/**
* @brief Task routine that waits on incoming network data.
*
* @param[in] pArgument The network connection.
*/
static void _networkReceiveTask( void * pArgument )
{
bool destroyConnection = false;
int32_t socketStatus = 0;
EventBits_t connectionFlags = 0;
/* Cast network connection to the correct type. */
_networkConnection_t * pNetworkConnection = pArgument;
while( true )
{
/* No buffered byte should be in the connection. */
configASSERT( pNetworkConnection->bufferedByteValid == false );
/* Block and wait for 1 byte of data. This simulates the behavior of poll().
* THIS IS A TEMPORARY WORKAROUND AND DOES NOT PROVIDE THREAD-SAFETY AGAINST
* MULTIPLE CALLS OF RECEIVE. */
do
{
socketStatus = SOCKETS_Recv( pNetworkConnection->socket,
&( pNetworkConnection->bufferedByte ),
1,
0 );
connectionFlags = xEventGroupGetBits( ( EventGroupHandle_t ) &( pNetworkConnection->connectionFlags ) );
if( ( connectionFlags & _FLAG_SHUTDOWN ) == _FLAG_SHUTDOWN )
{
socketStatus = SOCKETS_ECLOSED;
}
/* Check for timeout. Some ports return 0, some return EWOULDBLOCK. */
} while( ( socketStatus == 0 ) || ( socketStatus == SOCKETS_EWOULDBLOCK ) );
if( socketStatus <= 0 )
{
break;
}
pNetworkConnection->bufferedByteValid = true;
/* Invoke the network callback. */
pNetworkConnection->receiveCallback( pNetworkConnection,
pNetworkConnection->pReceiveContext );
/* Check if the connection was destroyed by the receive callback. This
* does not need to be thread-safe because the destroy connection function
* may only be called once (per its API doc). */
connectionFlags = xEventGroupGetBits( ( EventGroupHandle_t ) &( pNetworkConnection->connectionFlags ) );
if( ( connectionFlags & _FLAG_CONNECTION_DESTROYED ) == _FLAG_CONNECTION_DESTROYED )
{
destroyConnection = true;
break;
}
}
IotLogDebug( "Network receive task terminating." );
/* If necessary, destroy the network connection before exiting. */
if( destroyConnection == true )
{
_destroyConnection( pNetworkConnection );
}
else
{
/* Set the flag to indicate that the receive task has exited. */
( void ) xEventGroupSetBits( ( EventGroupHandle_t ) &( pNetworkConnection->connectionFlags ),
_FLAG_RECEIVE_TASK_EXITED );
}
vTaskDelete( NULL );
}
/*-----------------------------------------------------------*/
/**
* @brief Set up a secured TLS connection.
*
* @param[in] pAfrCredentials Credentials for the secured connection.
* @param[in] tcpSocket An initialized socket to secure.
* @param[in] pHostName Remote server name for SNI.
* @param[in] hostnameLength The length of `pHostName`.
*
* @return #IOT_NETWORK_SUCCESS or #IOT_NETWORK_SYSTEM_ERROR.
*/
static IotNetworkError_t _tlsSetup( const IotNetworkCredentials_t * pAfrCredentials,
Socket_t tcpSocket,
const char * pHostName,
size_t hostnameLength )
{
IOT_FUNCTION_ENTRY( IotNetworkError_t, IOT_NETWORK_SUCCESS );
int32_t socketStatus = SOCKETS_ERROR_NONE;
/* ALPN options for AWS IoT. */
const char * ppcALPNProtos[] = { socketsAWS_IOT_ALPN_MQTT };
/* Set secured option. */
socketStatus = SOCKETS_SetSockOpt( tcpSocket,
0,
SOCKETS_SO_REQUIRE_TLS,
NULL,
0 );
if( socketStatus != SOCKETS_ERROR_NONE )
{
IotLogError( "Failed to set secured option for new connection." );
IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_SYSTEM_ERROR );
}
/* Set ALPN option. */
if( pAfrCredentials->pAlpnProtos != NULL )
{
socketStatus = SOCKETS_SetSockOpt( tcpSocket,
0,
SOCKETS_SO_ALPN_PROTOCOLS,
ppcALPNProtos,
sizeof( ppcALPNProtos ) / sizeof( ppcALPNProtos[ 0 ] ) );
if( socketStatus != SOCKETS_ERROR_NONE )
{
IotLogError( "Failed to set ALPN option for new connection." );
IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_SYSTEM_ERROR );
}
}
/* Set SNI option. */
if( pAfrCredentials->disableSni == false )
{
socketStatus = SOCKETS_SetSockOpt( tcpSocket,
0,
SOCKETS_SO_SERVER_NAME_INDICATION,
pHostName,
hostnameLength + 1 );
if( socketStatus != SOCKETS_ERROR_NONE )
{
IotLogError( "Failed to set SNI option for new connection." );
IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_SYSTEM_ERROR );
}
}
/* Set custom server certificate. */
if( pAfrCredentials->pRootCa != NULL )
{
socketStatus = SOCKETS_SetSockOpt( tcpSocket,
0,
SOCKETS_SO_TRUSTED_SERVER_CERTIFICATE,
pAfrCredentials->pRootCa,
pAfrCredentials->rootCaSize );
if( socketStatus != SOCKETS_ERROR_NONE )
{
IotLogError( "Failed to set server certificate option for new connection." );
IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_SYSTEM_ERROR );
}
}
IOT_FUNCTION_EXIT_NO_CLEANUP();
}
/*-----------------------------------------------------------*/
IotNetworkError_t IotNetworkAfr_Create( void * pConnectionInfo,
void * pCredentialInfo,
void ** pConnection )
{
IOT_FUNCTION_ENTRY( IotNetworkError_t, IOT_NETWORK_SUCCESS );
Socket_t tcpSocket = SOCKETS_INVALID_SOCKET;
int32_t socketStatus = SOCKETS_ERROR_NONE;
SocketsSockaddr_t serverAddress = { 0 };
EventGroupHandle_t pConnectionFlags = NULL;
SemaphoreHandle_t pConnectionMutex = NULL;
const TickType_t receiveTimeout = pdMS_TO_TICKS( IOT_NETWORK_SOCKET_POLL_MS );
_networkConnection_t * pNewNetworkConnection = NULL;
/* Cast function parameters to correct types. */
const IotNetworkServerInfo_t * pServerInfo = pConnectionInfo;
const IotNetworkCredentials_t * pAfrCredentials = pCredentialInfo;
_networkConnection_t ** pNetworkConnection = ( _networkConnection_t ** ) pConnection;
/* Check host name length against the maximum length allowed by Secure
* Sockets. */
const size_t hostnameLength = strlen( pServerInfo->pHostName );
if( hostnameLength > ( size_t ) securesocketsMAX_DNS_NAME_LENGTH )
{
IotLogError( "Host name length exceeds %d, which is the maximum allowed.",
securesocketsMAX_DNS_NAME_LENGTH );
IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_BAD_PARAMETER );
}
pNewNetworkConnection = pvPortMalloc( sizeof( _networkConnection_t ) );
if( pNewNetworkConnection == NULL )
{
IotLogError( "Failed to allocate memory for new network connection." );
IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_NO_MEMORY );
}
/* Clear the connection information. */
( void ) memset( pNewNetworkConnection, 0x00, sizeof( _networkConnection_t ) );
/* Create a new TCP socket. */
tcpSocket = SOCKETS_Socket( SOCKETS_AF_INET,
SOCKETS_SOCK_STREAM,
SOCKETS_IPPROTO_TCP );
if( tcpSocket == SOCKETS_INVALID_SOCKET )
{
IotLogError( "Failed to create new socket." );
IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_SYSTEM_ERROR );
}
/* Set up connection encryption if credentials are provided. */
if( pAfrCredentials != NULL )
{
status = _tlsSetup( pAfrCredentials, tcpSocket, pServerInfo->pHostName, hostnameLength );
if( status != IOT_NETWORK_SUCCESS )
{
IOT_GOTO_CLEANUP();
}
}
/* Establish connection. */
serverAddress.ucSocketDomain = SOCKETS_AF_INET;
serverAddress.usPort = SOCKETS_htons( pServerInfo->port );
serverAddress.ulAddress = SOCKETS_GetHostByName( pServerInfo->pHostName );
/* Check for errors from DNS lookup. */
if( serverAddress.ulAddress == 0 )
{
IotLogError( "Failed to resolve %s.", pServerInfo->pHostName );
IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_SYSTEM_ERROR );
}
socketStatus = SOCKETS_Connect( tcpSocket,
&serverAddress,
sizeof( SocketsSockaddr_t ) );
if( socketStatus != SOCKETS_ERROR_NONE )
{
IotLogError( "Failed to establish new connection." );
IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_SYSTEM_ERROR );
}
/* Set a long timeout for receive. */
socketStatus = SOCKETS_SetSockOpt( tcpSocket,
0,
SOCKETS_SO_RCVTIMEO,
&receiveTimeout,
sizeof( TickType_t ) );
if( socketStatus != SOCKETS_ERROR_NONE )
{
IotLogError( "Failed to set socket receive timeout." );
IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_SYSTEM_ERROR );
}
IOT_FUNCTION_CLEANUP_BEGIN();
/* Clean up on failure. */
if( status != IOT_NETWORK_SUCCESS )
{
if( tcpSocket != SOCKETS_INVALID_SOCKET )
{
SOCKETS_Close( tcpSocket );
}
/* Clear the connection information. */
if( pNewNetworkConnection != NULL )
{
vPortFree( pNewNetworkConnection );
}
}
else
{
/* Set the socket. */
pNewNetworkConnection->socket = tcpSocket;
/* Create the connection event flags and mutex. */
pConnectionFlags = xEventGroupCreateStatic( &( pNewNetworkConnection->connectionFlags ) );
pConnectionMutex = xSemaphoreCreateMutexStatic( &( pNewNetworkConnection->socketMutex ) );
/* Static event flags and mutex creation should never fail. The handles
* should point inside the connection object. */
configASSERT( pConnectionFlags == ( EventGroupHandle_t ) &( pNewNetworkConnection->connectionFlags ) );
configASSERT( pConnectionMutex == ( SemaphoreHandle_t ) &( pNewNetworkConnection->socketMutex ) );
/* Set the output parameter. */
*pNetworkConnection = pNewNetworkConnection;
}
IOT_FUNCTION_CLEANUP_END();
}
/*-----------------------------------------------------------*/
IotNetworkError_t IotNetworkAfr_SetReceiveCallback( void * pConnection,
IotNetworkReceiveCallback_t receiveCallback,
void * pContext )
{
IotNetworkError_t status = IOT_NETWORK_SUCCESS;
/* Cast network connection to the correct type. */
_networkConnection_t * pNetworkConnection = ( _networkConnection_t * ) pConnection;
/* Set the receive callback and context. */
pNetworkConnection->receiveCallback = receiveCallback;
pNetworkConnection->pReceiveContext = pContext;
/* No flags should be set. */
configASSERT( xEventGroupGetBits( ( EventGroupHandle_t ) &( pNetworkConnection->connectionFlags ) ) == 0 );
/* Create task that waits for incoming data. */
if( xTaskCreate( _networkReceiveTask,
"NetRecv",
IOT_NETWORK_RECEIVE_TASK_STACK_SIZE,
pNetworkConnection,
IOT_NETWORK_RECEIVE_TASK_PRIORITY,
&( pNetworkConnection->receiveTask ) ) != pdPASS )
{
IotLogError( "Failed to create network receive task." );
status = IOT_NETWORK_SYSTEM_ERROR;
}
return status;
}
/*-----------------------------------------------------------*/
size_t IotNetworkAfr_Send( void * pConnection,
const uint8_t * pMessage,
size_t messageLength )
{
size_t bytesSent = 0;
int32_t socketStatus = SOCKETS_ERROR_NONE;
/* Cast network connection to the correct type. */
_networkConnection_t * pNetworkConnection = ( _networkConnection_t * ) pConnection;
/* Only one thread at a time may send on the connection. Lock the socket
* mutex to prevent other threads from sending. */
if( xSemaphoreTake( ( QueueHandle_t ) &( pNetworkConnection->socketMutex ),
portMAX_DELAY ) == pdTRUE )
{
socketStatus = SOCKETS_Send( pNetworkConnection->socket,
pMessage,
messageLength,
0 );
if( socketStatus > 0 )
{
bytesSent = ( size_t ) socketStatus;
}
xSemaphoreGive( ( QueueHandle_t ) &( pNetworkConnection->socketMutex ) );
}
return bytesSent;
}
/*-----------------------------------------------------------*/
size_t IotNetworkAfr_Receive( void * pConnection,
uint8_t * pBuffer,
size_t bytesRequested )
{
int32_t socketStatus = 0;
size_t bytesReceived = 0, bytesRemaining = bytesRequested;
/* Cast network connection to the correct type. */
_networkConnection_t * pNetworkConnection = ( _networkConnection_t * ) pConnection;
/* Write the buffered byte. THIS IS A TEMPORARY WORKAROUND AND ASSUMES THIS
* FUNCTION IS ALWAYS CALLED FROM THE RECEIVE CALLBACK. */
if( pNetworkConnection->bufferedByteValid == true )
{
*pBuffer = pNetworkConnection->bufferedByte;
bytesReceived = 1;
bytesRemaining--;
pNetworkConnection->bufferedByteValid = false;
}
/* Block and wait for incoming data. */
while( bytesRemaining > 0 )
{
socketStatus = SOCKETS_Recv( pNetworkConnection->socket,
pBuffer + bytesReceived,
bytesRemaining,
0 );
if( socketStatus == SOCKETS_EWOULDBLOCK )
{
/* The return value EWOULDBLOCK means no data was received within
* the socket timeout. Ignore it and try again. */
continue;
}
else if( socketStatus <= 0 )
{
IotLogError( "Error %ld while receiving data.", ( long int ) socketStatus );
break;
}
else
{
bytesReceived += ( size_t ) socketStatus;
bytesRemaining -= ( size_t ) socketStatus;
configASSERT( bytesReceived + bytesRemaining == bytesRequested );
}
}
if( bytesReceived < bytesRequested )
{
IotLogWarn( "Receive requested %lu bytes, but %lu bytes received instead.",
( unsigned long ) bytesRequested,
( unsigned long ) bytesReceived );
}
else
{
IotLogDebug( "Successfully received %lu bytes.",
( unsigned long ) bytesRequested );
}
return bytesReceived;
}
/*-----------------------------------------------------------*/
IotNetworkError_t IotNetworkAfr_Close( void * pConnection )
{
int32_t socketStatus = SOCKETS_ERROR_NONE;
/* Cast network connection to the correct type. */
_networkConnection_t * pNetworkConnection = ( _networkConnection_t * ) pConnection;
/* Call Secure Sockets shutdown function to close connection. */
socketStatus = SOCKETS_Shutdown( pNetworkConnection->socket,
SOCKETS_SHUT_RDWR );
if( socketStatus != SOCKETS_ERROR_NONE )
{
IotLogWarn( "Failed to close connection." );
}
/* Set the shutdown flag. */
( void ) xEventGroupSetBits( ( EventGroupHandle_t ) &( pNetworkConnection->connectionFlags ),
_FLAG_SHUTDOWN );
return IOT_NETWORK_SUCCESS;
}
/*-----------------------------------------------------------*/
IotNetworkError_t IotNetworkAfr_Destroy( void * pConnection )
{
/* Cast network connection to the correct type. */
_networkConnection_t * pNetworkConnection = ( _networkConnection_t * ) pConnection;
/* Check if this function is being called from the receive task. */
if( xTaskGetCurrentTaskHandle() == pNetworkConnection->receiveTask )
{
/* Set the flag specifying that the connection is destroyed. */
( void ) xEventGroupSetBits( ( EventGroupHandle_t ) &( pNetworkConnection->connectionFlags ),
_FLAG_CONNECTION_DESTROYED );
}
else
{
/* If a receive task was created, wait for it to exit. */
if( pNetworkConnection->receiveTask != NULL )
{
( void ) xEventGroupWaitBits( ( EventGroupHandle_t ) &( pNetworkConnection->connectionFlags ),
_FLAG_RECEIVE_TASK_EXITED,
pdTRUE,
pdTRUE,
portMAX_DELAY );
}
_destroyConnection( pNetworkConnection );
}
return IOT_NETWORK_SUCCESS;
}
/*-----------------------------------------------------------*/

View file

@ -0,0 +1,364 @@
/*
* Amazon FreeRTOS Platform V1.0.0
* Copyright (C) 2019 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_threads_freertos.c
* @brief Implementation of the functions in iot_threads.h for POSIX systems.
*/
/* The config header is always included first. */
#include "iot_config.h"
#include "semphr.h"
/* Platform threads include. */
#include "platform/iot_platform_types_freertos.h"
#include "platform/iot_threads.h"
#include "types/iot_platform_types.h"
/* Configure logs for the functions in this file. */
#ifdef IOT_LOG_LEVEL_PLATFORM
#define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_PLATFORM
#else
#ifdef IOT_LOG_LEVEL_GLOBAL
#define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_GLOBAL
#else
#define LIBRARY_LOG_LEVEL IOT_LOG_NONE
#endif
#endif
#define LIBRARY_LOG_NAME ( "THREAD" )
#include "iot_logging_setup.h"
/*
* Provide default values for undefined memory allocation functions based on
* the usage of dynamic memory allocation.
*/
#ifndef IotThreads_Malloc
#include <stdlib.h>
/**
* @brief Memory allocation. This function should have the same signature
* as [malloc](http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html).
*/
#define IotThreads_Malloc malloc
#endif
#ifndef IotThreads_Free
#include <stdlib.h>
/**
* @brief Free memory. This function should have the same signature as
* [free](http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html).
*/
#define IotThreads_Free free
#endif
/*-----------------------------------------------------------*/
static void _threadRoutineWrapper( void * pArgument )
{
threadInfo_t * pThreadInfo = ( threadInfo_t * ) pArgument;
/* Run the thread routine. */
pThreadInfo->threadRoutine( pThreadInfo->pArgument );
IotThreads_Free( pThreadInfo );
vTaskDelete( NULL );
}
/*-----------------------------------------------------------*/
bool Iot_CreateDetachedThread( IotThreadRoutine_t threadRoutine,
void * pArgument,
int32_t priority,
size_t stackSize )
{
bool status = true;
configASSERT( threadRoutine != NULL );
IotLogDebug( "Creating new thread." );
threadInfo_t * pThreadInfo = IotThreads_Malloc( sizeof( threadInfo_t ) );
if( pThreadInfo == NULL )
{
IotLogDebug( "Unable to allocate memory for threadRoutine %p.", threadRoutine );
status = false;
}
/* Create the FreeRTOS task that will run the thread. */
if( status )
{
pThreadInfo->threadRoutine = threadRoutine;
pThreadInfo->pArgument = pArgument;
if( xTaskCreate( _threadRoutineWrapper,
"iot_thread",
( configSTACK_DEPTH_TYPE ) stackSize,
pThreadInfo,
priority,
NULL ) != pdPASS )
{
/* Task creation failed. */
IotLogWarn( "Failed to create thread." );
IotThreads_Free( pThreadInfo );
status = false;
}
}
return status;
}
/*-----------------------------------------------------------*/
bool IotMutex_Create( IotMutex_t * pNewMutex,
bool recursive )
{
_IotSystemMutex_t * internalMutex = ( _IotSystemMutex_t * ) pNewMutex;
configASSERT( internalMutex != NULL );
IotLogDebug( "Creating new mutex %p.", pNewMutex );
if( recursive )
{
( void ) xSemaphoreCreateRecursiveMutexStatic( &internalMutex->xMutex );
}
else
{
( void ) xSemaphoreCreateMutexStatic( &internalMutex->xMutex );
}
/* remember the type of mutex */
if( recursive )
{
internalMutex->recursive = pdTRUE;
}
else
{
internalMutex->recursive = pdFALSE;
}
return true;
}
/*-----------------------------------------------------------*/
void IotMutex_Destroy( IotMutex_t * pMutex )
{
_IotSystemMutex_t * internalMutex = ( _IotSystemMutex_t * ) pMutex;
configASSERT( internalMutex != NULL );
vSemaphoreDelete( ( SemaphoreHandle_t ) &internalMutex->xMutex );
}
/*-----------------------------------------------------------*/
bool prIotMutexTimedLock( IotMutex_t * pMutex,
TickType_t timeout )
{
_IotSystemMutex_t * internalMutex = ( _IotSystemMutex_t * ) pMutex;
BaseType_t lockResult;
configASSERT( internalMutex != NULL );
IotLogDebug( "Locking mutex %p.", internalMutex );
/* Call the correct FreeRTOS mutex take function based on mutex type. */
if( internalMutex->recursive == pdTRUE )
{
lockResult = xSemaphoreTakeRecursive( ( SemaphoreHandle_t ) &internalMutex->xMutex, timeout );
}
else
{
lockResult = xSemaphoreTake( ( SemaphoreHandle_t ) &internalMutex->xMutex, timeout );
}
return( lockResult == pdTRUE );
}
/*-----------------------------------------------------------*/
void IotMutex_Lock( IotMutex_t * pMutex )
{
prIotMutexTimedLock( pMutex, portMAX_DELAY );
}
/*-----------------------------------------------------------*/
bool IotMutex_TryLock( IotMutex_t * pMutex )
{
return prIotMutexTimedLock( pMutex, 0 );
}
/*-----------------------------------------------------------*/
void IotMutex_Unlock( IotMutex_t * pMutex )
{
_IotSystemMutex_t * internalMutex = ( _IotSystemMutex_t * ) pMutex;
configASSERT( internalMutex != NULL );
IotLogDebug( "Unlocking mutex %p.", internalMutex );
/* Call the correct FreeRTOS mutex unlock function based on mutex type. */
if( internalMutex->recursive == pdTRUE )
{
( void ) xSemaphoreGiveRecursive( ( SemaphoreHandle_t ) &internalMutex->xMutex );
}
else
{
( void ) xSemaphoreGive( ( SemaphoreHandle_t ) &internalMutex->xMutex );
}
}
/*-----------------------------------------------------------*/
bool IotSemaphore_Create( IotSemaphore_t * pNewSemaphore,
uint32_t initialValue,
uint32_t maxValue )
{
_IotSystemSemaphore_t * internalSemaphore = ( _IotSystemSemaphore_t * ) pNewSemaphore;
configASSERT( internalSemaphore != NULL );
IotLogDebug( "Creating new semaphore %p.", pNewSemaphore );
( void ) xSemaphoreCreateCountingStatic( maxValue, initialValue, &internalSemaphore->xSemaphore );
return true;
}
/*-----------------------------------------------------------*/
uint32_t IotSemaphore_GetCount( IotSemaphore_t * pSemaphore )
{
_IotSystemSemaphore_t * internalSemaphore = ( _IotSystemSemaphore_t * ) pSemaphore;
UBaseType_t count = 0;
configASSERT( internalSemaphore != NULL );
count = uxSemaphoreGetCount( ( SemaphoreHandle_t ) &internalSemaphore->xSemaphore );
IotLogDebug( "Semaphore %p has count %d.", pSemaphore, count );
return ( uint32_t ) count;
}
/*-----------------------------------------------------------*/
void IotSemaphore_Destroy( IotSemaphore_t * pSemaphore )
{
_IotSystemSemaphore_t * internalSemaphore = ( _IotSystemSemaphore_t * ) pSemaphore;
configASSERT( internalSemaphore != NULL );
IotLogDebug( "Destroying semaphore %p.", internalSemaphore );
vSemaphoreDelete( ( SemaphoreHandle_t ) &internalSemaphore->xSemaphore );
}
/*-----------------------------------------------------------*/
void IotSemaphore_Wait( IotSemaphore_t * pSemaphore )
{
_IotSystemSemaphore_t * internalSemaphore = ( _IotSystemSemaphore_t * ) pSemaphore;
configASSERT( internalSemaphore != NULL );
IotLogDebug( "Waiting on semaphore %p.", internalSemaphore );
/* Take the semaphore using the FreeRTOS API. */
if( xSemaphoreTake( ( SemaphoreHandle_t ) &internalSemaphore->xSemaphore,
portMAX_DELAY ) != pdTRUE )
{
IotLogWarn( "Failed to wait on semaphore %p.",
pSemaphore );
/* Assert here, debugging we always want to know that this happened because you think
* that you are waiting successfully on the semaphore but you are not */
configASSERT( false );
}
}
/*-----------------------------------------------------------*/
bool IotSemaphore_TryWait( IotSemaphore_t * pSemaphore )
{
_IotSystemSemaphore_t * internalSemaphore = ( _IotSystemSemaphore_t * ) pSemaphore;
configASSERT( internalSemaphore != NULL );
IotLogDebug( "Attempting to wait on semaphore %p.", internalSemaphore );
return IotSemaphore_TimedWait( pSemaphore, 0 );
}
/*-----------------------------------------------------------*/
bool IotSemaphore_TimedWait( IotSemaphore_t * pSemaphore,
uint32_t timeoutMs )
{
_IotSystemSemaphore_t * internalSemaphore = ( _IotSystemSemaphore_t * ) pSemaphore;
configASSERT( internalSemaphore != NULL );
/* Take the semaphore using the FreeRTOS API. Cast the calculation to 64 bit to avoid overflows*/
if( xSemaphoreTake( ( SemaphoreHandle_t ) &internalSemaphore->xSemaphore,
pdMS_TO_TICKS( timeoutMs ) ) != pdTRUE )
{
/* Only warn if timeout > 0 */
if( timeoutMs > 0 )
{
IotLogWarn( "Timeout waiting on semaphore %p.",
internalSemaphore );
}
return false;
}
return true;
}
/*-----------------------------------------------------------*/
void IotSemaphore_Post( IotSemaphore_t * pSemaphore )
{
_IotSystemSemaphore_t * internalSemaphore = ( _IotSystemSemaphore_t * ) pSemaphore;
configASSERT( internalSemaphore != NULL );
IotLogDebug( "Posting to semaphore %p.", internalSemaphore );
/* Give the semaphore using the FreeRTOS API. */
BaseType_t result = xSemaphoreGive( ( SemaphoreHandle_t ) &internalSemaphore->xSemaphore );
if( result == pdFALSE )
{
IotLogDebug( "Unable to give semaphore over maximum", internalSemaphore );
}
}
/*-----------------------------------------------------------*/

View file

@ -0,0 +1,216 @@
/*
* Amazon FreeRTOS Platform V1.0.0
* Copyright (C) 2019 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_clock.h
* @brief Time-related functions used by libraries in this SDK.
*/
#ifndef IOT_CLOCK_H_
#define IOT_CLOCK_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/* Platform layer types include. */
#include "types/iot_platform_types.h"
/**
* @functionspage{platform_clock,platform clock component,Clock}
* - @functionname{platform_clock_function_gettimestring}
* - @functionname{platform_clock_function_gettimems}
* - @functionname{platform_clock_function_sleepms}
* - @functionname{platform_clock_function_timercreate}
* - @functionname{platform_clock_function_timerdestroy}
* - @functionname{platform_clock_function_timerarm}
*/
/**
* @functionpage{IotClock_GetTimestring,platform_clock,gettimestring}
* @functionpage{IotClock_GetTimeMs,platform_clock,gettimems}
* @functionpage{IotClock_SleepMs,platform_clock,sleepms}
* @functionpage{IotClock_TimerCreate,platform_clock,timercreate}
* @functionpage{IotClock_TimerDestroy,platform_clock,timerdestroy}
* @functionpage{IotClock_TimerArm,platform_clock,timerarm}
*/
/**
* @brief Generates a human-readable timestring, such as "01 Jan 2018 12:00".
*
* This function uses the system clock to generate a human-readable timestring.
* This timestring is printed by the [logging functions](@ref logging_functions).
*
* @param[out] pBuffer A buffer to store the timestring in.
* @param[in] bufferSize The size of `pBuffer`.
* @param[out] pTimestringLength The actual length of the timestring stored in
* `pBuffer`.
*
* @return `true` if a timestring was successfully generated; `false` otherwise.
*
* @warning The implementation of this function must not call any [logging functions]
* (@ref logging_functions).
*
* <b>Example</b>
* @code{c}
* char timestring[ 32 ];
* size_t timestringLength = 0;
*
* if( IotClock_GetTimestring( timestring, 32, &timestringLength ) == true )
* {
* printf( "Timestring: %.*s", timestringLength, timestring );
* }
* @endcode
*/
/* @[declare_platform_clock_gettimestring] */
bool IotClock_GetTimestring( char * pBuffer,
size_t bufferSize,
size_t * pTimestringLength );
/* @[declare_platform_clock_gettimestring] */
/**
* @brief Returns a nonzero, monotonically-increasing system time in milliseconds.
*
* This function reads a millisecond-resolution system clock. The clock should
* always be monotonically-increasing; therefore, real-time clocks that may be
* set by another process are not suitable for this function's implementation.
*
* @return The value of the system clock. This function is not expected to fail.
*
* <b>Example</b>
* @code{c}
* // Get current time.
* uint64_t currentTime = IotClock_GetTimeMs();
* @endcode
*/
/* @[declare_platform_clock_gettimems] */
uint64_t IotClock_GetTimeMs( void );
/* @[declare_platform_clock_gettimems] */
/**
* @brief Delay for the given number of milliseconds.
*
* This function suspends its calling thread for at least `sleepTimeMs` milliseconds.
*
* @param[in] sleepTimeMs Sleep time (in milliseconds).
*/
/* @[declare_platform_clock_sleepms] */
void IotClock_SleepMs( uint32_t sleepTimeMs );
/* @[declare_platform_clock_sleepms] */
/**
* @brief Create a new timer.
*
* This function creates a new, unarmed timer. It must be called on an uninitialized
* #IotTimer_t. This function must not be called on an already-initialized #IotTimer_t.
*
* @param[out] pNewTimer Set to a new timer handle on success.
* @param[in] expirationRoutine The function to run when this timer expires. This
* function should be called in its own <i>detached</i> thread.
* @param[in] pArgument The argument to pass to `expirationRoutine`.
*
* @return `true` if the timer is successfully created; `false` otherwise.
*
* @see @ref platform_clock_function_timerdestroy, @ref platform_clock_function_timerarm
*/
/* @[declare_platform_clock_timercreate] */
bool IotClock_TimerCreate( IotTimer_t * pNewTimer,
IotThreadRoutine_t expirationRoutine,
void * pArgument );
/* @[declare_platform_clock_timercreate] */
/**
* @brief Free resources used by a timer.
*
* This function frees resources used by a timer. It must be called on an initialized
* #IotTimer_t. No other timer functions should be called on `pTimer` after calling
* this function (unless the timer is re-created).
*
* This function will stop the `pTimer` if it is armed.
*
* @param[in] pTimer The timer to destroy.
*
* @see @ref platform_clock_function_timercreate, @ref platform_clock_function_timerarm
*/
/* @[declare_platform_clock_timerdestroy] */
void IotClock_TimerDestroy( IotTimer_t * pTimer );
/* @[declare_platform_clock_timerdestroy] */
/**
* @brief Arm a timer to expire at the given relative timeout.
*
* This function arms a timer to run its expiration routine at the given time.
*
* If `periodMs` is nonzero, the timer should expire periodically at intervals
* such as:
* - `relativeTimeoutMs`
* - `relativeTimeoutMs + periodMs`
* - `relativeTimeoutMs + 2 * periodMs`
* - Etc. (subject to some jitter).
*
* Setting `periodMs` to `0` arms a one-shot, non-periodic timer.
*
* @param[in] pTimer The timer to arm.
* @param[in] relativeTimeoutMs When the timer should expire, relative to the time
* this function is called.
* @param[in] periodMs How often the timer should expire again after `relativeTimerMs`.
*
* @return `true` if the timer was successfully armed; `false` otherwise.
*
* @see @ref platform_clock_function_timercreate, @ref platform_clock_function_timerdestroy
*
* <b>Example</b>
* @code{c}
*
* void timerExpirationRoutine( void * pArgument );
*
* void timerExample( void )
* {
* IotTimer_t timer;
*
* if( IotClock_TimerCreate( &timer, timerExpirationRoutine, NULL ) == true )
* {
* // Set the timer to periodically expire every 10 seconds.
* if( IotClock_TimerArm( &timer, 10000, 10000 ) == true )
* {
* // Wait for timer to expire.
* }
*
* IotClock_TimerDestroy( &timer );
* }
* }
* @endcode
*/
/* @[declare_platform_clock_timerarm] */
bool IotClock_TimerArm( IotTimer_t * pTimer,
uint32_t relativeTimeoutMs,
uint32_t periodMs );
/* @[declare_platform_clock_timerarm] */
#endif /* ifndef IOT_CLOCK_H_ */

View file

@ -0,0 +1,103 @@
/*
* Amazon FreeRTOS Platform V1.0.0
* Copyright (C) 2019 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_metrics.h
* @brief Functions for retrieving [Device Defender](@ref defender) metrics.
*
* The functions in this header are only required by Device Defender. They do not
* need to be implemented if Device Defender is not used.
*/
#ifndef IOT_METRICS_H_
#define IOT_METRICS_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdbool.h>
/* Linear containers (lists and queues) include. */
#include "iot_linear_containers.h"
/**
* @functionspage{platform_metrics,platform metrics component,Metrics}
* - @functionname{platform_metrics_function_init}
* - @functionname{platform_metrics_function_cleanup}
* - @functionname{platform_metrics_function_gettcpconnections}
*/
/**
* @functionpage{IotMetrics_Init,platform_metrics,init}
* @functionpage{IotMetrics_Cleanup,platform_metrics,cleanup}
* @functionpage{IotMetrics_GetTcpConnections,platform_metrics,gettcpconnections}
*/
/**
* @brief One-time initialization function for the platform metrics component.
*
* This function initializes the platform metrics component. <b>It must be called
* once (and only once) before calling any other metrics or [Device Defender function]
* (@ref defender_functions).</b> Calling this function more than once without first
* calling @ref platform_metrics_function_cleanup may result in a crash.
*
* @return `true` is initialization succeeded; `false` otherwise.
*
* @warning No thread-safety guarantees are provided for this function.
*/
/* @[declare_platform_metrics_init] */
bool IotMetrics_Init( void );
/* @[declare_platform_metrics_init] */
/**
* @brief One-time deinitialization function for the platform metrics component.
*
* This function frees resources taken in @ref platform_metrics_function_init.
* No other metrics or [Device Defender functions](@ref defender_functions) may
* be called unless @ref platform_metrics_function_init is called again.
*
* @warning No thread-safety guarantees are provided for this function.
*/
/* @[declare_platform_metrics_cleanup] */
void IotMetrics_Cleanup( void );
/* @[declare_platform_metrics_cleanup] */
/**
* @brief Retrieve a list of active TCP connections from the system.
*
* The provided connections are reported by Device Defender.
*
* @param[in] pContext Context passed as the first parameter of `metricsCallback`.
* @param[in] metricsCallback Called by this function to provide the list of TCP
* connections. The list given by this function is should not be used after the
* callback returns.
*/
/* @[declare_platform_metrics_gettcpconnections] */
void IotMetrics_GetTcpConnections( void * pContext,
void ( * metricsCallback )( void *, const IotListDouble_t * ) );
/* @[declare_platform_metrics_gettcpconnections] */
#endif /* ifndef IOT_METRICS_H_ */

View file

@ -0,0 +1,294 @@
/*
* Amazon FreeRTOS Platform V1.0.0
* Copyright (C) 2019 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_network.h
* @brief Abstraction of network functions used by libraries in this SDK.
*/
#ifndef IOT_NETWORK_H_
#define IOT_NETWORK_H_
/* Standard includes. */
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
/**
* @ingroup platform_datatypes_enums
* @brief Return codes for [network functions](@ref platform_network_functions).
*/
typedef enum IotNetworkError
{
IOT_NETWORK_SUCCESS = 0, /**< Function successfully completed. */
IOT_NETWORK_FAILURE, /**< Generic failure not covered by other values. */
IOT_NETWORK_BAD_PARAMETER, /**< At least one parameter was invalid. */
IOT_NETWORK_NO_MEMORY, /**< Memory allocation failed. */
IOT_NETWORK_SYSTEM_ERROR /**< An error occurred when calling a system API. */
} IotNetworkError_t;
/**
* @page platform_network_functions Networking
* @brief Functions of the network abstraction component.
*
* The network abstraction component does not declare functions, but uses function
* pointers instead. This allows multiple network stacks to be used at the same time.
* Libraries that require the network will request an #IotNetworkInterface_t
* parameter. The members of the #IotNetworkInterface_t will be called whenever
* the library interacts with the network.
*
* The following function pointers are associated with an #IotNetworkInterface_t.
* Together, they represent a network stack.
* - @functionname{platform_network_function_create}
* - @functionname{platform_network_function_setreceivecallback}
* - @functionname{platform_network_function_send}
* - @functionname{platform_network_function_receive}
* - @functionname{platform_network_function_close}
* - @functionname{platform_network_function_destroy}
* - @functionname{platform_network_function_receivecallback}
*/
/**
* @functionpage{IotNetworkInterface_t::create,platform_network,create}
* @functionpage{IotNetworkInterface_t::setReceiveCallback,platform_network,setreceivecallback}
* @functionpage{IotNetworkInterface_t::send,platform_network,send}
* @functionpage{IotNetworkInterface_t::receive,platform_network,receive}
* @functionpage{IotNetworkInterface_t::close,platform_network,close}
* @functionpage{IotNetworkInterface_t::destroy,platform_network,destroy}
* @functionpage{IotNetworkReceiveCallback_t,platform_network,receivecallback}
*/
/**
* @brief Provide an asynchronous notification of incoming network data.
*
* A function with this signature may be set with @ref platform_network_function_setreceivecallback
* to be invoked when data is available on the network.
*
* @param[in] pConnection The connection on which data is available, defined by
* the network stack.
* @param[in] pContext The third argument passed to @ref platform_network_function_setreceivecallback.
*/
/* @[declare_platform_network_receivecallback] */
typedef void ( * IotNetworkReceiveCallback_t )( void * pConnection,
void * pContext );
/* @[declare_platform_network_receivecallback] */
/**
* @ingroup platform_datatypes_paramstructs
* @brief Represents the functions of a network stack.
*
* Functions that match these signatures should be implemented against a system's
* network stack. See the `platform` directory for existing implementations.
*/
typedef struct IotNetworkInterface
{
/**
* @brief Create a new network connection.
*
* This function allocates resources and establishes a new network connection.
* @param[in] pConnectionInfo Represents information needed to set up the
* new connection, defined by the network stack.
* @param[in] pCredentialInfo Represents information needed to secure the
* new connection, defined by the network stack.
* @param[out] pConnection Set to represent a new connection, defined by the
* network stack.
*
* @return Any #IotNetworkError_t, as defined by the network stack.
*/
/* @[declare_platform_network_create] */
IotNetworkError_t ( * create )( void * pConnectionInfo,
void * pCredentialInfo,
void ** pConnection );
/* @[declare_platform_network_create] */
/**
* @brief Register an @ref platform_network_function_receivecallback.
*
* Sets an @ref platform_network_function_receivecallback to be called
* asynchronously when data arrives on the network. The network stack
* should invoke this function "as if" it were the thread routine of a
* detached thread.
*
* Each network connection may only have one receive callback at any time.
* @ref platform_network_function_close is expected to remove any active
* receive callbacks.
*
* @param[in] pConnection The connection to associate with the receive callback.
* @param[in] receiveCallback The function to invoke for incoming network data.
* @param[in] pContext A value to pass as the first parameter to the receive callback.
*
* @return Any #IotNetworkError_t, as defined by the network stack.
*
* @see platform_network_function_receivecallback
*/
/* @[declare_platform_network_setreceivecallback] */
IotNetworkError_t ( * setReceiveCallback )( void * pConnection,
IotNetworkReceiveCallback_t receiveCallback,
void * pContext );
/* @[declare_platform_network_setreceivecallback] */
/**
* @brief Send data over a return connection.
*
* Attempts to transmit `messageLength` bytes of `pMessage` across the
* connection represented by `pConnection`. Returns the number of bytes
* actually sent, `0` on failure.
*
* @param[in] pConnection The connection used to send data, defined by the
* network stack.
* @param[in] pMessage The message to send.
* @param[in] messageLength The length of `pMessage`.
*
* @return The number of bytes successfully sent, `0` on failure.
*/
/* @[declare_platform_network_send] */
size_t ( * send )( void * pConnection,
const uint8_t * pMessage,
size_t messageLength );
/* @[declare_platform_network_send] */
/**
* @brief Block and wait for incoming network data.
*
* Wait for a message of size `bytesRequested` to arrive on the network and
* place it in `pBuffer`.
*
* @param[in] pConnection The connection to wait on, defined by the network
* stack.
* @param[out] pBuffer Where to place the incoming network data. This buffer
* must be at least `bytesRequested` in size.
* @param[in] bytesRequested How many bytes to wait for. `pBuffer` must be at
* least this size.
*
* @return The number of bytes successfully received. This should be
* `bytesRequested` when successful. Any other value may indicate an error.
*/
/* @[declare_platform_network_receive] */
size_t ( * receive )( void * pConnection,
uint8_t * pBuffer,
size_t bytesRequested );
/* @[declare_platform_network_receive] */
/**
* @brief Close a network connection.
*
* This function closes the connection, but does not release the resources
* used by the connection. This allows calls to other networking functions
* to return an error and handle a closed connection without the risk of
* crashing. Once it can be guaranteed that `pConnection` will no longer be
* used, the connection can be destroyed with @ref platform_network_function_destroy.
*
* In addition to closing the connection, this function should also remove
* any active [receive callback](@ref platform_network_function_receivecallback).
*
* @param[in] pConnection The network connection to close, defined by the
* network stack.
*
* @return Any #IotNetworkError_t, as defined by the network stack.
*
* @note It must be safe to call this function on an already-closed connection.
*/
/* @[declare_platform_network_close] */
IotNetworkError_t ( * close )( void * pConnection );
/* @[declare_platform_network_close] */
/**
* @brief Free resources used by a network connection.
*
* This function releases the resources of a closed connection. It should be
* called after @ref platform_network_function_close.
*
* @param[in] pConnection The network connection to destroy, defined by
* the network stack.
*
* @return Any #IotNetworkError_t, as defined by the network stack.
*
* @attention No function should be called on the network connection after
* calling this function. This function must be safe to call from a
* [receive callback](@ref platform_network_function_receivecallback).
*/
/* @[declare_platform_network_destroy] */
IotNetworkError_t ( * destroy )( void * pConnection );
/* @[declare_platform_network_destroy] */
} IotNetworkInterface_t;
/**
* @ingroup platform_datatypes_paramstructs
* @brief Information on the remote server for connection setup.
*
* May be passed to #IotNetworkInterface_t.create as `pConnectionInfo`. This
* structure contains commonly-used parameters, but may be replaced with an
* alternative.
*/
typedef struct IotNetworkServerInfo
{
const char * pHostName; /**< @brief Server host name. Must be NULL-terminated. */
uint16_t port; /**< @brief Server port in host-order. */
} IotNetworkServerInfo_t;
/**
* @ingroup platform_datatypes_paramstructs
* @brief Contains the credentials necessary for connection setup.
*
* May be passed to #IotNetworkInterface_t.create as `pCredentialInfo`. This
* structure contains commonly-used parameters, but may be replaced with an
* alternative.
*/
typedef struct IotNetworkCredentials
{
/**
* @brief Set this to a non-NULL value to use ALPN.
*
* This string must be NULL-terminated.
*
* See [this link]
* (https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-why-it-is-useful-and-how-it-works/)
* for more information.
*/
const char * pAlpnProtos;
/**
* @brief Set this to a non-zero value to use TLS max fragment length
* negotiation (TLS MFLN).
*
* @note The network stack may have a minimum value for this parameter and
* may return an error if this parameter is too small.
*/
size_t maxFragmentLength;
/**
* @brief Disable server name indication (SNI) for a TLS session.
*/
bool disableSni;
const char * pRootCa; /**< @brief String representing a trusted server root certificate. */
size_t rootCaSize; /**< @brief Size associated with #IotNetworkCredentials_t.pRootCa. */
const char * pClientCert; /**< @brief String representing the client certificate. */
size_t clientCertSize; /**< @brief Size associated with #IotNetworkCredentials_t.pClientCert. */
const char * pPrivateKey; /**< @brief String representing the client certificate's private key. */
size_t privateKeySize; /**< @brief Size associated with #IotNetworkCredentials_t.pPrivateKey. */
} IotNetworkCredentials_t;
#endif /* ifndef IOT_NETWORK_H_ */

View file

@ -0,0 +1,355 @@
/*
* Amazon FreeRTOS Platform V1.0.0
* Copyright (C) 2019 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_threads.h
* @brief Threading and synchronization functions used by libraries in this SDK.
*/
#ifndef IOT_THREADS_H_
#define IOT_THREADS_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdbool.h>
#include <stdint.h>
/* Platform layer types include. */
#include "types/iot_platform_types.h"
/**
* @functionspage{platform_threads,platform thread management,Thread Management}
* - @functionname{platform_threads_function_createdetachedthread}
* - @functionname{platform_threads_function_mutexcreate}
* - @functionname{platform_threads_function_mutexdestroy}
* - @functionname{platform_threads_function_mutexlock}
* - @functionname{platform_threads_function_mutextrylock}
* - @functionname{platform_threads_function_mutexunlock}
* - @functionname{platform_threads_function_semaphorecreate}
* - @functionname{platform_threads_function_semaphoredestroy}
* - @functionname{platform_threads_function_semaphoregetcount}
* - @functionname{platform_threads_function_semaphorewait}
* - @functionname{platform_threads_function_semaphoretrywait}
* - @functionname{platform_threads_function_semaphoretimedwait}
* - @functionname{platform_threads_function_semaphorepost}
*/
/**
* @functionpage{Iot_CreateDetachedThread,platform_threads,createdetachedthread}
* @functionpage{IotMutex_Create,platform_threads,mutexcreate}
* @functionpage{IotMutex_Destroy,platform_threads,mutexdestroy}
* @functionpage{IotMutex_Lock,platform_threads,mutexlock}
* @functionpage{IotMutex_TryLock,platform_threads,mutextrylock}
* @functionpage{IotMutex_Unlock,platform_threads,mutexunlock}
* @functionpage{IotSemaphore_Create,platform_threads,semaphorecreate}
* @functionpage{IotSemaphore_Destroy,platform_threads,semaphoredestroy}
* @functionpage{IotSemaphore_GetCount,platform_threads,semaphoregetcount}
* @functionpage{IotSemaphore_Wait,platform_threads,semaphorewait}
* @functionpage{IotSemaphore_TryWait,platform_threads,semaphoretrywait}
* @functionpage{IotSemaphore_TimedWait,platform_threads,semaphoretimedwait}
* @functionpage{IotSemaphore_Post,platform_threads,semaphorepost}
*/
/**
* @brief Create a new detached thread, i.e. a thread that cleans up after itself.
*
* This function creates a new thread. Threads created by this function exit
* upon returning from the thread routine. Any resources taken must be freed
* by the exiting thread.
*
* @param[in] threadRoutine The function this thread should run.
* @param[in] pArgument The argument passed to `threadRoutine`.
* @param[in] priority Represents the priority of the new thread, as defined by
* the system. The value #IOT_THREAD_DEFAULT_PRIORITY (i.e. `0`) must be used to
* represent the system default for thread priority.
* @param[in] stackSize Represents the stack size of the new thread, as defined
* by the system. The value #IOT_THREAD_DEFAULT_STACK_SIZE (i.e. `0`) must be used
* to represent the system default for stack size.
*
* @return `true` if the new thread was successfully created; `false` otherwise.
*
* @code{c}
* // Thread routine.
* void threadRoutine( void * pArgument );
*
* // Run threadRoutine in a detached thread, using default priority and stack size.
* if( Iot_CreateDetachedThread( threadRoutine,
* NULL,
* IOT_THREAD_DEFAULT_PRIORITY,
* IOT_THREAD_DEFAULT_STACK_SIZE ) == true )
* {
* // Success
* }
* else
* {
* // Failure, no thread was created.
* }
* @endcode
*/
/* @[declare_platform_threads_createdetachedthread] */
bool Iot_CreateDetachedThread( IotThreadRoutine_t threadRoutine,
void * pArgument,
int32_t priority,
size_t stackSize );
/* @[declare_platform_threads_createdetachedthread] */
/**
* @brief Create a new mutex.
*
* This function creates a new, unlocked mutex. It must be called on an uninitialized
* #IotMutex_t. This function must not be called on an already-initialized #IotMutex_t.
*
* @param[in] pNewMutex Pointer to the memory that will hold the new mutex.
* @param[in] recursive Set to `true` to create a recursive mutex, i.e. a mutex that
* may be locked multiple times by the same thread. If the system does not support
* recursive mutexes, this function should do nothing and return `false`.
*
* @return `true` if mutex creation succeeds; `false` otherwise.
*
* @see @ref platform_threads_function_mutexdestroy
*
* <b>Example</b>
* @code{c}
* IotMutex_t mutex;
*
* // Create non-recursive mutex.
* if( IotMutex_Create( &mutex, false ) == true )
* {
* // Lock and unlock the mutex...
*
* // Destroy the mutex when it's no longer needed.
* IotMutex_Destroy( &mutex );
* }
* @endcode
*/
/* @[declare_platform_threads_mutexcreate] */
bool IotMutex_Create( IotMutex_t * pNewMutex, bool recursive );
/* @[declare_platform_threads_mutexcreate] */
/**
* @brief Free resources used by a mutex.
*
* This function frees resources used by a mutex. It must be called on an initialized
* #IotMutex_t. No other mutex functions should be called on `pMutex` after calling
* this function (unless the mutex is re-created).
*
* @param[in] pMutex The mutex to destroy.
*
* @warning This function must not be called on a locked mutex.
* @see @ref platform_threads_function_mutexcreate
*/
/* @[declare_platform_threads_mutexdestroy] */
void IotMutex_Destroy( IotMutex_t * pMutex );
/* @[declare_platform_threads_mutexdestroy] */
/**
* @brief Lock a mutex. This function should only return when the mutex is locked;
* it is not expected to fail.
*
* This function blocks and waits until a mutex is available. It waits forever
* (deadlocks) if `pMutex` is already locked and never unlocked.
*
* @param[in] pMutex The mutex to lock.
*
* @see @ref platform_threads_function_mutextrylock for a nonblocking lock.
*/
/* @[declare_platform_threads_mutexlock] */
void IotMutex_Lock( IotMutex_t * pMutex );
/* @[declare_platform_threads_mutexlock] */
/**
* @brief Attempt to lock a mutex. Return immediately if the mutex is not available.
*
* If `pMutex` is available, this function immediately locks it and returns.
* Otherwise, this function returns without locking `pMutex`.
*
* @param[in] pMutex The mutex to lock.
*
* @return `true` if the mutex was successfully locked; `false` if the mutex was
* not available.
*
* @see @ref platform_threads_function_mutexlock for a blocking lock.
*/
/* @[declare_platform_threads_mutextrylock] */
bool IotMutex_TryLock( IotMutex_t * pMutex );
/* @[declare_platform_threads_mutextrylock] */
/**
* @brief Unlock a mutex. This function should only return when the mutex is unlocked;
* it is not expected to fail.
*
* Unlocks a locked mutex. `pMutex` must have been locked by the thread calling
* this function.
*
* @param[in] pMutex The mutex to unlock.
*
* @note This function should not be called on a mutex that is already unlocked.
*/
/* @[declare_platform_threads_mutexunlock] */
void IotMutex_Unlock( IotMutex_t * pMutex );
/* @[declare_platform_threads_mutexunlock] */
/**
* @brief Create a new counting semaphore.
*
* This function creates a new counting semaphore with a given intial and
* maximum value. It must be called on an uninitialized #IotSemaphore_t.
* This function must not be called on an already-initialized #IotSemaphore_t.
*
* @param[in] pNewSemaphore Pointer to the memory that will hold the new semaphore.
* @param[in] initialValue The semaphore should be initialized with this value.
* @param[in] maxValue The maximum value the semaphore will reach.
*
* @return `true` if semaphore creation succeeds; `false` otherwise.
*
* @see @ref platform_threads_function_semaphoredestroy
*
* <b>Example</b>
* @code{c}
* IotSemaphore_t sem;
*
* // Create a locked binary semaphore.
* if( IotSemaphore_Create( &sem, 0, 1 ) == true )
* {
* // Unlock the semaphore.
* IotSemaphore_Post( &sem );
*
* // Destroy the semaphore when it's no longer needed.
* IotSemaphore_Destroy( &sem );
* }
* @endcode
*/
/* @[declare_platform_threads_semaphorecreate] */
bool IotSemaphore_Create( IotSemaphore_t * pNewSemaphore,
uint32_t initialValue,
uint32_t maxValue );
/* @[declare_platform_threads_semaphorecreate] */
/**
* @brief Free resources used by a semaphore.
*
* This function frees resources used by a semaphore. It must be called on an initialized
* #IotSemaphore_t. No other semaphore functions should be called on `pSemaphore` after
* calling this function (unless the semaphore is re-created).
*
* @param[in] pSemaphore The semaphore to destroy.
*
* @warning This function must not be called on a semaphore with waiting threads.
* @see @ref platform_threads_function_semaphorecreate
*/
/* @[declare_platform_threads_semaphoredestroy] */
void IotSemaphore_Destroy( IotSemaphore_t * pSemaphore );
/* @[declare_platform_threads_semaphoredestroy] */
/**
* @brief Query the current count of the semaphore.
*
* This function queries a counting semaphore for its current value. A counting
* semaphore's value is always 0 or positive.
*
* @param[in] pSemaphore The semaphore to query.
*
* @return The current count of the semaphore. This function should not fail.
*/
/* @[declare_platform_threads_semaphoregetcount] */
uint32_t IotSemaphore_GetCount( IotSemaphore_t * pSemaphore );
/* @[declare_platform_threads_semaphoregetcount] */
/**
* @brief Wait on (lock) a semaphore. This function should only return when the
* semaphore wait succeeds; it is not expected to fail.
*
* This function blocks and waits until a counting semaphore is positive. It
* waits forever (deadlocks) if `pSemaphore` has a count `0` that is never
* [incremented](@ref platform_threads_function_semaphorepost).
*
* @param[in] pSemaphore The semaphore to lock.
*
* @see @ref platform_threads_function_semaphoretrywait for a nonblocking wait;
* @ref platform_threads_function_semaphoretimedwait for a wait with timeout.
*/
/* @[declare_platform_threads_semaphorewait] */
void IotSemaphore_Wait( IotSemaphore_t * pSemaphore );
/* @[declare_platform_threads_semaphorewait] */
/**
* @brief Attempt to wait on (lock) a semaphore. Return immediately if the semaphore
* is not available.
*
* If the count of `pSemaphore` is positive, this function immediately decrements
* the semaphore and returns. Otherwise, this function returns without decrementing
* `pSemaphore`.
*
* @param[in] pSemaphore The semaphore to lock.
*
* @return `true` if the semaphore wait succeeded; `false` if the semaphore has
* a count of `0`.
*
* @see @ref platform_threads_function_semaphorewait for a blocking wait;
* @ref platform_threads_function_semaphoretimedwait for a wait with timeout.
*/
/* @[declare_platform_threads_semaphoretrywait] */
bool IotSemaphore_TryWait( IotSemaphore_t * pSemaphore );
/* @[declare_platform_threads_semaphoretrywait] */
/**
* @brief Attempt to wait on (lock) a semaphore with a timeout.
*
* This function blocks and waits until a counting semaphore is positive
* <i>or</i> its timeout expires (whichever is sooner). It decrements
* `pSemaphore` and returns `true` if the semaphore is positive at some
* time during the wait. If `pSemaphore` is always `0` during the wait,
* this function returns `false`.
*
* @param[in] pSemaphore The semaphore to lock.
* @param[in] timeoutMs Relative timeout of semaphore lock. This function returns
* false if the semaphore couldn't be locked within this timeout.
*
* @return `true` if the semaphore wait succeeded; `false` if it timed out.
*
* @see @ref platform_threads_function_semaphoretrywait for a nonblocking wait;
* @ref platform_threads_function_semaphorewait for a blocking wait.
*/
/* @[declare_platform_threads_semaphoretimedwait] */
bool IotSemaphore_TimedWait( IotSemaphore_t * pSemaphore,
uint32_t timeoutMs );
/* @[declare_platform_threads_semaphoretimedwait] */
/**
* @brief Post to (unlock) a semaphore. This function should only return when the
* semaphore post succeeds; it is not expected to fail.
*
* This function increments the count of a semaphore. Any thread may call this
* function to increment a semaphore's count.
*
* @param[in] pSemaphore The semaphore to unlock.
*/
/* @[declare_platform_threads_semaphorepost] */
void IotSemaphore_Post( IotSemaphore_t * pSemaphore );
/* @[declare_platform_threads_semaphorepost] */
#endif /* ifndef IOT_THREADS_H_ */

View file

@ -0,0 +1,158 @@
/*
* Amazon FreeRTOS Platform V1.0.0
* Copyright (C) 2019 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_platform_types.h
* @brief Types of the platform layer.
*/
#ifndef IOT_PLATFORM_TYPES_H_
#define IOT_PLATFORM_TYPES_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Linear containers (lists and queues) include for metrics types. */
#include "iot_linear_containers.h"
/*------------------------- Thread management types -------------------------*/
/**
* @brief A value representing the system default for new thread priority.
*/
#ifndef IOT_THREAD_DEFAULT_PRIORITY
#define IOT_THREAD_DEFAULT_PRIORITY 0
#endif
/**
* @brief A value representhing the system default for new thread stack size.
*/
#ifndef IOT_THREAD_DEFAULT_STACK_SIZE
#define IOT_THREAD_DEFAULT_STACK_SIZE 0
#endif
/**
* @ingroup platform_datatypes_handles
* @brief The type used to represent mutexes, configured with the type
* `_IotSystemMutex_t`.
*
* <span style="color:red;font-weight:bold">
* `_IotSystemMutex_t` will be automatically configured during build and generally
* does not need to be defined.
* </span>
*
* Mutexes should only be released by the threads that take them.
*
* <b>Example</b> <br>
* To change the type of #IotMutex_t to `long`:
* @code{c}
* typedef long _IotSystemMutex_t;
* #include "iot_threads.h"
* @endcode
*/
typedef _IotSystemMutex_t IotMutex_t;
/**
* @ingroup platform_datatypes_handles
* @brief The type used to represent semaphores, configured with the type
* `_IotSystemSemaphore_t`.
*
* <span style="color:red;font-weight:bold">
* `_IotSystemSemaphore_t` will be automatically configured during build and
* generally does not need to be defined.
* </span>
*
* Semaphores must be counting, and any thread may take (wait on) or release
* (post to) a semaphore.
*
* <b>Example</b> <br>
* To change the type of #IotSemaphore_t to `long`:
* @code{c}
* typedef long _IotSystemSemaphore_t;
* #include "iot_threads.h"
* @endcode
*/
typedef _IotSystemSemaphore_t IotSemaphore_t;
/**
* @brief Thread routine function.
*
* @param[in] void * The argument passed to the @ref
* platform_threads_function_createdetachedthread. For application use.
*/
typedef void ( * IotThreadRoutine_t )( void * );
/*-------------------------- Clock and timer types --------------------------*/
/**
* @ingroup platform_datatypes_handles
* @brief The type used to represent timers, configured with the type
* `_IotSystemTimer_t`.
*
* <span style="color:red;font-weight:bold">
* `_IotSystemTimer_t` will be automatically configured during build and generally
* does not need to be defined.
* </span>
*
* <b>Example</b> <br>
* To change the type of #IotTimer_t to `long`:
* @code{c}
* typedef long _IotSystemTimer_t;
* #include "iot_clock.h"
* @endcode
*/
typedef _IotSystemTimer_t IotTimer_t;
/*------------------------------ Metrics types ------------------------------*/
/**
* @brief The length of the buffer used to store IP addresses for metrics.
*
* This is the length of the longest IPv6 address plus space for the port number
* and NULL terminator.
*/
#define IOT_METRICS_IP_ADDRESS_LENGTH 54
/**
* @brief Represents a TCP connection to a remote IPv4 server.
*
* A list of these is provided by @ref platform_metrics_function_gettcpconnections.
*/
typedef struct IotMetricsTcpConnection
{
IotLink_t link; /**< @brief List link member. */
void * pNetworkContext; /**< @brief Context that may be used by metrics or Defender. */
size_t addressLength; /**< @brief The length of the address stored in #IotMetricsTcpConnection_t.pRemoteAddress. */
/**
* @brief NULL-terminated IP address and port in text format.
*
* IPv4 addresses will be in the format `xxx.xxx.xxx.xxx:port`.
* IPv6 addresses will be in the format `[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx]:port`.
*/
char pRemoteAddress[ IOT_METRICS_IP_ADDRESS_LENGTH ];
} IotMetricsTcpConnection_t;
#endif /* ifndef IOT_PLATFORM_TYPES_H_ */

View file

@ -0,0 +1,342 @@
/*
* Amazon FreeRTOS Secure Sockets V1.1.5
* 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
*/
/* Define _SECURE_SOCKETS_WRAPPER_NOT_REDEFINE to prevent secure sockets functions
* from redefining in iot_secure_sockets_wrapper_metrics.h */
#define _SECURE_SOCKETS_WRAPPER_NOT_REDEFINE
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "FreeRTOSIPConfig.h"
#include "list.h"
#include "semphr.h"
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "iot_secure_sockets.h"
#include "task.h"
#undef _SECURE_SOCKETS_WRAPPER_NOT_REDEFINE
/* Internal context structure. */
typedef struct SSOCKETContext
{
Socket_t xSocket;
char * pcDestination;
BaseType_t xSendFlags;
BaseType_t xRecvFlags;
BaseType_t xConnectAttempted;
} SSOCKETContext_t, * SSOCKETContextPtr_t;
/*
* Helper routines.
*/
/*
* @brief Network send callback.
*/
static BaseType_t prvNetworkSend( void * pvContext,
const unsigned char * pucData,
size_t xDataLength )
{
SSOCKETContextPtr_t pxContext = ( SSOCKETContextPtr_t ) pvContext; /*lint !e9087 cast used for portability. */
return FreeRTOS_send( pxContext->xSocket, pucData, xDataLength, pxContext->xSendFlags );
}
/*-----------------------------------------------------------*/
/*
* @brief Network receive callback.
*/
static BaseType_t prvNetworkRecv( void * pvContext,
unsigned char * pucReceiveBuffer,
size_t xReceiveLength )
{
SSOCKETContextPtr_t pxContext = ( SSOCKETContextPtr_t ) pvContext; /*lint !e9087 cast used for portability. */
return FreeRTOS_recv( pxContext->xSocket, pucReceiveBuffer, xReceiveLength, pxContext->xRecvFlags );
}
/*-----------------------------------------------------------*/
/*
* Interface routines.
*/
int32_t SOCKETS_Close( Socket_t xSocket )
{
SSOCKETContextPtr_t pxContext = ( SSOCKETContextPtr_t ) xSocket; /*lint !e9087 cast used for portability. */
int32_t lReturn;
if( ( xSocket != SOCKETS_INVALID_SOCKET ) && ( NULL != pxContext ) )
{
/* Clean-up destination string. */
if( NULL != pxContext->pcDestination )
{
vPortFree( pxContext->pcDestination );
}
/* Close the underlying socket handle. */
( void ) FreeRTOS_closesocket( pxContext->xSocket );
/* Free the context. */
vPortFree( pxContext );
lReturn = SOCKETS_ERROR_NONE;
}
else
{
lReturn = SOCKETS_EINVAL;
}
return lReturn;
}
/*-----------------------------------------------------------*/
int32_t SOCKETS_Connect( Socket_t xSocket,
SocketsSockaddr_t * pxAddress,
Socklen_t xAddressLength )
{
int32_t lStatus = SOCKETS_ERROR_NONE;
SSOCKETContextPtr_t pxContext = ( SSOCKETContextPtr_t ) xSocket; /*lint !e9087 cast used for portability. */
struct freertos_sockaddr xTempAddress = { 0 };
if( ( pxContext != SOCKETS_INVALID_SOCKET ) && ( pxAddress != NULL ) )
{
/* A connection was attempted. If this function fails, then the socket is invalid and the user
* must call SOCKETS_Close(), on this socket, and SOCKETS_Socket() to get a new socket. */
pxContext->xConnectAttempted = pdTRUE;
/* Connect the wrapped socket. */
xTempAddress.sin_addr = pxAddress->ulAddress;
xTempAddress.sin_family = pxAddress->ucSocketDomain;
xTempAddress.sin_len = ( uint8_t ) sizeof( xTempAddress );
xTempAddress.sin_port = pxAddress->usPort;
lStatus = FreeRTOS_connect( pxContext->xSocket, &xTempAddress, xAddressLength );
}
else
{
lStatus = SOCKETS_SOCKET_ERROR;
}
return lStatus;
}
/*-----------------------------------------------------------*/
uint32_t SOCKETS_GetHostByName( const char * pcHostName )
{
return FreeRTOS_gethostbyname( pcHostName );
}
/*-----------------------------------------------------------*/
int32_t SOCKETS_Recv( Socket_t xSocket,
void * pvBuffer,
size_t xBufferLength,
uint32_t ulFlags )
{
int32_t lStatus = SOCKETS_SOCKET_ERROR;
SSOCKETContextPtr_t pxContext = ( SSOCKETContextPtr_t ) xSocket; /*lint !e9087 cast used for portability. */
if( ( xSocket != SOCKETS_INVALID_SOCKET ) &&
( pvBuffer != NULL ) )
{
pxContext->xRecvFlags = ( BaseType_t ) ulFlags;
/* Receive unencrypted. */
lStatus = prvNetworkRecv( pxContext, pvBuffer, xBufferLength );
}
else
{
lStatus = SOCKETS_EINVAL;
}
return lStatus;
}
/*-----------------------------------------------------------*/
int32_t SOCKETS_Send( Socket_t xSocket,
const void * pvBuffer,
size_t xDataLength,
uint32_t ulFlags )
{
int32_t lStatus = SOCKETS_SOCKET_ERROR;
SSOCKETContextPtr_t pxContext = ( SSOCKETContextPtr_t ) xSocket; /*lint !e9087 cast used for portability. */
if( ( xSocket != SOCKETS_INVALID_SOCKET ) &&
( pvBuffer != NULL ) )
{
pxContext->xSendFlags = ( BaseType_t ) ulFlags;
/* Send unencrypted. */
lStatus = prvNetworkSend( pxContext, pvBuffer, xDataLength );
}
else
{
lStatus = SOCKETS_EINVAL;
}
return lStatus;
}
/*-----------------------------------------------------------*/
int32_t SOCKETS_SetSockOpt( Socket_t xSocket,
int32_t lLevel,
int32_t lOptionName,
const void * pvOptionValue,
size_t xOptionLength )
{
int32_t lStatus = SOCKETS_ERROR_NONE;
TickType_t xTimeout;
SSOCKETContextPtr_t pxContext = ( SSOCKETContextPtr_t ) xSocket; /*lint !e9087 cast used for portability. */
if( ( xSocket != SOCKETS_INVALID_SOCKET ) && ( xSocket != NULL ) )
{
switch( lOptionName )
{
case SOCKETS_SO_NONBLOCK:
xTimeout = 0;
/* Non-blocking connect is not supported. Socket may be set to nonblocking
* only after a connection is made. */
if( pdTRUE == pxContext->xConnectAttempted )
{
lStatus = FreeRTOS_setsockopt( pxContext->xSocket,
lLevel,
SOCKETS_SO_RCVTIMEO,
&xTimeout,
sizeof( xTimeout ) );
if( lStatus == SOCKETS_ERROR_NONE )
{
lStatus = FreeRTOS_setsockopt( pxContext->xSocket,
lLevel,
SOCKETS_SO_SNDTIMEO,
&xTimeout,
sizeof( xTimeout ) );
}
}
else
{
lStatus = SOCKETS_EISCONN;
}
break;
case SOCKETS_SO_RCVTIMEO:
case SOCKETS_SO_SNDTIMEO:
/* Comply with Berkeley standard - a 0 timeout is wait forever. */
xTimeout = *( ( const TickType_t * ) pvOptionValue ); /*lint !e9087 pvOptionValue passed should be of TickType_t */
if( xTimeout == 0U )
{
xTimeout = portMAX_DELAY;
}
lStatus = FreeRTOS_setsockopt( pxContext->xSocket,
lLevel,
lOptionName,
&xTimeout,
xOptionLength );
break;
default:
lStatus = FreeRTOS_setsockopt( pxContext->xSocket,
lLevel,
lOptionName,
pvOptionValue,
xOptionLength );
break;
}
}
else
{
lStatus = SOCKETS_EINVAL;
}
return lStatus;
}
/*-----------------------------------------------------------*/
int32_t SOCKETS_Shutdown( Socket_t xSocket,
uint32_t ulHow )
{
int32_t lReturn;
SSOCKETContextPtr_t pxContext = ( SSOCKETContextPtr_t ) xSocket; /*lint !e9087 cast used for portability. */
if( ( xSocket != SOCKETS_INVALID_SOCKET ) && ( xSocket != NULL ) )
{
lReturn = FreeRTOS_shutdown( pxContext->xSocket, ( BaseType_t ) ulHow );
}
else
{
lReturn = SOCKETS_EINVAL;
}
return lReturn;
}
/*-----------------------------------------------------------*/
Socket_t SOCKETS_Socket( int32_t lDomain,
int32_t lType,
int32_t lProtocol )
{
SSOCKETContextPtr_t pxContext = NULL;
Socket_t xSocket;
/* Ensure that only supported values are supplied. */
configASSERT( lDomain == SOCKETS_AF_INET );
configASSERT( lType == SOCKETS_SOCK_STREAM );
configASSERT( lProtocol == SOCKETS_IPPROTO_TCP );
/* Create the wrapped socket. */
xSocket = FreeRTOS_socket( lDomain, lType, lProtocol );
if( xSocket != FREERTOS_INVALID_SOCKET )
{
/* Allocate the internal context structure. */
if( NULL == ( pxContext = pvPortMalloc( sizeof( SSOCKETContext_t ) ) ) )
{
/* Need to close socket. */
( void ) FreeRTOS_closesocket( xSocket );
pxContext = SOCKETS_INVALID_SOCKET;
}
else
{
memset( pxContext, 0, sizeof( SSOCKETContext_t ) );
pxContext->xSocket = xSocket;
}
}
else
{
pxContext = SOCKETS_INVALID_SOCKET;
}
return pxContext;
}
/*-----------------------------------------------------------*/
BaseType_t SOCKETS_Init( void )
{
/* Empty initialization for this port. */
return pdPASS;
}
/*-----------------------------------------------------------*/

View file

@ -0,0 +1,609 @@
/*
* Amazon FreeRTOS Secure Sockets V1.1.5
* 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_secure_sockets.h
* @brief Secure Sockets Interface.
*
* Secure sockets is a portable layer for establishing a TCP/IP
* connection, with the option of using TLS.
*
* Secure sockets is based on the Berkeley sockets API.
* A few difference general differences between Berkeley and SOCKETS are:
* - SOCKETS has additional socket options to enable TLS, server name
* indication, and per-socket root of trust server certificates. See
* SOCKETS_SetSockOpt() for more information.
* - SOCKETS API return an error code, rather than returning -1 and setting
* a global errno value.
*
*/
#ifndef _AWS_SECURE_SOCKETS_H_
#define _AWS_SECURE_SOCKETS_H_
/*
#ifdef __cplusplus
* extern "C" {
#endif
*/
#include <stdint.h>
#include <stddef.h>
#include "iot_secure_sockets_config.h"
#include "iot_secure_sockets_config_defaults.h"
#include "iot_secure_sockets_wrapper_metrics.h"
#include "iot_lib_init.h"
/**
* @ingroup SecureSockets_datatypes_handles
* @brief The socket handle data type.
*
* For detail of socket, refer to [Network Sockets]
* (https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/socket.html)
*
* Data contained by the Socket_t type is port specific.
*/
typedef void * Socket_t;
/**
* @brief The "size_t" of secure sockets.
*
* This type is used for compatibility with the expected Berkeley sockets
* naming.
*/
#define Socklen_t uint32_t
/**
* @anchor SocketsErrors
* @name SocketsErrors
* @brief Error codes returned by the SOCKETS API.
*
* Note that SOCKETS API may also propagate port-specific
* error codes when they are more descriptive. See your
* port's error codes for more details.
* PORT_SPECIFIC_LINK
*/
/**@{ */
#define SOCKETS_ERROR_NONE ( 0 ) /*!< No error. */
#define SOCKETS_SOCKET_ERROR ( -1 ) /*!< Catch-all sockets error code. */
#define SOCKETS_EWOULDBLOCK ( -11 ) /*!< A resource is temporarily unavailable. */
#define SOCKETS_ENOMEM ( -12 ) /*!< Memory allocation failed. */
#define SOCKETS_EINVAL ( -22 ) /*!< Invalid argument. */
#define SOCKETS_ENOPROTOOPT ( -109 ) /*!< A bad option was specified . */
#define SOCKETS_ENOTCONN ( -126 ) /*!< The supplied socket is not connected. */
#define SOCKETS_EISCONN ( -127 ) /*!< The supplied socket is already connected. */
#define SOCKETS_ECLOSED ( -128 ) /*!< The supplied socket has already been closed. */
#define SOCKETS_TLS_INIT_ERROR ( -1001 ) /*!< TLS initialization failed. */
#define SOCKETS_TLS_HANDSHAKE_ERROR ( -1002 ) /*!< TLS handshake failed. */
#define SOCKETS_TLS_SERVER_UNVERIFIED ( -1003 ) /*!< A connection was made but the server could not be verified. It is recommended that the socket be closed. */
#define SOCKETS_TLS_RECV_ERROR ( -1004 ) /*!< TLS receive operation failed. */
#define SOCKETS_TLS_SEND_ERROR ( -1005 ) /*!< TLS send operation failed. */
#define SOCKETS_PERIPHERAL_RESET ( -1006 ) /*!< Communications peripheral has been reset. */
/**@} */
/**
* @brief Assigned to an Socket_t variable when the socket is not valid.
*/
#define SOCKETS_INVALID_SOCKET ( ( Socket_t ) ~0U )
/**
* @anchor SocketDomains
* @name SocketDomains
*
* @brief Options for the lDomain parameter of SOCKETS_Socket()
* function.
*
* These select the protocol family to be used for communication.
*/
/**@{ */
#define SOCKETS_AF_INET ( 2 ) /*!< IPv4 Internet Protocols. */
#define SOCKETS_PF_INET SOCKETS_AF_INET /*!< IPv4 Internet Protocol. */
#define SOCKETS_AF_INET6 ( 10 ) /*!< IPv6 Internet Protocols. This option is currently not supported. */
/**@} */
/**
* @anchor SocketTypes
* @name SocketTypes
*
* @brief Options for the lType parameter of SOCKETS_Socket()
* function.
*
* These specify the communication semantics.
*/
/**@{ */
#define SOCKETS_SOCK_DGRAM ( 2 ) /*!< Datagram. */
#define SOCKETS_SOCK_STREAM ( 1 ) /*!< Byte-stream. */
/**@} */
/**
* @anchor Protocols
* @name Protocols
*
* @brief Options for the lProtocol parameter of SOCKETS_Socket() function.
*
*/
/**@{ */
#define SOCKETS_IPPROTO_UDP ( 17 ) /*!< UDP. This option is currently not supported. */
#define SOCKETS_IPPROTO_TCP ( 6 ) /*!< TCP. */
/**@} */
/**
* @anchor SetSockOptOptions
* @name SetSockOptOptions
*
* @brief Options for lOptionName in SOCKETS_SetSockOpt().
*
*/
/**@{ */
#define SOCKETS_SO_RCVTIMEO ( 0 ) /**< Set the receive timeout. */
#define SOCKETS_SO_SNDTIMEO ( 1 ) /**< Set the send timeout. */
#define SOCKETS_SO_SNDBUF ( 4 ) /**< Set the size of the send buffer (TCP only). */
#define SOCKETS_SO_RCVBUF ( 5 ) /**< Set the size of the receive buffer (TCP only). */
#define SOCKETS_SO_SERVER_NAME_INDICATION ( 6 ) /**< Toggle client use of TLS SNI. */
#define SOCKETS_SO_TRUSTED_SERVER_CERTIFICATE ( 7 ) /**< Override default TLS server certificate trust. Must be PEM encoded and length must include null terminator. */
#define SOCKETS_SO_REQUIRE_TLS ( 8 ) /**< Toggle client enforcement of TLS. */
#define SOCKETS_SO_NONBLOCK ( 9 ) /**< Socket is nonblocking. */
#define SOCKETS_SO_ALPN_PROTOCOLS ( 10 ) /**< Application protocol list to be included in TLS ClientHello. */
#define SOCKETS_SO_WAKEUP_CALLBACK ( 17 ) /**< Set the callback to be called whenever there is data available on the socket for reading. */
/**@} */
/**
* @anchor ShutdownFlags <br>
* @name ShutdownFlags
*
* @brief Options for the ulHow parameter in SOCKETS_Shutdown().
*/
/**@{ */
#define SOCKETS_SHUT_RD ( 0 ) /**< No further receives. */
#define SOCKETS_SHUT_WR ( 1 ) /**< No further sends. */
#define SOCKETS_SHUT_RDWR ( 2 ) /**< No further send or receive. */
/**@} */
/**
* @brief Maximum length of an ASCII DNS name.
*/
#define securesocketsMAX_DNS_NAME_LENGTH ( 253 )
/**
* @ingroup SecureSockets_datatypes_paramstructs
* @brief Socket address.
*
* \sa PORT_SPECIFIC_LINK
*/
typedef struct SocketsSockaddr
{
uint8_t ucLength; /**< Length of SocketsSockaddr structure. */
uint8_t ucSocketDomain; /**< Only SOCKETS_AF_INET is supported. */
uint16_t usPort; /**< Port number. Convention is to call this sin_port. */
uint32_t ulAddress; /**< IP Address. Convention is to call this sin_addr. */
} SocketsSockaddr_t;
/**
* @brief Well-known port numbers.
*/
#define securesocketsDEFAULT_TLS_DESTINATION_PORT 443
/**
* @brief Secure Sockets library initialization 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( SOCKETS_Init );
/**
* @brief Creates a TCP socket.
*
* See the [FreeRTOS+TCP networking tutorial]
* (https://freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_Networking_Tutorial.html)
* for more information on TCP sockets.
*
* See the [Berkeley Sockets API]
* (https://en.wikipedia.org/wiki/Berkeley_sockets#Socket_API_functions)
* in wikipedia
*
* @sa SOCKETS_Close()
*
* @param[in] lDomain Must be set to SOCKETS_AF_INET. See @ref SocketDomains.
* @param[in] lType Set to SOCKETS_SOCK_STREAM to create a TCP socket.
* No other value is valid. See @ref SocketTypes.
* @param[in] lProtocol Set to SOCKETS_IPPROTO_TCP to create a TCP socket.
* No other value is valid. See @ref Protocols.
*
* @return
* * If a socket is created successfully, then the socket handle is
* returned
* * @ref SOCKETS_INVALID_SOCKET is returned if an error occurred.
*/
/*
* This call allocates memory and claims a socket resource.
*/
/* @[declare_secure_sockets_socket] */
Socket_t SOCKETS_Socket( int32_t lDomain,
int32_t lType,
int32_t lProtocol );
/* @[declare_secure_sockets_socket] */
/**
* @brief Connects the socket to the specified IP address and port.
*
* The socket must first have been successfully created by a call to SOCKETS_Socket().
*
* \note To create a secure socket, SOCKETS_SetSockOpt() should be called with the
* SOCKETS_SO_REQUIRE_TLS option \a before SOCKETS_Connect() is called.
*
* If this function returns an error the socket is considered invalid.
*
* \warning SOCKETS_Connect() is not safe to be called on the same socket
* from multiple threads simultaneously with SOCKETS_Connect(),
* SOCKETS_SetSockOpt(), SOCKETS_Shutdown(), SOCKETS_Close().
*
* See the [Berkeley Sockets API]
* (https://en.wikipedia.org/wiki/Berkeley_sockets#Socket_API_functions)
* in wikipedia
*
* @param[in] xSocket The handle of the socket to be connected.
* @param[in] pxAddress A pointer to a SocketsSockaddr_t structure that contains the
* the address to connect the socket to.
* @param[in] xAddressLength Should be set to sizeof( @ref SocketsSockaddr_t ).
*
* @return
* * @ref SOCKETS_ERROR_NONE if a connection is established.
* * If an error occurred, a negative value is returned. @ref SocketsErrors
*/
/* @[declare_secure_sockets_connect] */
int32_t SOCKETS_Connect( Socket_t xSocket,
SocketsSockaddr_t * pxAddress,
Socklen_t xAddressLength );
/* @[declare_secure_sockets_connect] */
/**
* @brief Receive data from a TCP socket.
*
* The socket must have already been created using a call to SOCKETS_Socket()
* and connected to a remote socket using SOCKETS_Connect().
*
* See the [Berkeley Sockets API]
* (https://en.wikipedia.org/wiki/Berkeley_sockets#Socket_API_functions)
* in wikipedia
*
* @param[in] xSocket The handle of the socket from which data is being received.
* @param[out] pvBuffer The buffer into which the received data will be placed.
* @param[in] xBufferLength The maximum number of bytes which can be received.
* pvBuffer must be at least xBufferLength bytes long.
* @param[in] ulFlags Not currently used. Should be set to 0.
*
* @return
* * If the receive was successful then the number of bytes received (placed in the
* buffer pointed to by pvBuffer) is returned.
* * If a timeout occurred before data could be received then 0 is returned (timeout
* is set using @ref SOCKETS_SO_RCVTIMEO).
* * If an error occurred, a negative value is returned. @ref SocketsErrors
*/
/* @[declare_secure_sockets_recv] */
int32_t SOCKETS_Recv( Socket_t xSocket,
void * pvBuffer,
size_t xBufferLength,
uint32_t ulFlags );
/* @[declare_secure_sockets_recv] */
/**
* @brief Transmit data to the remote socket.
*
* The socket must have already been created using a call to SOCKETS_Socket() and
* connected to a remote socket using SOCKETS_Connect().
*
* See the [Berkeley Sockets API]
* (https://en.wikipedia.org/wiki/Berkeley_sockets#Socket_API_functions)
* in wikipedia
*
* @param[in] xSocket The handle of the sending socket.
* @param[in] pvBuffer The buffer containing the data to be sent.
* @param[in] xDataLength The length of the data to be sent.
* @param[in] ulFlags Not currently used. Should be set to 0.
*
* @return
* * On success, the number of bytes actually sent is returned.
* * If an error occurred, a negative value is returned. @ref SocketsErrors
*/
/* @[declare_secure_sockets_send] */
int32_t SOCKETS_Send( Socket_t xSocket,
const void * pvBuffer,
size_t xDataLength,
uint32_t ulFlags );
/* @[declare_secure_sockets_send] */
/**
* @brief Closes all or part of a full-duplex connection on the socket.
*
* Disable reads and writes on a connected TCP socket. A connected TCP socket must be gracefully
* shut down before it can be closed.
*
* See the [Berkeley Sockets API]
* (https://en.wikipedia.org/wiki/Berkeley_sockets#Socket_API_functions)
* in wikipedia
*
* \warning SOCKETS_Shutdown() is not safe to be called on the same socket
* from multiple threads simultaneously with SOCKETS_Connect(),
* SOCKETS_SetSockOpt(), SOCKETS_Shutdown(), SOCKETS_Close().
*
* @param[in] xSocket The handle of the socket to shutdown.
* @param[in] ulHow SOCKETS_SHUT_RD, SOCKETS_SHUT_WR or SOCKETS_SHUT_RDWR.
* @ref ShutdownFlags
*
* @return
* * If the operation was successful, 0 is returned.
* * If an error occurred, a negative value is returned. @ref SocketsErrors
*/
/* @[declare_secure_sockets_shutdown] */
int32_t SOCKETS_Shutdown( Socket_t xSocket,
uint32_t ulHow );
/* @[declare_secure_sockets_shutdown] */
/**
* @brief Closes the socket and frees the related resources.
*
* A socket should be shutdown gracefully before it is closed, and cannot be used after it has been closed.
*
* See the [Berkeley Sockets API]
* (https://en.wikipedia.org/wiki/Berkeley_sockets#Socket_API_functions)
* in wikipedia
*
* \warning SOCKETS_Close() is not safe to be called on the same socket
* from multiple threads simultaneously with SOCKETS_Connect(),
* SOCKETS_SetSockOpt(), SOCKETS_Shutdown(), SOCKETS_Close().
*
* @param[in] xSocket The handle of the socket to close.
*
* @return
* * On success, 0 is returned.
* * If an error occurred, a negative value is returned. @ref SocketsErrors
*/
/* @[declare_secure_sockets_close] */
int32_t SOCKETS_Close( Socket_t xSocket );
/* @[declare_secure_sockets_close] */
/**
* @brief AWS IoT ALPN protocol name for MQTT over TLS on server port 443.
*/
#define socketsAWS_IOT_ALPN_MQTT "x-amzn-mqtt-ca"
/**
* @brief Manipulates the options for the socket.
*
* See the [Berkeley Sockets API]
* (https://en.wikipedia.org/wiki/Berkeley_sockets#Socket_API_functions)
* in wikipedia
*
* @param[in] xSocket The handle of the socket to set the option for.
* @param[in] lLevel Not currently used. Should be set to 0.
* @param[in] lOptionName See @ref SetSockOptOptions.
* @param[in] pvOptionValue A buffer containing the value of the option to set.
* @param[in] xOptionLength The length of the buffer pointed to by pvOptionValue.
*
* \warning SOCKETS_Close() is not safe to be called on the same socket
* from multiple threads simultaneously with SOCKETS_Connect(),
* SOCKETS_SetSockOpt(), SOCKETS_Shutdown(), SOCKETS_Close().
*
* @note Socket option support and possible values vary by port. Please see
* PORT_SPECIFIC_LINK to check the valid options and limitations of your device.
*
* - Berkeley Socket Options
* - @ref SOCKETS_SO_RCVTIMEO
* - Sets the receive timeout
* - pvOptionValue (TickType_t) is the number of milliseconds that the
* receive function should wait before timing out.
* - Setting pvOptionValue = 0 causes receive to wait forever.
* - See PORT_SPECIFIC_LINK for device limitations.
* - @ref SOCKETS_SO_SNDTIMEO
* - Sets the send timeout
* - pvOptionValue (TickType_t) is the number of milliseconds that the
* send function should wait before timing out.
* - Setting pvOptionValue = 0 causes send to wait forever.
* - See PORT_SPECIFIC_LINK for device limitations.
* - Non-Standard Options
* - @ref SOCKETS_SO_NONBLOCK
* - Makes a socket non-blocking.
* - Non-blocking connect is not supported - socket option should be
* called after connect.
* - pvOptionValue is ignored for this option.
* - @ref SOCKETS_SO_WAKEUP_CALLBACK
* - Set the callback to be called whenever there is data available on
* the socket for reading
* - This option provides an asynchronous way to handle received data
* - pvOptionValue is a pointer to the callback function
* - See PORT_SPECIFIC_LINK for device limitations.
* - Security Sockets Options
* - @ref SOCKETS_SO_REQUIRE_TLS
* - Use TLS for all connect, send, and receive on this socket.
* - This socket options MUST be set for TLS to be used, even
* if other secure socket options are set.
* - This socket option should be set before SOCKETS_Connect() is
* called.
* - pvOptionValue is ignored for this option.
* - @ref SOCKETS_SO_TRUSTED_SERVER_CERTIFICATE
* - Set the root of trust server certificate for the socket.
* - This socket option only takes effect if @ref SOCKETS_SO_REQUIRE_TLS
* is also set. If @ref SOCKETS_SO_REQUIRE_TLS is not set,
* this option will be ignored.
* - pvOptionValue is a pointer to the formatted server certificate.
* TODO: Link to description of how to format certificates with \n
* - xOptionLength (BaseType_t) is the length of the certificate
* in bytes.
* - @ref SOCKETS_SO_SERVER_NAME_INDICATION
* - Use Server Name Indication (SNI)
* - This socket option only takes effect if @ref SOCKETS_SO_REQUIRE_TLS
* is also set. If @ref SOCKETS_SO_REQUIRE_TLS is not set,
* this option will be ignored.
* - pvOptionValue is a pointer to a string containing the hostname
* - xOptionLength is the length of the hostname string in bytes.
* - @ref SOCKETS_SO_ALPN_PROTOCOLS
* - Negotiate an application protocol along with TLS.
* - The ALPN list is expressed as an array of NULL-terminated ANSI
* strings.
* - xOptionLength is the number of items in the array.
*
* @return
* * On success, 0 is returned.
* * If an error occurred, a negative value is returned. @ref SocketsErrors
*/
/* @[declare_secure_sockets_setsockopt] */
int32_t SOCKETS_SetSockOpt( Socket_t xSocket,
int32_t lLevel,
int32_t lOptionName,
const void * pvOptionValue,
size_t xOptionLength );
/* @[declare_secure_sockets_setsockopt] */
/**
* @brief Resolve a host name using Domain Name Service.
*
* See the [Berkeley Sockets API]
* (https://en.wikipedia.org/wiki/Berkeley_sockets#Socket_API_functions)
* in wikipedia
*
* @param[in] pcHostName The host name to resolve.
* @return
* * The IPv4 address of the specified host.
* * If an error has occurred, 0 is returned.
*/
/* @[declare_secure_sockets_gethostbyname] */
uint32_t SOCKETS_GetHostByName( const char * pcHostName );
/* @[declare_secure_sockets_gethostbyname] */
/**
* @brief Convert an unsigned thirty-two-bit value from host endianness to network
* endianness.
*
* @param[in] usIn The unsigned thirty-two-bit value to convert.
*/
#if defined( socketsconfigBYTE_ORDER ) && ( socketsconfigBYTE_ORDER == pdLITTLE_ENDIAN )
#define SOCKETS_htonl( ulIn ) ( ( uint32_t ) ( ( ( ulIn & 0xFF ) << 24 ) | ( ( ulIn & 0xFF00 ) << 8 ) | ( ( ulIn & 0xFF0000 ) >> 8 ) | ( ( ulIn & 0xFF000000 ) >> 24 ) ) )
#else
#define SOCKETS_htonl( usIn ) ( ( uint32_t ) ( usIn ) )
#endif
/**
* @brief Convert an unsigned thirty-two-bit value from network endianness to host
* endianness.
*
* @param[in] usIn The unsigned thirty-two-bit value to convert.
*/
#define SOCKETS_ntohl( usIn ) SOCKETS_htonl( usIn )
/**
* @brief Convert an unsigned sixteen-bit value from host endianness to network
* endianness.
*
* @param[in] usIn The unsigned sixteen-bit value to convert.
*/
#if defined( socketsconfigBYTE_ORDER ) && ( socketsconfigBYTE_ORDER == pdLITTLE_ENDIAN )
#define SOCKETS_htons( usIn ) ( ( uint16_t ) ( ( ( usIn ) << 8U ) | ( ( usIn ) >> 8U ) ) )
#else
#define SOCKETS_htons( usIn ) ( ( uint16_t ) ( usIn ) )
#endif
/**
* @brief Convert an unsigned sixteen-bit value from network endianness to host
* endianness.
*
* @param[in] usIn The unsigned sixteen-bit value to convert.
*/
#define SOCKETS_ntohs( usIn ) SOCKETS_htons( usIn )
/**
* @brief Convert an IP address expressed as four separate numeric octets into a an IP address expressed as a 32-bit number in network byte order
* (for example 192, 168, 0, 100)
*
* @param[in] ucOctet0 0th IP Octet
* @param[in] ucOctet1 1st IP Octet
* @param[in] ucOctet2 2nd IP Octet
* @param[in] ucOctet3 3rd IP Octet
*/
#if defined( socketsconfigBYTE_ORDER ) && ( socketsconfigBYTE_ORDER == pdLITTLE_ENDIAN )
#define SOCKETS_inet_addr_quick( ucOctet0, ucOctet1, ucOctet2, ucOctet3 ) \
( ( ( ( uint32_t ) ( ucOctet3 ) ) << 24UL ) | \
( ( ( uint32_t ) ( ucOctet2 ) ) << 16UL ) | \
( ( ( uint32_t ) ( ucOctet1 ) ) << 8UL ) | \
( ( uint32_t ) ( ucOctet0 ) ) )
/**
* @brief Convert an IP address expressed as a 32-bit number in network byte order to a string in decimal dot notation.
* (for example "192.168.0.100")
*
* @param[in] ulIPAddress An IP address expressed as a 32-bit value in network byte order.
* @param[in] pucBuffer A pointer to a buffer into which the IP address will be written in decimal dot notation.
*/
#define SOCKETS_inet_ntoa( ulIPAddress, pucBuffer ) \
sprintf( ( char * ) ( pucBuffer ), "%u.%u.%u.%u", \
( ( unsigned ) ( ( ulIPAddress ) & 0xffUL ) ), \
( ( unsigned ) ( ( ( ulIPAddress ) >> 8 ) & 0xffUL ) ), \
( ( unsigned ) ( ( ( ulIPAddress ) >> 16 ) & 0xffUL ) ), \
( ( unsigned ) ( ( ulIPAddress ) >> 24 ) ) )
#else /* socketsconfigBYTE_ORDER. */
#define SOCKETS_inet_addr_quick( ucOctet0, ucOctet1, ucOctet2, ucOctet3 ) \
( ( ( ( uint32_t ) ( ucOctet0 ) ) << 24UL ) | \
( ( ( uint32_t ) ( ucOctet1 ) ) << 16UL ) | \
( ( ( uint32_t ) ( ucOctet2 ) ) << 8UL ) | \
( ( uint32_t ) ( ucOctet3 ) ) )
/**
* @brief Convert an IP address expressed as a 32-bit number in network byte order to a string in decimal dot notation.
* (for example "192.168.0.100")
*
* @param[in] ulIPAddress An IP address expressed as a 32-bit value in network byte order.
* @param[in] pucBuffer A pointer to a buffer into which the IP address will be written in decimal dot notation.
*/
#define SOCKETS_inet_ntoa( ulIPAddress, pucBuffer ) \
sprintf( ( char * ) ( pucBuffer ), "%u.%u.%u.%u", \
( ( unsigned ) ( ( ulIPAddress ) >> 24 ) ), \
( ( unsigned ) ( ( ( ulIPAddress ) >> 16 ) & 0xffUL ) ), \
( ( unsigned ) ( ( ( ulIPAddress ) >> 8 ) & 0xffUL ) ), \
( ( unsigned ) ( ( ulIPAddress ) & 0xffUL ) ) )
#endif /* socketsconfigBYTE_ORDER. */
/*
#ifdef __cplusplus
* }
#endif
*/
#endif /* _AWS_SECURE_SOCKETS_H_ */

View file

@ -0,0 +1,72 @@
/*
* Amazon FreeRTOS Secure Sockets V1.1.5
* 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_secure_sockets_config_defaults.h
* @brief Ensures that the required sockets configuration options are supplied
* and the optional ones are set to sane values if the user does not supply.
*/
#ifndef AWS_INC_SECURE_SOCKETS_CONFIG_DEFAULTS_H_
#define AWS_INC_SECURE_SOCKETS_CONFIG_DEFAULTS_H_
/**
* @brief Byte order of the target MCU must be defined.
*
* Valid values are pdLITTLE_ENDIAN and pdBIG_ENDIAN.
*/
#ifndef socketsconfigBYTE_ORDER
#error "socketsconfigBYTE_ORDER must be defined."
#endif
/**
* @brief Default socket send timeout.
*
* The user can change the send timeout for a socket using the SOCKETS_SetSockOpt API
* with the SOCKETS_SO_SNDTIMEO option.
*/
#ifndef socketsconfigDEFAULT_SEND_TIMEOUT
#define socketsconfigDEFAULT_SEND_TIMEOUT ( 10000 )
#endif
/**
* @brief Default socket receive timeout.
*
* The user can change the receive timeout for a socket using the SOCKETS_SetSockOpt API
* with the SOCKETS_SO_RCVTIMEO option.
*/
#ifndef socketsconfigDEFAULT_RECV_TIMEOUT
#define socketsconfigDEFAULT_RECV_TIMEOUT ( 10000 )
#endif
/**
* @brief By default, metrics of secure socket is disabled.
*
*/
#ifndef AWS_IOT_SECURE_SOCKETS_METRICS_ENABLED
#define AWS_IOT_SECURE_SOCKETS_METRICS_ENABLED ( 0 )
#endif
#endif /* AWS_INC_SECURE_SOCKETS_CONFIG_DEFAULTS_H_ */

View file

@ -0,0 +1,43 @@
/*
* Amazon FreeRTOS Secure Sockets V1.1.5
* 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
*/
#ifndef _AWS_SECURE_SOCKETS_WRAPPER_METRICS_
#define _AWS_SECURE_SOCKETS_WRAPPER_METRICS_
/* This file redefines Secure Sockets functions to be called through a wrapper macro,
* but only if metrics is enabled explicitly. */
#if AWS_IOT_SECURE_SOCKETS_METRICS_ENABLED == 1
/* This macro is included in aws_secure_socket.c and aws_secure_socket_wrapper_metrics.c.
* It will prevent the redefine in those source files. */
#ifndef _SECURE_SOCKETS_WRAPPER_NOT_REDEFINE
#define SOCKETS_Init Sockets_MetricsInit
#define SOCKETS_Connect Sockets_MetricsConnect
#define SOCKETS_Shutdown Sockets_MetricsShutdown
#endif
#endif
#endif /* ifndef _AWS_SECURE_SOCKETS_WRAPPER_METRICS_ */

View file

@ -0,0 +1,39 @@
/*
* Amazon FreeRTOS Common V1.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_atomic.h
* @brief Chooses the appropriate atomic operations header.
*
* On FreeRTOS, this file chooses the atomic header provided with the FreeRTOS
* kernel.
*/
#ifndef IOT_ATOMIC_H_
#define IOT_ATOMIC_H_
#include "atomic.h"
#endif /* ifndef IOT_ATOMIC_H_ */

View file

@ -0,0 +1,67 @@
/*
* Amazon FreeRTOS Common V1.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_init.h
* @brief Provides function signatures for common initialization and cleanup of
* this SDK.
*/
#ifndef IOT_INIT_H_
#define IOT_INIT_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdbool.h>
/**
* @brief One-time initialization function for this SDK.
*
* This function initializes common libraries, such as static memory and task
* pool. <b>It must be called once (and only once) before calling any other
* function in this SDK.</b> Calling this function more than once without first
* calling `IotSdk_Cleanup` may result in a crash.
*
* @return `true` if initialization succeeded; `false` otherwise. Logs may be
* printed in case of failure.
*
* @warning No thread-safety guarantees are provided for this function.
*/
bool IotSdk_Init( void );
/**
* @brief One-time deinitialization function for all common libraries.
*
* This function frees resources taken in `IotSdk_Init`. No other function
* in this SDK may be called after calling this function unless `IotSdk_Init`
* is called again.
*
* @warning No thread-safety guarantees are provided for this function.
*/
void IotSdk_Cleanup( void );
#endif /* IOT_INIT_H_ */

View file

@ -0,0 +1,956 @@
/*
* Amazon FreeRTOS Common V1.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_linear_containers.h
* @brief Declares and implements doubly-linked lists and queues.
*/
#ifndef IOT_LINEAR_CONTAINERS_H_
#define IOT_LINEAR_CONTAINERS_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/**
* @defgroup linear_containers_datatypes_listqueue List and queue
* @brief Structures that represent a list or queue.
*/
/**
* @ingroup linear_containers_datatypes_listqueue
* @brief Link member placed in structs of a list or queue.
*
* All elements in a list or queue must contain one of these members. The macro
* #IotLink_Container can be used to calculate the starting address of the
* link's container.
*/
typedef struct IotLink
{
struct IotLink * pPrevious; /**< @brief Pointer to the previous element. */
struct IotLink * pNext; /**< @brief Pointer to the next element. */
} IotLink_t;
/**
* @ingroup linear_containers_datatypes_listqueue
* @brief Represents a doubly-linked list.
*/
typedef IotLink_t IotListDouble_t;
/**
* @ingroup linear_containers_datatypes_listqueue
* @brief Represents a queue.
*/
typedef IotLink_t IotDeQueue_t;
/**
* @constantspage{linear_containers,linear containers library}
*
* @section linear_containers_constants_initializers Linear Containers Initializers
* @brief Provides default values for initializing the linear containers data types.
*
* @snippet this define_linear_containers_initializers
*
* All user-facing data types of the linear containers library should be initialized
* using one of the following.
*
* @warning Failure to initialize a linear containers data type with the appropriate
* initializer may result in a runtime error!
* @note The initializers may change at any time in future versions, but their
* names will remain the same.
*/
/* @[define_linear_containers_initializers] */
#define IOT_LINK_INITIALIZER { 0 } /**< @brief Initializer for an #IotLink_t. */
#define IOT_LIST_DOUBLE_INITIALIZER IOT_LINK_INITIALIZER /**< @brief Initializer for an #IotListDouble_t. */
#define IOT_DEQUEUE_INITIALIZER IOT_LINK_INITIALIZER /**< @brief Initializer for an #IotDeQueue_t. */
/* @[define_linear_containers_initializers] */
/**
* @def IotContainers_Assert( expression )
* @brief Assertion macro for the linear containers library.
*
* Set @ref IOT_CONTAINERS_ENABLE_ASSERTS to `1` to enable assertions in the linear
* containers library.
*
* @param[in] expression Expression to be evaluated.
*/
#if IOT_CONTAINERS_ENABLE_ASSERTS == 1
#ifndef IotContainers_Assert
#include <assert.h>
#define IotContainers_Assert( expression ) assert( expression )
#endif
#else
#define IotContainers_Assert( expression )
#endif
/**
* @brief Calculates the starting address of a containing struct.
*
* @param[in] type Type of the containing struct.
* @param[in] pLink Pointer to a link member.
* @param[in] linkName Name of the #IotLink_t in the containing struct.
*/
#define IotLink_Container( type, pLink, linkName ) \
( ( type * ) ( void * ) ( ( ( uint8_t * ) ( pLink ) ) - offsetof( type, linkName ) ) )
/**
* @brief Iterates through all elements of a linear container.
*
* Container elements must not be freed or removed while iterating.
*
* @param[in] pStart The first element to iterate from.
* @param[out] pLink Pointer to a container element.
*/
#define IotContainers_ForEach( pStart, pLink ) \
for( ( pLink ) = ( pStart )->pNext; \
( pLink ) != ( pStart ); \
( pLink ) = ( pLink )->pNext )
/**
* @functionspage{linear_containers,linear containers library}
* - @functionname{linear_containers_function_link_islinked}
* - @functionname{linear_containers_function_list_double_create}
* - @functionname{linear_containers_function_list_double_count}
* - @functionname{linear_containers_function_list_double_isempty}
* - @functionname{linear_containers_function_list_double_peekhead}
* - @functionname{linear_containers_function_list_double_peektail}
* - @functionname{linear_containers_function_list_double_inserthead}
* - @functionname{linear_containers_function_list_double_inserttail}
* - @functionname{linear_containers_function_list_double_insertbefore}
* - @functionname{linear_containers_function_list_double_insertafter}
* - @functionname{linear_containers_function_list_double_insertsorted}
* - @functionname{linear_containers_function_list_double_remove}
* - @functionname{linear_containers_function_list_double_removehead}
* - @functionname{linear_containers_function_list_double_removetail}
* - @functionname{linear_containers_function_list_double_removeall}
* - @functionname{linear_containers_function_list_double_findfirstmatch}
* - @functionname{linear_containers_function_list_double_removefirstmatch}
* - @functionname{linear_containers_function_list_double_removeallmatches}
* - @functionname{linear_containers_function_queue_create}
* - @functionname{linear_containers_function_queue_count}
* - @functionname{linear_containers_function_queue_isempty}
* - @functionname{linear_containers_function_queue_peekhead}
* - @functionname{linear_containers_function_queue_peektail}
* - @functionname{linear_containers_function_queue_enqueuehead}
* - @functionname{linear_containers_function_queue_dequeuehead}
* - @functionname{linear_containers_function_queue_enqueuetail}
* - @functionname{linear_containers_function_queue_dequeuetail}
* - @functionname{linear_containers_function_queue_remove}
* - @functionname{linear_containers_function_queue_removeall}
* - @functionname{linear_containers_function_queue_removeallmatches}
*/
/**
* @functionpage{IotLink_IsLinked,linear_containers,link_islinked}
* @functionpage{IotListDouble_Create,linear_containers,list_double_create}
* @functionpage{IotListDouble_Count,linear_containers,list_double_count}
* @functionpage{IotListDouble_IsEmpty,linear_containers,list_double_isempty}
* @functionpage{IotListDouble_PeekHead,linear_containers,list_double_peekhead}
* @functionpage{IotListDouble_PeekTail,linear_containers,list_double_peektail}
* @functionpage{IotListDouble_InsertHead,linear_containers,list_double_inserthead}
* @functionpage{IotListDouble_InsertTail,linear_containers,list_double_inserttail}
* @functionpage{IotListDouble_InsertBefore,linear_containers,list_double_insertbefore}
* @functionpage{IotListDouble_InsertAfter,linear_containers,list_double_insertafter}
* @functionpage{IotListDouble_InsertSorted,linear_containers,list_double_insertsorted}
* @functionpage{IotListDouble_Remove,linear_containers,list_double_remove}
* @functionpage{IotListDouble_RemoveHead,linear_containers,list_double_removehead}
* @functionpage{IotListDouble_RemoveTail,linear_containers,list_double_removetail}
* @functionpage{IotListDouble_RemoveAll,linear_containers,list_double_removeall}
* @functionpage{IotListDouble_FindFirstMatch,linear_containers,list_double_findfirstmatch}
* @functionpage{IotListDouble_RemoveFirstMatch,linear_containers,list_double_removefirstmatch}
* @functionpage{IotListDouble_RemoveAllMatches,linear_containers,list_double_removeallmatches}
* @functionpage{IotDeQueue_Create,linear_containers,queue_create}
* @functionpage{IotDeQueue_Count,linear_containers,queue_count}
* @functionpage{IotDeQueue_IsEmpty,linear_containers,queue_isempty}
* @functionpage{IotDeQueue_PeekHead,linear_containers,queue_peekhead}
* @functionpage{IotDeQueue_PeekTail,linear_containers,queue_peektail}
* @functionpage{IotDeQueue_EnqueueHead,linear_containers,queue_enqueuehead}
* @functionpage{IotDeQueue_DequeueHead,linear_containers,queue_dequeuehead}
* @functionpage{IotDeQueue_EnqueueTail,linear_containers,queue_enqueuetail}
* @functionpage{IotDeQueue_DequeueTail,linear_containers,queue_dequeuetail}
* @functionpage{IotDeQueue_Remove,linear_containers,queue_remove}
* @functionpage{IotDeQueue_RemoveAll,linear_containers,queue_removeall}
* @functionpage{IotDeQueue_RemoveAllMatches,linear_containers,queue_removeallmatches}
*/
/**
* @brief Check if an #IotLink_t is linked in a list or queue.
*
* @param[in] pLink The link to check.
*
* @return `true` if `pCurrent` is linked in a list or queue; `false` otherwise.
*/
/* @[declare_linear_containers_link_islinked] */
static inline bool IotLink_IsLinked( const IotLink_t * const pLink )
/* @[declare_linear_containers_link_islinked] */
{
bool isLinked = false;
if( pLink != NULL )
{
isLinked = ( pLink->pNext != NULL ) && ( pLink->pPrevious != NULL );
}
return isLinked;
}
/**
* @brief Create a new doubly-linked list.
*
* This function initializes a new doubly-linked list. It must be called on an
* uninitialized #IotListDouble_t before calling any other doubly-linked list
* function. This function must not be called on an already-initialized
* #IotListDouble_t.
*
* This function will not fail. The function @ref linear_containers_function_list_double_removeall
* may be called to destroy a list.
*
* @param[in] pList Pointer to the memory that will hold the new doubly-linked list.
*/
/* @[declare_linear_containers_list_double_create] */
static inline void IotListDouble_Create( IotListDouble_t * const pList )
/* @[declare_linear_containers_list_double_create] */
{
/* This function must not be called with a NULL parameter. */
IotContainers_Assert( pList != NULL );
/* An empty list is a link pointing to itself. */
pList->pPrevious = pList;
pList->pNext = pList;
}
/**
* @brief Return the number of elements contained in an #IotListDouble_t.
*
* @param[in] pList The doubly-linked list with the elements to count.
*
* @return The number of elements in the doubly-linked list.
*/
/* @[declare_linear_containers_list_double_count] */
static inline size_t IotListDouble_Count( const IotListDouble_t * const pList )
/* @[declare_linear_containers_list_double_count] */
{
size_t count = 0;
if( pList != NULL )
{
/* Get the list head. */
const IotLink_t * pCurrent = pList->pNext;
/* Iterate through the list to count the elements. */
while( pCurrent != pList )
{
count++;
pCurrent = pCurrent->pNext;
}
}
return count;
}
/**
* @brief Check if a doubly-linked list is empty.
*
* @param[in] pList The doubly-linked list to check.
*
* @return `true` if the list is empty; `false` otherwise.
*/
/* @[declare_linear_containers_list_double_isempty] */
static inline bool IotListDouble_IsEmpty( const IotListDouble_t * const pList )
/* @[declare_linear_containers_list_double_isempty] */
{
/* An empty list is NULL link, or a link pointing to itself. */
return( ( pList == NULL ) || ( pList->pNext == pList ) );
}
/**
* @brief Return an #IotLink_t representing the first element in a doubly-linked list
* without removing it.
*
* @param[in] pList The list to peek.
*
* @return Pointer to an #IotLink_t representing the element at the head of the
* list; `NULL` if the list is empty. The macro #IotLink_Container may be used to
* determine the address of the link's container.
*/
/* @[declare_linear_containers_list_double_peekhead] */
static inline IotLink_t * IotListDouble_PeekHead( const IotListDouble_t * const pList )
/* @[declare_linear_containers_list_double_peekhead] */
{
IotLink_t * pHead = NULL;
if( pList != NULL )
{
if( IotListDouble_IsEmpty( pList ) == false )
{
pHead = pList->pNext;
}
}
return pHead;
}
/**
* @brief Return an #IotLink_t representing the last element in a doubly-linked
* list without removing it.
*
* @param[in] pList The list to peek.
*
* @return Pointer to an #IotLink_t representing the element at the tail of the
* list; `NULL` if the list is empty. The macro #IotLink_Container may be used to
* determine the address of the link's container.
*/
/* @[declare_linear_containers_list_double_peektail] */
static inline IotLink_t * IotListDouble_PeekTail( const IotListDouble_t * const pList )
/* @[declare_linear_containers_list_double_peektail] */
{
IotLink_t * pTail = NULL;
if( pList != NULL )
{
if( IotListDouble_IsEmpty( pList ) == false )
{
pTail = pList->pPrevious;
}
}
return pTail;
}
/**
* @brief Insert an element at the head of a doubly-linked list.
*
* @param[in] pList The doubly-linked list that will hold the new element.
* @param[in] pLink Pointer to the new element's link member.
*/
/* @[declare_linear_containers_list_double_inserthead] */
static inline void IotListDouble_InsertHead( IotListDouble_t * const pList,
IotLink_t * const pLink )
/* @[declare_linear_containers_list_double_inserthead] */
{
/* This function must not be called with NULL parameters. */
IotContainers_Assert( pList != NULL );
IotContainers_Assert( pLink != NULL );
/* Save current list head. */
IotLink_t * pHead = pList->pNext;
/* Place new element before list head. */
pLink->pNext = pHead;
pLink->pPrevious = pList;
/* Assign new list head. */
pHead->pPrevious = pLink;
pList->pNext = pLink;
}
/**
* @brief Insert an element at the tail of a doubly-linked list.
*
* @param[in] pList The double-linked list that will hold the new element.
* @param[in] pLink Pointer to the new element's link member.
*/
/* @[declare_linear_containers_list_double_inserttail] */
static inline void IotListDouble_InsertTail( IotListDouble_t * const pList,
IotLink_t * const pLink )
/* @[declare_linear_containers_list_double_inserttail] */
{
/* This function must not be called with NULL parameters. */
IotContainers_Assert( pList != NULL );
IotContainers_Assert( pLink != NULL );
/* Save current list tail. */
IotLink_t * pTail = pList->pPrevious;
pLink->pNext = pList;
pLink->pPrevious = pTail;
pList->pPrevious = pLink;
pTail->pNext = pLink;
}
/**
* @brief Insert an element before another element in a doubly-linked list.
*
* @param[in] pElement The new element will be placed before this element.
* @param[in] pLink Pointer to the new element's link member.
*/
/* @[declare_linear_containers_list_double_insertbefore] */
static inline void IotListDouble_InsertBefore( IotLink_t * const pElement,
IotLink_t * const pLink )
/* @[declare_linear_containers_list_double_insertbefore] */
{
IotListDouble_InsertTail( pElement, pLink );
}
/**
* @brief Insert an element after another element in a doubly-linked list.
*
* @param[in] pElement The new element will be placed after this element.
* @param[in] pLink Pointer to the new element's link member.
*/
/* @[declare_linear_containers_list_double_insertafter] */
static inline void IotListDouble_InsertAfter( IotLink_t * const pElement,
IotLink_t * const pLink )
/* @[declare_linear_containers_list_double_insertafter] */
{
IotListDouble_InsertHead( pElement, pLink );
}
/**
* @brief Insert an element in a sorted doubly-linked list.
*
* Places an element into a list by sorting it into order. The function
* `compare` is used to determine where to place the new element.
*
* @param[in] pList The list that will hold the new element.
* @param[in] pLink Pointer to the new element's link member.
* @param[in] compare Determines the order of the list. Returns a negative
* value if its first argument is less than its second argument; returns
* zero if its first argument is equal to its second argument; returns a
* positive value if its first argument is greater than its second argument.
* The parameters to this function are #IotLink_t, so the macro #IotLink_Container
* may be used to determine the address of the link's container.
*/
/* @[declare_linear_containers_list_double_insertsorted] */
static inline void IotListDouble_InsertSorted( IotListDouble_t * const pList,
IotLink_t * const pLink,
int32_t ( *compare )( const IotLink_t * const, const IotLink_t * const ) )
/* @[declare_linear_containers_list_double_insertsorted] */
{
/* This function must not be called with NULL parameters. */
IotContainers_Assert( pList != NULL );
IotContainers_Assert( pLink != NULL );
IotContainers_Assert( compare != NULL );
/* Insert at head for empty list. */
if( IotListDouble_IsEmpty( pList ) == true )
{
IotListDouble_InsertHead( pList, pLink );
}
else
{
bool inserted = false;
IotLink_t * pCurrent = pList->pNext;
/* Iterate through the list to find the correct position. */
while( pCurrent != pList )
{
/* Comparing for '<' preserves the order of insertion. */
if( compare( pLink, pCurrent ) < 0 )
{
IotListDouble_InsertBefore( pCurrent, pLink );
inserted = true;
break;
}
pCurrent = pCurrent->pNext;
}
/* New element is greater than all elements in list. Insert at tail. */
if( inserted == false )
{
IotListDouble_InsertTail( pList, pLink );
}
}
}
/**
* @brief Remove a single element from a doubly-linked list.
*
* @param[in] pLink The element to remove.
*/
/* @[declare_linear_containers_list_double_remove] */
static inline void IotListDouble_Remove( IotLink_t * const pLink )
/* @[declare_linear_containers_list_double_remove] */
{
/* This function must not be called with a NULL parameter. */
IotContainers_Assert( pLink != NULL );
/* This function must be called on a linked element. */
IotContainers_Assert( IotLink_IsLinked( pLink ) == true );
pLink->pPrevious->pNext = pLink->pNext;
pLink->pNext->pPrevious = pLink->pPrevious;
pLink->pPrevious = NULL;
pLink->pNext = NULL;
}
/**
* @brief Remove the element at the head of a doubly-linked list.
*
* @param[in] pList The doubly-linked list that holds the element to remove.
*
* @return Pointer to an #IotLink_t representing the removed list head; `NULL`
* if the list is empty. The macro #IotLink_Container may be used to determine
* the address of the link's container.
*/
/* @[declare_linear_containers_list_double_removehead] */
static inline IotLink_t * IotListDouble_RemoveHead( IotListDouble_t * const pList )
/* @[declare_linear_containers_list_double_removehead] */
{
IotLink_t * pHead = NULL;
if( IotListDouble_IsEmpty( pList ) == false )
{
pHead = pList->pNext;
IotListDouble_Remove( pHead );
}
return pHead;
}
/**
* @brief Remove the element at the tail of a doubly-linked list.
*
* @param[in] pList The doubly-linked list that holds the element to remove.
*
* @return Pointer to an #IotLink_t representing the removed list tail; `NULL`
* if the list is empty. The macro #IotLink_Container may be used to determine
* the address of the link's container.
*/
/* @[declare_linear_containers_list_double_removetail] */
static inline IotLink_t * IotListDouble_RemoveTail( IotListDouble_t * const pList )
/* @[declare_linear_containers_list_double_removetail] */
{
IotLink_t * pTail = NULL;
if( IotListDouble_IsEmpty( pList ) == false )
{
pTail = pList->pPrevious;
IotListDouble_Remove( pTail );
}
return pTail;
}
/**
* @brief Remove all elements in a doubly-linked list.
*
* @param[in] pList The list to empty.
* @param[in] freeElement A function to free memory used by each removed list
* element. Optional; pass `NULL` to ignore.
* @param[in] linkOffset Offset in bytes of a link member in its container, used
* to calculate the pointer to pass to `freeElement`. This value should be calculated
* with the C `offsetof` macro. This parameter is ignored if `freeElement` is `NULL`
* or its value is `0`.
*/
/* @[declare_linear_containers_list_double_removeall] */
static inline void IotListDouble_RemoveAll( IotListDouble_t * const pList,
void ( *freeElement )( void * ),
size_t linkOffset )
/* @[declare_linear_containers_list_double_removeall] */
{
/* This function must not be called with a NULL pList parameter. */
IotContainers_Assert( pList != NULL );
/* Get the list head. */
IotLink_t * pCurrent = pList->pNext;
/* Iterate through the list and remove all elements. */
while( pCurrent != pList )
{
/* Save a pointer to the next list element. */
IotLink_t * pNext = pCurrent->pNext;
/* Remove and free the current list element. */
IotListDouble_Remove( pCurrent );
if( freeElement != NULL )
{
freeElement( ( ( uint8_t * ) pCurrent ) - linkOffset );
}
/* Move the iterating pointer to the next list element. */
pCurrent = pNext;
}
}
/**
* @brief Search a doubly-linked list for the first matching element.
*
* If a match is found, the matching element is <b>not</b> removed from the list.
* See @ref linear_containers_function_list_double_removefirstmatch for the function
* that searches and removes.
*
* @param[in] pList The doubly-linked list to search.
* @param[in] pStartPoint An element in `pList`. Only elements between this one and
* the list tail are checked. Pass `NULL` to search from the beginning of the list.
* @param[in] isMatch Function to determine if an element matches. Pass `NULL` to
* search using the address `pMatch`, i.e. `element == pMatch`.
* @param[in] pMatch If `isMatch` is `NULL`, each element in the list is compared
* to this address to find a match. Otherwise, it is passed as the second argument
* to `isMatch`.
*
* @return Pointer to an #IotLink_t representing the first matched element; `NULL`
* if no match is found. The macro #IotLink_Container may be used to determine the
* address of the link's container.
*/
/* @[declare_linear_containers_list_double_findfirstmatch] */
static inline IotLink_t * IotListDouble_FindFirstMatch( const IotListDouble_t * const pList,
const IotLink_t * const pStartPoint,
bool ( *isMatch )( const IotLink_t * const, void * ),
void * pMatch )
/* @[declare_linear_containers_list_double_findfirstmatch] */
{
/* The const must be cast away to match this function's return value. Nevertheless,
* this function will respect the const-ness of pStartPoint. */
IotLink_t * pCurrent = ( IotLink_t * ) pStartPoint;
/* This function must not be called with a NULL pList parameter. */
IotContainers_Assert( pList != NULL );
/* Search starting from list head if no start point is given. */
if( pStartPoint == NULL )
{
pCurrent = pList->pNext;
}
/* Iterate through the list to search for matches. */
while( pCurrent != pList )
{
/* Call isMatch if provided. Otherwise, compare pointers. */
if( isMatch != NULL )
{
if( isMatch( pCurrent, pMatch ) == true )
{
return pCurrent;
}
}
else
{
if( pCurrent == pMatch )
{
return pCurrent;
}
}
pCurrent = pCurrent->pNext;
}
/* No match found, return NULL. */
return NULL;
}
/**
* @brief Search a doubly-linked list for the first matching element and remove
* it.
*
* An #IotLink_t may be passed as `pList` to start searching after the head of a
* doubly-linked list.
*
* @param[in] pList The doubly-linked list to search.
* @param[in] pStartPoint An element in `pList`. Only elements between this one and
* the list tail are checked. Pass `NULL` to search from the beginning of the list.
* @param[in] isMatch Function to determine if an element matches. Pass `NULL` to
* search using the address `pMatch`, i.e. `element == pMatch`.
* @param[in] pMatch If `isMatch` is `NULL`, each element in the list is compared
* to this address to find a match. Otherwise, it is passed as the second argument
* to `isMatch`.
*
* @return Pointer to an #IotLink_t representing the matched and removed element;
* `NULL` if no match is found. The macro #IotLink_Container may be used to determine
* the address of the link's container.
*/
/* @[declare_linear_containers_list_double_removefirstmatch] */
static inline IotLink_t * IotListDouble_RemoveFirstMatch( IotListDouble_t * const pList,
const IotLink_t * const pStartPoint,
bool ( *isMatch )( const IotLink_t *, void * ),
void * pMatch )
/* @[declare_linear_containers_list_double_removefirstmatch] */
{
IotLink_t * pMatchedElement = IotListDouble_FindFirstMatch( pList,
pStartPoint,
isMatch,
pMatch );
if( pMatchedElement != NULL )
{
IotListDouble_Remove( pMatchedElement );
}
return pMatchedElement;
}
/**
* @brief Remove all matching elements from a doubly-linked list.
*
* @param[in] pList The doubly-linked list to search.
* @param[in] isMatch Function to determine if an element matches. Pass `NULL` to
* search using the address `pMatch`, i.e. `element == pMatch`.
* @param[in] pMatch If `isMatch` is `NULL`, each element in the list is compared
* to this address to find a match. Otherwise, it is passed as the second argument
* to `isMatch`.
* @param[in] freeElement A function to free memory used by each removed list
* element. Optional; pass `NULL` to ignore.
* @param[in] linkOffset Offset in bytes of a link member in its container, used
* to calculate the pointer to pass to `freeElement`. This value should be calculated
* with the C `offsetof` macro. This parameter is ignored if `freeElement` is `NULL`
* or its value is `0`.
*/
/* @[declare_linear_containers_list_double_removeallmatches] */
static inline void IotListDouble_RemoveAllMatches( IotListDouble_t * const pList,
bool ( *isMatch )( const IotLink_t *, void * ),
void * pMatch,
void ( *freeElement )( void * ),
size_t linkOffset )
/* @[declare_linear_containers_list_double_removeallmatches] */
{
IotLink_t * pMatchedElement = NULL, * pNextElement = NULL;
/* Search the list for all matching elements. */
do
{
pMatchedElement = IotListDouble_FindFirstMatch( pList,
pMatchedElement,
isMatch,
pMatch );
if( pMatchedElement != NULL )
{
/* Save pointer to next element. */
pNextElement = pMatchedElement->pNext;
/* Match found; remove and free. */
IotListDouble_Remove( pMatchedElement );
if( freeElement != NULL )
{
freeElement( ( ( uint8_t * ) pMatchedElement ) - linkOffset );
}
/* Continue search from next element. */
pMatchedElement = pNextElement;
}
} while( pMatchedElement != NULL );
}
/**
* @brief Create a new queue.
*
* This function initializes a new double-ended queue. It must be called on an uninitialized
* #IotDeQueue_t before calling any other queue function. This function must not be
* called on an already-initialized #IotDeQueue_t.
*
* This function will not fail.
*
* @param[in] pQueue Pointer to the memory that will hold the new queue.
*/
/* @[declare_linear_containers_queue_create] */
static inline void IotDeQueue_Create( IotDeQueue_t * const pQueue )
/* @[declare_linear_containers_queue_create] */
{
IotListDouble_Create( pQueue );
}
/**
* @brief Return the number of elements contained in an #IotDeQueue_t.
*
* @param[in] pQueue The queue with the elements to count.
*
* @return The number of items elements in the queue.
*/
/* @[declare_linear_containers_queue_count] */
static inline size_t IotDeQueue_Count( const IotDeQueue_t * const pQueue )
/* @[declare_linear_containers_queue_count] */
{
return IotListDouble_Count( pQueue );
}
/**
* @brief Check if a queue is empty.
*
* @param[in] pQueue The queue to check.
*
* @return `true` if the queue is empty; `false` otherwise.
*
*/
/* @[declare_linear_containers_queue_isempty] */
static inline bool IotDeQueue_IsEmpty( const IotDeQueue_t * const pQueue )
/* @[declare_linear_containers_queue_isempty] */
{
return IotListDouble_IsEmpty( pQueue );
}
/**
* @brief Return an #IotLink_t representing the element at the front of the queue
* without removing it.
*
* @param[in] pQueue The queue to peek.
*
* @return Pointer to an #IotLink_t representing the element at the head of the
* queue; `NULL` if the queue is empty. The macro #IotLink_Container may be used
* to determine the address of the link's container.
*/
/* @[declare_linear_containers_queue_peekhead] */
static inline IotLink_t * IotDeQueue_PeekHead( const IotDeQueue_t * const pQueue )
/* @[declare_linear_containers_queue_peekhead] */
{
return IotListDouble_PeekHead( pQueue );
}
/**
* @brief Return an #IotLink_t representing the element at the back of the queue
* without removing it.
*
* @param[in] pQueue The queue to peek.
*
* @return Pointer to an #IotLink_t representing the element at the head of the
* queue; `NULL` if the queue is empty. The macro #IotLink_Container may be used
* to determine the address of the link's container.
*/
/* @[declare_linear_containers_queue_peektail] */
static inline IotLink_t * IotDeQueue_PeekTail( const IotDeQueue_t * const pQueue )
/* @[declare_linear_containers_queue_peektail] */
{
return IotListDouble_PeekTail( pQueue );
}
/**
* @brief Add an element at the head of the queue.
*
* @param[in] pQueue The queue that will hold the new element.
* @param[in] pLink Pointer to the new element's link member.
*/
/* @[declare_linear_containers_queue_enqueuehead] */
static inline void IotDeQueue_EnqueueHead( IotDeQueue_t * const pQueue,
IotLink_t * const pLink )
/* @[declare_linear_containers_queue_enqueuehead] */
{
IotListDouble_InsertHead( pQueue, pLink );
}
/**
* @brief Remove an element at the head of the queue.
*
* @param[in] pQueue The queue that holds the element to remove.
*
* @return Pointer to an #IotLink_t representing the removed queue element; `NULL`
* if the queue is empty. The macro #IotLink_Container may be used to determine
* the address of the link's container.
*/
/* @[declare_linear_containers_queue_dequeuehead] */
static inline IotLink_t * IotDeQueue_DequeueHead( IotDeQueue_t * const pQueue )
/* @[declare_linear_containers_queue_dequeuehead] */
{
return IotListDouble_RemoveHead( pQueue );
}
/**
* @brief Add an element at the tail of the queue.
*
* @param[in] pQueue The queue that will hold the new element.
* @param[in] pLink Pointer to the new element's link member.
*/
/* @[declare_linear_containers_queue_enqueuetail] */
static inline void IotDeQueue_EnqueueTail( IotDeQueue_t * const pQueue,
IotLink_t * const pLink )
/* @[declare_linear_containers_queue_enqueuetail] */
{
IotListDouble_InsertTail( pQueue, pLink );
}
/**
* @brief Remove an element at the tail of the queue.
*
* @param[in] pQueue The queue that holds the element to remove.
*
* @return Pointer to an #IotLink_t representing the removed queue element; `NULL`
* if the queue is empty. The macro #IotLink_Container may be used to determine
* the address of the link's container.
*/
/* @[declare_linear_containers_queue_dequeuetail] */
static inline IotLink_t * IotDeQueue_DequeueTail( IotDeQueue_t * const pQueue )
/* @[declare_linear_containers_queue_dequeuetail] */
{
return IotListDouble_RemoveTail( pQueue );
}
/**
* @brief Remove a single element from a queue.
*
* @param[in] pLink The element to remove.
*/
/* @[declare_linear_containers_queue_remove] */
static inline void IotDeQueue_Remove( IotLink_t * const pLink )
/* @[declare_linear_containers_queue_remove] */
{
IotListDouble_Remove( pLink );
}
/**
* @brief Remove all elements in a queue.
*
* @param[in] pQueue The queue to empty.
* @param[in] freeElement A function to free memory used by each removed queue
* element. Optional; pass `NULL` to ignore.
* @param[in] linkOffset Offset in bytes of a link member in its container, used
* to calculate the pointer to pass to `freeElement`. This value should be calculated
* with the C `offsetof` macro. This parameter is ignored if `freeElement` is `NULL`
* or its value is `0`.
*/
/* @[declare_linear_containers_queue_removeall] */
static inline void IotDeQueue_RemoveAll( IotDeQueue_t * const pQueue,
void ( * freeElement )( void * ),
size_t linkOffset )
/* @[declare_linear_containers_queue_removeall] */
{
IotListDouble_RemoveAll( pQueue, freeElement, linkOffset );
}
/**
* @brief Remove all matching elements from a queue.
*
* @param[in] pQueue The queue to search.
* @param[in] isMatch Function to determine if an element matches. Pass `NULL` to
* search using the address `pMatch`, i.e. `element == pMatch`.
* @param[in] pMatch If `isMatch` is `NULL`, each element in the queue is compared
* to this address to find a match. Otherwise, it is passed as the second argument
* to `isMatch`.
* @param[in] freeElement A function to free memory used by each removed queue
* element. Optional; pass `NULL` to ignore.
* @param[in] linkOffset Offset in bytes of a link member in its container, used
* to calculate the pointer to pass to `freeElement`. This value should be calculated
* with the C `offsetof` macro. This parameter is ignored if `freeElement` is `NULL`
* or its value is `0`.
*/
/* @[declare_linear_containers_queue_removeallmatches] */
static inline void IotDeQueue_RemoveAllMatches( IotDeQueue_t * const pQueue,
bool ( * isMatch )( const IotLink_t *, void * ),
void * pMatch,
void ( * freeElement )( void * ),
size_t linkOffset )
/* @[declare_linear_containers_queue_removeallmatches] */
{
IotListDouble_RemoveAllMatches( pQueue, isMatch, pMatch, freeElement, linkOffset );
}
#endif /* IOT_LINEAR_CONTAINERS_H_ */

View file

@ -0,0 +1,223 @@
/*
* Amazon FreeRTOS Common V1.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_logging_setup.h
* @brief Defines the logging macro #IotLog.
*/
#ifndef IOT_LOGGING_SETUP_H_
#define IOT_LOGGING_SETUP_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Logging include. Because it's included here, iot_logging.h never needs
* to be included in source. */
#include "private/iot_logging.h"
/**
* @functionpage{IotLog,logging,log}
* @functionpage{IotLog_PrintBuffer,logging,printbuffer}
*/
/**
* @def IotLog( messageLevel, pLogConfig, ... )
* @brief Logging function for a specific library. In most cases, this is the
* logging function to call.
*
* This function prints a single log message. It is available when @ref
* LIBRARY_LOG_LEVEL is not #IOT_LOG_NONE. Log messages automatically
* include the [log level](@ref logging_constants_levels), [library name]
* (@ref LIBRARY_LOG_NAME), and time. An optional @ref IotLogConfig_t may
* be passed to this function to hide information for a single log message.
*
* The logging library must be set up before this function may be called. See
* @ref logging_setup_use for more information.
*
* This logging function also has the following abbreviated forms that can be used
* when an #IotLogConfig_t isn't needed.
*
* Name | Equivalent to
* ---- | -------------
* #IotLogError | @code{c} IotLog( IOT_LOG_ERROR, NULL, ... ) @endcode
* #IotLogWarn | @code{c} IotLog( IOT_LOG_WARN, NULL, ... ) @endcode
* #IotLogInfo | @code{c} IotLog( IOT_LOG_INFO, NULL, ... ) @endcode
* #IotLogDebug | @code{c} IotLog( IOT_LOG_DEBUG, NULL, ... ) @endcode
*
* @param[in] messageLevel Log level of this message. Must be one of the
* @ref logging_constants_levels.
* @param[in] pLogConfig Pointer to an #IotLogConfig_t. Optional; pass `NULL`
* to ignore.
* @param[in] ... Message and format specification.
*
* @return No return value. On errors, it prints nothing.
*
* @note This function may be implemented as a macro.
* @see @ref logging_function_generic for the generic (not library-specific)
* logging function.
*/
/**
* @def IotLog_PrintBuffer( pHeader, pBuffer, bufferSize )
* @brief Log the contents of buffer as bytes. Only available when @ref
* LIBRARY_LOG_LEVEL is #IOT_LOG_DEBUG.
*
* This function prints the bytes located at a given memory address. It is
* intended for debugging only, and is therefore only available when @ref
* LIBRARY_LOG_LEVEL is #IOT_LOG_DEBUG.
*
* Log messages printed by this function <b>always</b> include the [log level]
* (@ref logging_constants_levels), [library name](@ref LIBRARY_LOG_NAME),
* and time. In addition, this function may print an optional header `pHeader`
* before it prints the contents of the buffer. This function does not have an
* #IotLogConfig_t parameter.
*
* The logging library must be set up before this function may be called. See
* @ref logging_setup_use for more information.
*
* @param[in] pHeader A message to log before the buffer. Optional; pass `NULL`
* to ignore.
* @param[in] pBuffer Pointer to start of buffer.
* @param[in] bufferSize Size of `pBuffer`.
*
* @return No return value. On errors, it prints nothing.
*
* @note This function may be implemented as a macro.
* @note To conserve memory, @ref logging_function_genericprintbuffer (the underlying
* implementation) only allocates enough memory for a single line of output. Therefore,
* in multithreaded systems, its output may appear "fragmented" if other threads are
* logging simultaneously.
* @see @ref logging_function_genericprintbuffer for the generic (not library-specific)
* buffer logging function.
*
* <b>Example</b>
* @code{c}
* const uint8_t pBuffer[] = { 0x00, 0x01, 0x02, 0x03 };
*
* IotLog_PrintBuffer( "This buffer contains:",
* pBuffer,
* 4 );
* @endcode
* The code above prints something like the following:
* @code{c}
* [DEBUG][LIB_NAME][2018-01-01 12:00:00] This buffer contains:
* 00 01 02 03
* @endcode
*/
/**
* @def IotLogError( ... )
* @brief Abbreviated logging macro for level #IOT_LOG_ERROR.
*
* Equivalent to:
* @code{c}
* IotLog( IOT_LOG_ERROR, NULL, ... )
* @endcode
*/
/**
* @def IotLogWarn( ... )
* @brief Abbreviated logging macro for level #IOT_LOG_WARN.
*
* Equivalent to:
* @code{c}
* IotLog( IOT_LOG_WARN, NULL, ... )
* @endcode
*/
/**
* @def IotLogInfo( ... )
* @brief Abbreviated logging macro for level #IOT_LOG_INFO.
*
* Equivalent to:
* @code{c}
* IotLog( IOT_LOG_INFO, NULL, ... )
* @endcode
*/
/**
* @def IotLogDebug( ... )
* @brief Abbreviated logging macro for level #IOT_LOG_DEBUG.
*
* Equivalent to:
* @code{c}
* IotLog( IOT_LOG_DEBUG, NULL, ... )
* @endcode
*/
/* Check that LIBRARY_LOG_LEVEL is defined and has a valid value. */
#if !defined( LIBRARY_LOG_LEVEL ) || \
( LIBRARY_LOG_LEVEL != IOT_LOG_NONE && \
LIBRARY_LOG_LEVEL != IOT_LOG_ERROR && \
LIBRARY_LOG_LEVEL != IOT_LOG_WARN && \
LIBRARY_LOG_LEVEL != IOT_LOG_INFO && \
LIBRARY_LOG_LEVEL != IOT_LOG_DEBUG )
#error "Please define LIBRARY_LOG_LEVEL as either IOT_LOG_NONE, IOT_LOG_ERROR, IOT_LOG_WARN, IOT_LOG_INFO, or IOT_LOG_DEBUG."
/* Check that LIBRARY_LOG_NAME is defined and has a valid value. */
#elif !defined( LIBRARY_LOG_NAME )
#error "Please define LIBRARY_LOG_NAME."
#else
/* Define IotLog if the log level is greater than "none". */
#if LIBRARY_LOG_LEVEL > IOT_LOG_NONE
#define IotLog( messageLevel, pLogConfig, ... ) \
IotLog_Generic( LIBRARY_LOG_LEVEL, \
LIBRARY_LOG_NAME, \
messageLevel, \
pLogConfig, \
__VA_ARGS__ )
/* Define the abbreviated logging macros. */
#define IotLogError( ... ) IotLog( IOT_LOG_ERROR, NULL, __VA_ARGS__ )
#define IotLogWarn( ... ) IotLog( IOT_LOG_WARN, NULL, __VA_ARGS__ )
#define IotLogInfo( ... ) IotLog( IOT_LOG_INFO, NULL, __VA_ARGS__ )
#define IotLogDebug( ... ) IotLog( IOT_LOG_DEBUG, NULL, __VA_ARGS__ )
/* If log level is DEBUG, enable the function to print buffers. */
#if LIBRARY_LOG_LEVEL >= IOT_LOG_DEBUG
#define IotLog_PrintBuffer( pHeader, pBuffer, bufferSize ) \
IotLog_GenericPrintBuffer( LIBRARY_LOG_NAME, \
pHeader, \
pBuffer, \
bufferSize )
#else
#define IotLog_PrintBuffer( pHeader, pBuffer, bufferSize )
#endif
/* Remove references to IotLog from the source code if logging is disabled. */
#else
/* @[declare_logging_log] */
#define IotLog( messageLevel, pLogConfig, ... )
/* @[declare_logging_log] */
/* @[declare_logging_printbuffer] */
#define IotLog_PrintBuffer( pHeader, pBuffer, bufferSize )
/* @[declare_logging_printbuffer] */
#define IotLogError( ... )
#define IotLogWarn( ... )
#define IotLogInfo( ... )
#define IotLogDebug( ... )
#endif
#endif
#endif /* ifndef IOT_LOGGING_SETUP_H_ */

View file

@ -0,0 +1,558 @@
/*
* Amazon FreeRTOS Common V1.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_taskpool.h
* @brief User-facing functions of the task pool library.
*/
#ifndef IOT_TASKPOOL_H_
#define IOT_TASKPOOL_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
/* Task pool types. */
#include "types/iot_taskpool_types.h"
/*------------------------- Task Pool library functions --------------------------*/
/**
* @functionspage{taskpool,task pool library}
* - @functionname{taskpool_function_createsystemtaskpool}
* - @functionname{taskpool_function_getsystemtaskpool}
* - @functionname{taskpool_function_create}
* - @functionname{taskpool_function_destroy}
* - @functionname{taskpool_function_setmaxthreads}
* - @functionname{taskpool_function_createjob}
* - @functionname{taskpool_function_createrecyclablejob}
* - @functionname{taskpool_function_destroyrecyclablejob}
* - @functionname{taskpool_function_recyclejob}
* - @functionname{taskpool_function_schedule}
* - @functionname{taskpool_function_scheduledeferred}
* - @functionname{taskpool_function_getstatus}
* - @functionname{taskpool_function_trycancel}
* - @functionname{taskpool_function_getjobstoragefromhandle}
* - @functionname{taskpool_function_strerror}
*/
/**
* @functionpage{IotTaskPool_CreateSystemTaskPool,taskpool,createsystemtaskpool}
* @functionpage{IotTaskPool_GetSystemTaskPool,taskpool,getsystemtaskpool}
* @functionpage{IotTaskPool_Create,taskpool,create}
* @functionpage{IotTaskPool_Destroy,taskpool,destroy}
* @functionpage{IotTaskPool_SetMaxThreads,taskpool,setmaxthreads}
* @functionpage{IotTaskPool_CreateJob,taskpool,createjob}
* @functionpage{IotTaskPool_CreateRecyclableJob,taskpool,createrecyclablejob}
* @functionpage{IotTaskPool_DestroyRecyclableJob,taskpool,destroyrecyclablejob}
* @functionpage{IotTaskPool_RecycleJob,taskpool,recyclejob}
* @functionpage{IotTaskPool_Schedule,taskpool,schedule}
* @functionpage{IotTaskPool_ScheduleDeferred,taskpool,scheduledeferred}
* @functionpage{IotTaskPool_GetStatus,taskpool,getstatus}
* @functionpage{IotTaskPool_TryCancel,taskpool,trycancel}
* @functionpage{IotTaskPool_GetJobStorageFromHandle,taskpool,getjobstoragefromhandle}
* @functionpage{IotTaskPool_strerror,taskpool,strerror}
*/
/**
* @brief Creates the one single instance of the system task pool.
*
* This function should be called once by the application to initialize the one single instance of the system task pool.
* An application should initialize the system task pool early in the boot sequence, before initializing any other library
* and before posting any jobs. Early initialization it typically easy to accomplish by creating the system task pool
* before starting the scheduler.
*
* This function does not allocate memory to hold the task pool data structures and state, but it
* may allocate memory to hold the dependent entities and data structures, e.g. the threads of the task
* pool. The system task pool handle is recoverable for later use by calling @ref IotTaskPool_GetSystemTaskPool or
* the shortcut @ref IOT_SYSTEM_TASKPOOL.
*
* @param[in] pInfo A pointer to the task pool initialization data.
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
* - #IOT_TASKPOOL_NO_MEMORY
*
* @warning This function should be called only once. Calling this function more that once will result in
* undefined behavior.
*
*/
/* @[declare_taskpool_createsystemtaskpool] */
IotTaskPoolError_t IotTaskPool_CreateSystemTaskPool( const IotTaskPoolInfo_t * const pInfo );
/* @[declare_taskpool_createsystemtaskpool] */
/**
* @brief Retrieves the one and only instance of a system task pool
*
* This function retrieves the system task pool created with @ref IotTaskPool_CreateSystemTaskPool, and it is functionally
* equivalent to using the shortcut @ref IOT_SYSTEM_TASKPOOL.
*
* @return The system task pool handle.
*
* @warning This function should be called after creating the system task pool with @ref IotTaskPool_CreateSystemTaskPool.
* Calling this function before creating the system task pool may return a pointer to an uninitialized task pool, NULL, or otherwise
* fail with undefined behaviour.
*
*/
/* @[declare_taskpool_getsystemtaskpool] */
IotTaskPool_t IotTaskPool_GetSystemTaskPool( void );
/* @[declare_taskpool_getsystemtaskpool] */
/**
* @brief Creates one instance of a task pool.
*
* This function should be called by the user to initialize one instance of a task
* pool. The task pool instance will be created around the storage pointed to by the `pTaskPool`
* parameter. This function will create the minimum number of threads requested by the user
* through an instance of the #IotTaskPoolInfo_t type specified with the `pInfo` parameter.
* This function does not allocate memory to hold the task pool data structures and state, but it
* may allocates memory to hold the dependent data structures, e.g. the threads of the task
* pool.
*
* @param[in] pInfo A pointer to the task pool initialization data.
* @param[out] pTaskPool A pointer to the task pool handle to be used after initialization.
* The pointer `pTaskPool` will hold a valid handle only if (@ref IotTaskPool_Create)
* completes successfully.
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
* - #IOT_TASKPOOL_NO_MEMORY
*
*/
/* @[declare_taskpool_create] */
IotTaskPoolError_t IotTaskPool_Create( const IotTaskPoolInfo_t * const pInfo,
IotTaskPool_t * const pTaskPool );
/* @[declare_taskpool_create] */
/**
* @brief Destroys a task pool instance and collects all memory associated with a task pool and its
* satellite data structures.
*
* This function should be called to destroy one instance of a task pool previously created with a call
* to @ref IotTaskPool_Create or @ref IotTaskPool_CreateSystemTaskPool.
* Calling this fuction release all underlying resources. After calling this function, any job scheduled but not yet executed
* will be canceled and destroyed.
* The `taskPool` instance will no longer be valid after this function returns.
*
* @param[in] taskPool A handle to the task pool, e.g. as returned by a call to @ref IotTaskPool_Create or
* @ref IotTaskPool_CreateSystemTaskPool. The `taskPool` instance will no longer be valid after this function returns.
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
*
*/
/* @[declare_taskpool_destroy] */
IotTaskPoolError_t IotTaskPool_Destroy( IotTaskPool_t taskPool );
/* @[declare_taskpool_destroy] */
/**
* @brief Sets the maximum number of threads for one instance of a task pool.
*
* This function sets the maximum number of threads for the task pool
* pointed to by `taskPool`.
*
* If the number of currently active threads in the task pool is greater than `maxThreads`, this
* function causes the task pool to shrink the number of active threads.
*
* @param[in] taskPool A handle to the task pool that must have been previously initialized with
* a call to @ref IotTaskPool_Create or @ref IotTaskPool_CreateSystemTaskPool.
* @param[in] maxThreads The maximum number of threads for the task pool.
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
* - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS
*
*/
/* @[declare_taskpool_setmaxthreads] */
IotTaskPoolError_t IotTaskPool_SetMaxThreads( IotTaskPool_t taskPool,
uint32_t maxThreads );
/* @[declare_taskpool_setmaxthreads] */
/**
* @brief Creates a job for the task pool around a user-provided storage.
*
* This function may allocate memory to hold the state for a job.
*
* @param[in] userCallback A user-specified callback for the job.
* @param[in] pUserContext A user-specified context for the callback.
* @param[in] pJobStorage The storage for the job data structure.
* @param[out] pJob A pointer to an instance of @ref IotTaskPoolJob_t that will be initialized when this
* function returns successfully. This handle can be used to inspect the job status with
* @ref IotTaskPool_GetStatus or cancel the job with @ref IotTaskPool_TryCancel, etc....
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
*
*
*/
/* @[declare_taskpool_createjob] */
IotTaskPoolError_t IotTaskPool_CreateJob( IotTaskPoolRoutine_t userCallback,
void * pUserContext,
IotTaskPoolJobStorage_t * const pJobStorage,
IotTaskPoolJob_t * const pJob );
/* @[declare_taskpool_createjob] */
/**
* brief Creates a job for the task pool by allocating the job dynamically.
*
* A recyclable job does not need to be allocated twice, but it can rather be reused through
* subsequent calls to @ref IotTaskPool_CreateRecyclableJob.
*
* @param[in] taskPool A handle to the task pool for which to create a recyclable job.
* @param[in] userCallback A user-specified callback for the job.
* @param[in] pUserContext A user-specified context for the callback.
* @param[out] pJob A pointer to an instance of @ref IotTaskPoolJob_t that will be initialized when this
* function returns successfully. This handle can be used to inspect the job status with
* @ref IotTaskPool_GetStatus or cancel the job with @ref IotTaskPool_TryCancel, etc....
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
* - #IOT_TASKPOOL_NO_MEMORY
* - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS
*
* @note This function will not allocate memory. //_RB_ Incorrect comment.
*
* @warning A recyclable job should be recycled with a call to @ref IotTaskPool_RecycleJob rather than destroyed.
*
*/
/* @[declare_taskpool_createrecyclablejob] */
IotTaskPoolError_t IotTaskPool_CreateRecyclableJob( IotTaskPool_t taskPool,
IotTaskPoolRoutine_t userCallback,
void * pUserContext,
IotTaskPoolJob_t * const pJob );
/* @[declare_taskpool_createrecyclablejob] */
/**
* @brief This function un-initializes a job.
*
* This function will destroy a job created with @ref IotTaskPool_CreateRecyclableJob.
* A job should not be destroyed twice. A job that was previously scheduled but has not completed yet should not be destroyed,
* but rather the application should attempt to cancel it first by calling @ref IotTaskPool_TryCancel.
* An attempt to destroy a job that was scheduled but not yet executed or canceled, may result in a
* @ref IOT_TASKPOOL_ILLEGAL_OPERATION error.
*
* @param[in] taskPool A handle to the task pool, e.g. as returned by a call to @ref IotTaskPool_Create or @ref IotTaskPool_CreateSystemTaskPool.
* @param[in] job A handle to a job that was create with a call to @ref IotTaskPool_CreateJob.
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
* - #IOT_TASKPOOL_ILLEGAL_OPERATION
* - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS
*
* @warning The task pool will try and prevent destroying jobs that are currently queued for execution, but does
* not enforce strict ordering of operations. It is up to the user to make sure @ref IotTaskPool_DestroyRecyclableJob is not called
* our of order.
*
* @warning Calling this function on job that was not previously created with @ref IotTaskPool_CreateRecyclableJob
* will result in a @ref IOT_TASKPOOL_ILLEGAL_OPERATION error.
*
*/
/* @[declare_taskpool_destroyrecyclablejob] */
IotTaskPoolError_t IotTaskPool_DestroyRecyclableJob( IotTaskPool_t taskPool,
IotTaskPoolJob_t job );
/* @[declare_taskpool_destroyrecyclablejob] */
/**
* @brief Recycles a job into the task pool job cache.
*
* This function will try and recycle the job into the task pool cache. If the cache is full,
* the job memory is destroyed as if the user called @ref IotTaskPool_DestroyRecyclableJob. The job should be recycled into
* the task pool instance from where it was allocated.
* Failure to do so will yield undefined results. A job should not be recycled twice. A job
* that was previously scheduled but not completed or canceled cannot be safely recycled. An attempt to do so will result
* in an @ref IOT_TASKPOOL_ILLEGAL_OPERATION error.
*
* @param[in] taskPool A handle to the task pool, e.g. as returned by a call to @ref IotTaskPool_Create.
* @param[out] job A pointer to a job that was create with a call to @ref IotTaskPool_CreateJob.
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
* - #IOT_TASKPOOL_ILLEGAL_OPERATION
* - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS
*
* @warning The `taskPool` used in this function should be the same
* used to create the job pointed to by `job`, or the results will be undefined.
*
* @warning Attempting to call this function on a statically allocated job will result in @ref IOT_TASKPOOL_ILLEGAL_OPERATION
* error.
*
* @warning This function should be used to recycle a job in the task pool cache when after the job executed.
* Failing to call either this function or @ref IotTaskPool_DestroyRecyclableJob will result is a memory leak. Statically
* allocated jobs do not need to be recycled or destroyed.
*
*/
/* @[declare_taskpool_recyclejob] */
IotTaskPoolError_t IotTaskPool_RecycleJob( IotTaskPool_t taskPool,
IotTaskPoolJob_t job );
/* @[declare_taskpool_recyclejob] */
/**
* @brief This function schedules a job created with @ref IotTaskPool_CreateJob or @ref IotTaskPool_CreateRecyclableJob
* against the task pool pointed to by `taskPool`.
*
* See @ref taskpool_design for a description of the jobs lifetime and interaction with the threads used in the task pool
* library.
*
* @param[in] taskPool A handle to the task pool that must have been previously initialized with.
* a call to @ref IotTaskPool_Create.
* @param[in] job A job to schedule for execution. This must be first initialized with a call to @ref IotTaskPool_CreateJob.
* @param[in] flags Flags to be passed by the user, e.g. to identify the job as high priority by specifying #IOT_TASKPOOL_JOB_HIGH_PRIORITY.
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
* - #IOT_TASKPOOL_ILLEGAL_OPERATION
* - #IOT_TASKPOOL_NO_MEMORY
* - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS
*
*
* @note This function will not allocate memory, so it is guaranteed to succeed if the paramters are correct and the task pool
* was correctly initialized, and not yet destroyed.
*
* @warning The `taskPool` used in this function should be the same used to create the job pointed to by `job`, or the
* results will be undefined.
*
* <b>Example</b>
* @code{c}
* // An example of a user context to pass to a callback through a task pool thread.
* typedef struct JobUserContext
* {
* uint32_t counter;
* } JobUserContext_t;
*
* // An example of a user callback to invoke through a task pool thread.
* static void ExecutionCb( IotTaskPool_t taskPool, IotTaskPoolJob_t job, void * context )
* {
* ( void )taskPool;
* ( void )job;
*
* JobUserContext_t * pUserContext = ( JobUserContext_t * )context;
*
* pUserContext->counter++;
* }
*
* void TaskPoolExample( )
* {
* JobUserContext_t userContext = { 0 };
* IotTaskPoolJob_t job;
* IotTaskPool_t taskPool;
*
* // Configure the task pool to hold at least two threads and three at the maximum.
* // Provide proper stack size and priority per the application needs.
*
* const IotTaskPoolInfo_t tpInfo = { .minThreads = 2, .maxThreads = 3, .stackSize = 512, .priority = 0 };
*
* // Create a task pool.
* IotTaskPool_Create( &tpInfo, &taskPool );
*
* // Statically allocate one job, schedule it.
* IotTaskPool_CreateJob( &ExecutionCb, &userContext, &job );
*
* IotTaskPoolError_t errorSchedule = IotTaskPool_Schedule( taskPool, &job, 0 );
*
* switch ( errorSchedule )
* {
* case IOT_TASKPOOL_SUCCESS:
* break;
* case IOT_TASKPOOL_BAD_PARAMETER: // Invalid parameters, such as a NULL handle, can trigger this error.
* case IOT_TASKPOOL_ILLEGAL_OPERATION: // Scheduling a job that was previously scheduled or destroyed could trigger this error.
* case IOT_TASKPOOL_NO_MEMORY: // Scheduling a with flag #IOT_TASKPOOL_JOB_HIGH_PRIORITY could trigger this error.
* case IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS: // Scheduling a job after trying to destroy the task pool could trigger this error.
* // ASSERT
* break;
* default:
* // ASSERT
* }
*
* //
* // ... Perform other operations ...
* //
*
* IotTaskPool_Destroy( taskPool );
* }
* @endcode
*/
/* @[declare_taskpool_schedule] */
IotTaskPoolError_t IotTaskPool_Schedule( IotTaskPool_t taskPool,
IotTaskPoolJob_t job,
uint32_t flags );
/* @[declare_taskpool_schedule] */
/**
* @brief This function schedules a job created with @ref IotTaskPool_CreateJob against the task pool
* pointed to by `taskPool` to be executed after a user-defined time interval.
*
* See @ref taskpool_design for a description of the jobs lifetime and interaction with the threads used in the task pool
* library.
*
* @param[in] taskPool A handle to the task pool that must have been previously initialized with.
* a call to @ref IotTaskPool_Create.
* @param[in] job A job to schedule for execution. This must be first initialized with a call to @ref IotTaskPool_CreateJob.
* @param[in] timeMs The time in milliseconds to wait before scheduling the job.
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
* - #IOT_TASKPOOL_ILLEGAL_OPERATION
* - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS
*
*
* @note This function will not allocate memory.
*
* @warning The `taskPool` used in this function should be the same
* used to create the job pointed to by `job`, or the results will be undefined.
*
*/
/* @[declare_taskpool_scheduledeferred] */
IotTaskPoolError_t IotTaskPool_ScheduleDeferred( IotTaskPool_t taskPool,
IotTaskPoolJob_t job,
uint32_t timeMs );
/* @[declare_taskpool_scheduledeferred] */
/**
* @brief This function retrieves the current status of a job.
*
* @param[in] taskPool A handle to the task pool that must have been previously initialized with
* a call to @ref IotTaskPool_Create or @ref IotTaskPool_CreateSystemTaskPool.
* @param[in] job The job to cancel.
* @param[out] pStatus The status of the job at the time of cancellation.
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
* - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS
*
* @warning This function is not thread safe and the job status returned in `pStatus` may be invalid by the time
* the calling thread has a chance to inspect it.
*/
/* @[declare_taskpool_getstatus] */
IotTaskPoolError_t IotTaskPool_GetStatus( IotTaskPool_t taskPool,
IotTaskPoolJob_t job,
IotTaskPoolJobStatus_t * const pStatus );
/* @[declare_taskpool_getstatus] */
/**
* @brief This function tries to cancel a job that was previously scheduled with @ref IotTaskPool_Schedule.
*
* A job can be canceled only if it is not yet executing, i.e. if its status is
* @ref IOT_TASKPOOL_STATUS_READY or @ref IOT_TASKPOOL_STATUS_SCHEDULED. Calling
* @ref IotTaskPool_TryCancel on a job whose status is @ref IOT_TASKPOOL_STATUS_COMPLETED,
* or #IOT_TASKPOOL_STATUS_CANCELED will yield a #IOT_TASKPOOL_CANCEL_FAILED return result.
*
* @param[in] taskPool A handle to the task pool that must have been previously initialized with
* a call to @ref IotTaskPool_Create.
* @param[in] job The job to cancel.
* @param[out] pStatus The status of the job at the time of cancellation.
*
* @return One of the following:
* - #IOT_TASKPOOL_SUCCESS
* - #IOT_TASKPOOL_BAD_PARAMETER
* - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS
* - #IOT_TASKPOOL_CANCEL_FAILED
*
* @warning The `taskPool` used in this function should be the same
* used to create the job pointed to by `job`, or the results will be undefined.
*
*/
/* @[declare_taskpool_trycancel] */
IotTaskPoolError_t IotTaskPool_TryCancel( IotTaskPool_t taskPool,
IotTaskPoolJob_t job,
IotTaskPoolJobStatus_t * const pStatus );
/* @[declare_taskpool_trycancel] */
/**
* @brief Returns a pointer to the job storage from an instance of a job handle
* of type @ref IotTaskPoolJob_t. This function is guaranteed to succeed for a
* valid job handle.
*
* @param[in] job The job handle.
*
* @return A pointer to the storage associated with the job handle `job`.
*
* @warning If the `job` handle used is invalid, the results will be undefined.
*/
/* @[declare_taskpool_getjobstoragefromhandle] */
IotTaskPoolJobStorage_t * IotTaskPool_GetJobStorageFromHandle( IotTaskPoolJob_t job );
/* @[declare_taskpool_getjobstoragefromhandle] */
/**
* @brief Returns a string that describes an @ref IotTaskPoolError_t.
*
* Like the POSIX's `strerror`, this function returns a string describing a
* return code. In this case, the return code is a task pool 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_taskpool_strerror] */
const char * IotTaskPool_strerror( IotTaskPoolError_t status );
/* @[declare_taskpool_strerror] */
/**
* @brief The maximum number of task pools to be created when using
* a memory pool.
*/
#ifndef IOT_TASKPOOLS
#define IOT_TASKPOOLS ( 4 )
#endif
/**
* @brief The maximum number of jobs to cache.
*/
#ifndef IOT_TASKPOOL_JOBS_RECYCLE_LIMIT
#define IOT_TASKPOOL_JOBS_RECYCLE_LIMIT ( 8UL )
#endif
/**
* @brief The maximum timeout in milliseconds to wait for a job to be scheduled before waking up a worker thread.
* A worker thread that wakes up as a result of a timeout may exit to allow the task pool to fold back to its
* minimum number of threads.
*/
#ifndef IOT_TASKPOOL_JOB_WAIT_TIMEOUT_MS
#define IOT_TASKPOOL_JOB_WAIT_TIMEOUT_MS ( 60 * 1000UL )
#endif
#endif /* ifndef IOT_TASKPOOL_H_ */

View file

@ -0,0 +1,117 @@
/*
* Amazon FreeRTOS Common V1.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_error.h
* @brief Provides macros for error checking and function cleanup.
*
* The macros in this file are generic. They may be customized by each library
* by setting the library prefix.
*/
#ifndef IOT_ERROR_H_
#define IOT_ERROR_H_
/* The config header is always included first. */
#include "iot_config.h"
/**
* @brief Declare the status variable and an initial value.
*
* This macro should be at the beginning of any functions that use cleanup sections.
*
* @param[in] statusType The type of the status variable for this function.
* @param[in] initialValue The initial value to assign to the status variable.
*/
#define IOT_FUNCTION_ENTRY( statusType, initialValue ) statusType status = initialValue
/**
* @brief Declares the label that begins a cleanup section.
*
* This macro should be placed at the end of a function and followed by
* #IOT_FUNCTION_CLEANUP_END.
*/
#define IOT_FUNCTION_CLEANUP_BEGIN() iotCleanup:
/**
* @brief Declares the end of a cleanup section.
*
* This macro should be placed at the end of a function and preceded by
* #IOT_FUNCTION_CLEANUP_BEGIN.
*/
#define IOT_FUNCTION_CLEANUP_END() return status
/**
* @brief Declares an empty cleanup section.
*
* This macro should be placed at the end of a function to exit on error if no
* cleanup is required.
*/
#define IOT_FUNCTION_EXIT_NO_CLEANUP() IOT_FUNCTION_CLEANUP_BEGIN(); IOT_FUNCTION_CLEANUP_END()
/**
* @brief Jump to the cleanup section.
*/
#define IOT_GOTO_CLEANUP() goto iotCleanup
/**
* @brief Assign a value to the status variable and jump to the cleanup section.
*
* @param[in] statusValue The value to assign to the status variable.
*/
#define IOT_SET_AND_GOTO_CLEANUP( statusValue ) { status = ( statusValue ); IOT_GOTO_CLEANUP(); }
/**
* @brief Jump to the cleanup section if a condition is `false`.
*
* This macro may be used in place of `assert` to exit a function is a condition
* is `false`.
*
* @param[in] condition The condition to check.
*/
#define IOT_GOTO_CLEANUP_IF_FALSE( condition ) { if( ( condition ) == false ) { IOT_GOTO_CLEANUP(); } }
/**
* @brief Assign a value to the status variable and jump to the cleanup section
* if a condition is `false`.
*
* @param[in] statusValue The value to assign to the status variable.
* @param[in] condition The condition to check.
*/
#define IOT_SET_AND_GOTO_CLEANUP_IF_FALSE( statusValue, condition ) \
if( ( condition ) == false ) \
IOT_SET_AND_GOTO_CLEANUP( statusValue )
/**
* @brief Check a condition; if `false`, assign the "Bad parameter" status value
* and jump to the cleanup section.
*
* @param[in] libraryPrefix The library prefix of the status variable.
* @param[in] condition The condition to check.
*/
#define IOT_VALIDATE_PARAMETER( libraryPrefix, condition ) \
IOT_SET_AND_GOTO_CLEANUP_IF_FALSE( libraryPrefix ## _BAD_PARAMETER, condition )
#endif /* ifndef IOT_ERROR_H_ */

View file

@ -0,0 +1,33 @@
/*
* Amazon FreeRTOS Common V1.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
*/
#ifndef _AWS_LIB_INIT_H_
#define _AWS_LIB_INIT_H_
#include "FreeRTOS.h"
#define lib_initDECLARE_LIB_INIT( f ) extern BaseType_t f( void )
#endif /* _AWS_LIB_INIT_H_ */

View file

@ -0,0 +1,229 @@
/*
* Amazon FreeRTOS Common V1.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_logging.h
* @brief Generic logging function header file.
*
* Declares the generic logging function and the log levels. This file never
* needs to be included in source code. The header iot_logging_setup.h should
* be included instead.
*
* @see iot_logging_setup.h
*/
#ifndef IOT_LOGGING_H_
#define IOT_LOGGING_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/**
* @constantspage{logging,logging library}
*
* @section logging_constants_levels Log levels
* @brief Log levels for the libraries in this SDK.
*
* Each library should specify a log level by setting @ref LIBRARY_LOG_LEVEL.
* All log messages with a level at or below the specified level will be printed
* for that library.
*
* Currently, there are 4 log levels. In the order of lowest to highest, they are:
* - #IOT_LOG_NONE <br>
* @copybrief IOT_LOG_NONE
* - #IOT_LOG_ERROR <br>
* @copybrief IOT_LOG_ERROR
* - #IOT_LOG_WARN <br>
* @copybrief IOT_LOG_WARN
* - #IOT_LOG_INFO <br>
* @copybrief IOT_LOG_INFO
* - #IOT_LOG_DEBUG <br>
* @copybrief IOT_LOG_DEBUG
*/
/**
* @brief No log messages.
*
* Log messages with this level will be silently discarded. When @ref
* LIBRARY_LOG_LEVEL is #IOT_LOG_NONE, logging is disabled and no [logging functions]
* (@ref logging_functions) can be called.
*/
#define IOT_LOG_NONE 0
/**
* @brief Only critical, unrecoverable errors.
*
* Log messages with this level will be printed when a library encounters an
* error from which it cannot easily recover.
*/
#define IOT_LOG_ERROR 1
/**
* @brief Message about an abnormal but recoverable event.
*
* Log messages with this level will be printed when a library encounters an
* abnormal event that may be indicative of an error. Libraries should continue
* execution after logging a warning.
*/
#define IOT_LOG_WARN 2
/**
* @brief A helpful, informational message.
*
* Log messages with this level may indicate the normal status of a library
* function. They should be used to track how far a program has executed.
*/
#define IOT_LOG_INFO 3
/**
* @brief Detailed and excessive debug information.
*
* Log messages with this level are intended for developers. They may contain
* excessive information such as internal variables, buffers, or other specific
* information.
*/
#define IOT_LOG_DEBUG 4
/**
* @paramstructs{logging,logging}
*/
/**
* @ingroup logging_datatypes_paramstructs
* @brief Log message configuration struct.
*
* @paramfor @ref logging_function_log, @ref logging_function_generic
*
* By default, log messages print the library name, log level, and a timestring.
* This struct can be passed to @ref logging_function_generic to disable one of
* the above components in the log message.
*
* <b>Example:</b>
*
* @code{c}
* IotLog_Generic( IOT_LOG_DEBUG, "SAMPLE", IOT_LOG_DEBUG, NULL, "Hello world!" );
* @endcode
* The code above prints the following message:
* @code
* [DEBUG][SAMPLE][2018-01-01 12:00:00] Hello world!
* @endcode
*
* The timestring can be disabled as follows:
* @code
* IotLogConfig_t logConfig = { .hideLogLevel = false, .hideLibraryName = false, .hideTimestring = true};
* IotLog_Generic( IOT_LOG_DEBUG, "SAMPLE", IOT_LOG_DEBUG, &logConfig, "Hello world!" );
* @endcode
* The resulting log message will be:
* @code
* [DEBUG][SAMPLE] Hello world!
* @endcode
*/
typedef struct IotLogConfig
{
bool hideLogLevel; /**< @brief Don't print the log level string for this message. */
bool hideLibraryName; /**< @brief Don't print the library name for this message. */
bool hideTimestring; /**< @brief Don't print the timestring for this message. */
} IotLogConfig_t;
/**
* @functionspage{logging,logging library}
*
* - @functionname{logging_function_log}
* - @functionname{logging_function_printbuffer}
* - @functionname{logging_function_generic}
* - @functionname{logging_function_genericprintbuffer}
*/
/**
* @functionpage{IotLog_Generic,logging,generic}
* @functionpage{IotLog_PrintBuffer,logging,genericprintbuffer}
*/
/**
* @brief Generic logging function that prints a single message.
*
* This function is the generic logging function shared across all libraries.
* The library-specific logging function @ref logging_function_log is implemented
* using this function. Like @ref logging_function_log, this function is only
* available when @ref LIBRARY_LOG_LEVEL is #IOT_LOG_NONE.
*
* In most cases, the library-specific logging function @ref logging_function_log
* should be called instead of this function.
*
* @param[in] libraryLogSetting The log level setting of the library, used to
* determine if the log message should be printed. Must be one of the @ref
* logging_constants_levels.
* @param[in] pLibraryName The library name to print. See @ref LIBRARY_LOG_NAME.
* @param[in] messageLevel The log level of the this message. See @ref LIBRARY_LOG_LEVEL.
* @param[in] pLogConfig Pointer to a #IotLogConfig_t. Optional; pass `NULL` to ignore.
* @param[in] pFormat Format string for the log message.
* @param[in] ... Arguments for format specification.
*
* @return No return value. On errors, it prints nothing.
*/
/* @[declare_logging_generic] */
void IotLog_Generic( int libraryLogSetting,
const char * const pLibraryName,
int messageLevel,
const IotLogConfig_t * const pLogConfig,
const char * const pFormat,
... );
/* @[declare_logging_generic] */
/**
* @brief Generic function to log the contents of a buffer as bytes.
*
* This function is the generic buffer logging function shared across all libraries.
* The library-specific buffer logging function @ref logging_function_printbuffer is
* implemented using this function. Like @ref logging_function_printbuffer, this
* function is only available when @ref LIBRARY_LOG_LEVEL is #IOT_LOG_DEBUG.
*
* In most cases, the library-specific buffer logging function @ref
* logging_function_printbuffer should be called instead of this function.
*
* @param[in] pLibraryName The library name to print with the log. See @ref LIBRARY_LOG_NAME.
* @param[in] pHeader A message to print before printing the buffer.
* @param[in] pBuffer The buffer to print.
* @param[in] bufferSize The number of bytes in `pBuffer` to print.
*
* @return No return value. On errors, it prints nothing.
*
* @note To conserve memory, this function only allocates enough memory for a
* single line of output. Therefore, in multithreaded systems, its output may
* appear "fragmented" if other threads are logging simultaneously.
*/
/* @[declare_logging_genericprintbuffer] */
void IotLog_GenericPrintBuffer( const char * const pLibraryName,
const char * const pHeader,
const uint8_t * const pBuffer,
size_t bufferSize );
/* @[declare_logging_genericprintbuffer] */
#endif /* ifndef IOT_LOGGING_H_ */

View file

@ -0,0 +1,250 @@
/*
* Amazon FreeRTOS Common V1.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_static_memory.h
* @brief Common functions for managing static buffers. Only used when
* @ref IOT_STATIC_MEMORY_ONLY is `1`.
*/
/* The config header is always included first. */
#include "iot_config.h"
/* The functions in this file should only exist in static memory only mode, hence
* the check for IOT_STATIC_MEMORY_ONLY in the double inclusion guard. */
#if !defined( IOT_STATIC_MEMORY_H_ ) && ( IOT_STATIC_MEMORY_ONLY == 1 )
#define IOT_STATIC_MEMORY_H_
/* Standard includes. */
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/**
* @functionspage{static_memory,static memory component}
* - @functionname{static_memory_function_init}
* - @functionname{static_memory_function_cleanup}
* - @functionname{static_memory_function_findfree}
* - @functionname{static_memory_function_returninuse}
* - @functionname{static_memory_function_messagebuffersize}
* - @functionname{static_memory_function_mallocmessagebuffer}
* - @functionname{static_memory_function_freemessagebuffer}
*/
/*----------------------- Initialization and cleanup ------------------------*/
/**
* @functionpage{IotStaticMemory_Init,static_memory,init}
* @functionpage{IotStaticMemory_Cleanup,static_memory,cleanup}
*/
/**
* @brief One-time initialization function for static memory.
*
* This function performs internal setup of static memory. <b>It must be called
* once (and only once) before calling any other static memory function.</b>
* Calling this function more than once without first calling
* @ref static_memory_function_cleanup may result in a crash.
*
* @return `true` if initialization succeeded; `false` otherwise.
*
* @attention This function is called by `IotSdk_Init` and does not need to be
* called by itself.
*
* @warning No thread-safety guarantees are provided for this function.
*
* @see static_memory_function_cleanup
*/
/* @[declare_static_memory_init] */
bool IotStaticMemory_Init( void );
/* @[declare_static_memory_init] */
/**
* @brief One-time deinitialization function for static memory.
*
* This function frees resources taken in @ref static_memory_function_init.
* It should be called after to clean up static memory. After this function
* returns, @ref static_memory_function_init must be called again before
* calling any other static memory function.
*
* @attention This function is called by `IotSdk_Cleanup` and does not need
* to be called by itself.
*
* @warning No thread-safety guarantees are provided for this function.
*
* @see static_memory_function_init
*/
/* @[declare_static_memory_cleanup] */
void IotStaticMemory_Cleanup( void );
/* @[declare_static_memory_cleanup] */
/*------------------------- Buffer allocation and free ----------------------*/
/**
* @functionpage{IotStaticMemory_FindFree,static_memory,findfree}
* @functionpage{IotStaticMemory_ReturnInUse,static_memory,returninuse}
*/
/**
* @brief Find a free buffer using the "in-use" flags.
*
* If a free buffer is found, this function marks the buffer in-use. This function
* is common to the static memory implementation.
*
* @param[in] pInUse The "in-use" flags to search.
* @param[in] limit How many flags to check, i.e. the size of `pInUse`.
*
* @return The index of a free buffer; `-1` if no free buffers are available.
*
* <b>Example</b>:
* @code{c}
* // To use this function, first declare two arrays. One provides the statically-allocated
* // objects, the other provides flags to determine which objects are in-use.
* #define NUMBER_OF_OBJECTS ...
* #define OBJECT_SIZE ...
* static bool _pInUseObjects[ NUMBER_OF_OBJECTS ] = { 0 };
* static uint8_t _pObjects[ NUMBER_OF_OBJECTS ][ OBJECT_SIZE ] = { { 0 } }; // Placeholder for objects.
*
* // The function to statically allocate objects. Must have the same signature
* // as malloc().
* void * Iot_MallocObject( size_t size )
* {
* int32_t freeIndex = -1;
* void * pNewObject = NULL;
*
* // Check that sizes match.
* if( size != OBJECT_SIZE )
* {
* // Get the index of a free object.
* freeIndex = IotStaticMemory_FindFree( _pInUseMessageBuffers,
* IOT_MESSAGE_BUFFERS );
*
* if( freeIndex != -1 )
* {
* pNewBuffer = &( _pMessageBuffers[ freeIndex ][ 0 ] );
* }
* }
*
* return pNewBuffer;
* }
* @endcode
*/
/* @[declare_static_memory_findfree] */
int32_t IotStaticMemory_FindFree( bool * pInUse,
size_t limit );
/* @[declare_static_memory_findfree] */
/**
* @brief Return an "in-use" buffer.
*
* This function is common to the static memory implementation.
*
* @param[in] ptr Pointer to the buffer to return.
* @param[in] pPool The pool of buffers that the in-use buffer was allocated from.
* @param[in] pInUse The "in-use" flags for pPool.
* @param[in] limit How many buffers (and flags) to check while searching for ptr.
* @param[in] elementSize The size of a single element in pPool.
*
* <b>Example</b>:
* @code{c}
* // To use this function, first declare two arrays. One provides the statically-allocated
* // objects, the other provides flags to determine which objects are in-use.
* #define NUMBER_OF_OBJECTS ...
* #define OBJECT_SIZE ...
* static bool _pInUseObjects[ NUMBER_OF_OBJECTS ] = { 0 };
* static uint8_t _pObjects[ NUMBER_OF_OBJECTS ][ OBJECT_SIZE ] = { { 0 } }; // Placeholder for objects.
*
* // The function to free statically-allocated objects. Must have the same signature
* // as free().
* void Iot_FreeObject( void * ptr )
* {
* IotStaticMemory_ReturnInUse( ptr,
* _pObjects,
* _pInUseObjects,
* NUMBER_OF_OBJECTS,
* OBJECT_SIZE );
* }
* @endcode
*/
/* @[declare_static_memory_returninuse] */
void IotStaticMemory_ReturnInUse( void * ptr,
void * pPool,
bool * pInUse,
size_t limit,
size_t elementSize );
/* @[declare_static_memory_returninuse] */
/*------------------------ Message buffer management ------------------------*/
/**
* @functionpage{Iot_MessageBufferSize,static_memory,messagebuffersize}
* @functionpage{Iot_MallocMessageBuffer,static_memory,mallocmessagebuffer}
* @functionpage{Iot_FreeMessageBuffer,static_memory,freemessagebuffer}
*/
/**
* @brief Get the fixed size of a message buffer.
*
* The size of the message buffers are known at compile time, but it is a [constant]
* (@ref IOT_MESSAGE_BUFFER_SIZE) that may not be visible to all source files.
* This function allows other source files to know the size of a message buffer.
*
* @return The size, in bytes, of a single message buffer.
*/
/* @[declare_static_memory_messagebuffersize] */
size_t Iot_MessageBufferSize( void );
/* @[declare_static_memory_messagebuffersize] */
/**
* @brief Get an empty message buffer.
*
* This function is the analog of [malloc]
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html)
* for message buffers.
*
* @param[in] size Requested size for a message buffer.
*
* @return Pointer to the start of a message buffer. If the `size` argument is larger
* than the [fixed size of a message buffer](@ref IOT_MESSAGE_BUFFER_SIZE)
* or no message buffers are available, `NULL` is returned.
*/
/* @[declare_static_memory_mallocmessagebuffer] */
void * Iot_MallocMessageBuffer( size_t size );
/* @[declare_static_memory_mallocmessagebuffer] */
/**
* @brief Free an in-use message buffer.
*
* This function is the analog of [free]
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html)
* for message buffers.
*
* @param[in] ptr Pointer to the message buffer to free.
*/
/* @[declare_static_memory_freemessagebuffer] */
void Iot_FreeMessageBuffer( void * ptr );
/* @[declare_static_memory_freemessagebuffer] */
#endif /* if !defined( IOT_STATIC_MEMORY_H_ ) && ( IOT_STATIC_MEMORY_ONLY == 1 ) */

View file

@ -0,0 +1,293 @@
/*
* Amazon FreeRTOS Common V1.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_taskpool_internal.h
* @brief Internal header of task pool library. This header should not be included in
* typical application code.
*/
#ifndef IOT_TASKPOOL_INTERNAL_H_
#define IOT_TASKPOOL_INTERNAL_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Task pool include. */
#include "private/iot_error.h"
#include "iot_taskpool.h"
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "semphr.h"
#include "timers.h"
/* Establish a few convenience macros to handle errors in a standard way. */
/**
* @brief Every public API return an enumeration value with an undelying value of 0 in case of success.
*/
#define TASKPOOL_SUCCEEDED( x ) ( ( x ) == IOT_TASKPOOL_SUCCESS )
/**
* @brief Every public API returns an enumeration value with an undelying value different than 0 in case of success.
*/
#define TASKPOOL_FAILED( x ) ( ( x ) != IOT_TASKPOOL_SUCCESS )
/**
* @brief Jump to the cleanup area.
*/
#define TASKPOOL_GOTO_CLEANUP() IOT_GOTO_CLEANUP()
/**
* @brief Declare the storage for the error status variable.
*/
#define TASKPOOL_FUNCTION_ENTRY( result ) IOT_FUNCTION_ENTRY( IotTaskPoolError_t, result )
/**
* @brief Check error and leave in case of failure.
*/
#define TASKPOOL_ON_ERROR_GOTO_CLEANUP( expr ) \
{ if( TASKPOOL_FAILED( status = ( expr ) ) ) { IOT_GOTO_CLEANUP(); } \
}
/**
* @brief Exit if an argument is NULL.
*/
#define TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( ptr ) IOT_VALIDATE_PARAMETER( IOT_TASKPOOL, ( ptr != NULL ) )
/**
* @brief Exit if an argument is NULL.
*/
#define TASKPOOL_ON_ARG_ERROR_GOTO_CLEANUP( expr ) IOT_VALIDATE_PARAMETER( IOT_TASKPOOL, ( ( expr ) == false ) )
/**
* @brief Set error and leave.
*/
#define TASKPOOL_SET_AND_GOTO_CLEANUP( expr ) IOT_SET_AND_GOTO_CLEANUP( expr )
/**
* @brief Initialize error and declare start of cleanup area.
*/
#define TASKPOOL_FUNCTION_CLEANUP() IOT_FUNCTION_CLEANUP_BEGIN()
/**
* @brief Initialize error and declare end of cleanup area.
*/
#define TASKPOOL_FUNCTION_CLEANUP_END() IOT_FUNCTION_CLEANUP_END()
/**
* @brief Create an empty cleanup area.
*/
#define TASKPOOL_NO_FUNCTION_CLEANUP() IOT_FUNCTION_EXIT_NO_CLEANUP()
/**
* @brief Does not create a cleanup area.
*/
#define TASKPOOL_NO_FUNCTION_CLEANUP_NOLABEL() return status
/**
* @def IotTaskPool_Assert( expression )
* @brief Assertion macro for the Task pool library.
*
* Set @ref IOT_TASKPOOL_ENABLE_ASSERTS to `1` to enable assertions in the Task pool
* library.
*
* @param[in] expression Expression to be evaluated.
*/
#if IOT_TASKPOOL_ENABLE_ASSERTS == 1
#ifndef IotTaskPool_Assert
#include <assert.h>
#define IotTaskPool_Assert( expression ) assert( expression )
#endif
#else
#define IotTaskPool_Assert( expression )
#endif
/* Configure logs for TASKPOOL functions. */
#ifdef IOT_LOG_LEVEL_TASKPOOL
#define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_TASKPOOL
#else
#ifdef IOT_LOG_LEVEL_GLOBAL
#define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_GLOBAL
#else
#define LIBRARY_LOG_LEVEL IOT_LOG_NONE
#endif
#endif
#define LIBRARY_LOG_NAME ( "TASKPOOL" )
#include "iot_logging_setup.h"
/*
* Provide default values for undefined memory allocation functions based on
* the usage of dynamic memory allocation.
*/
#if IOT_STATIC_MEMORY_ONLY == 1
#include "private/iot_static_memory.h"
/**
* @brief Allocate an #_taskPool_t. This function should have the
* same signature as [malloc].
*/
void * IotTaskPool_MallocTaskPool( size_t size );
/**
* @brief Free an #_taskPool_t. This function should have the
* same signature as [malloc].
*/
void IotTaskPool_FreeTaskPool( void * ptr );
/**
* @brief Allocate an #IotTaskPoolJob_t. This function should have the
* same signature as [malloc].
*/
void * IotTaskPool_MallocJob( size_t size );
/**
* @brief Free an #IotTaskPoolJob_t. This function should have the same
* same signature as [malloc].
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html).
*/
void IotTaskPool_FreeJob( void * ptr );
/**
* @brief Allocate an #_taskPoolTimerEvent_t. This function should have the
* same signature as [malloc].
*/
void * IotTaskPool_MallocTimerEvent( size_t size );
/**
* @brief Free an #_taskPoolTimerEvent_t. This function should have the
* same signature as[ free ].
*/
void IotTaskPool_FreeTimerEvent( void * ptr );
#else /* if IOT_STATIC_MEMORY_ONLY == 1 */
#include <stdlib.h>
#ifndef IotTaskPool_MallocTaskPool
#define IotTaskPool_MallocTaskPool malloc
#endif
#ifndef IotTaskPool_FreeTaskPool
#define IotTaskPool_FreeTaskPool free
#endif
#ifndef IotTaskPool_MallocJob
#define IotTaskPool_MallocJob malloc
#endif
#ifndef IotTaskPool_FreeJob
#define IotTaskPool_FreeJob free
#endif
#ifndef IotTaskPool_MallocTimerEvent
#define IotTaskPool_MallocTimerEvent malloc
#endif
#ifndef IotTaskPool_FreeTimerEvent
#define IotTaskPool_FreeTimerEvent free
#endif
#endif /* if IOT_STATIC_MEMORY_ONLY == 1 */
/* ---------------------------------------------------------------------------------------------- */
/**
* @cond DOXYGEN_IGNORE
* Doxygen should ignore this section.
*
* A macros to manage task pool memory allocation.
*/
#define IOT_TASK_POOL_INTERNAL_STATIC ( ( uint32_t ) 0x00000001 ) /* Flag to mark a job as user-allocated. */
/** @endcond */
/**
* @brief Task pool jobs cache.
*
* @warning This is a system-level data type that should not be modified or used directly in any application.
* @warning This is a system-level data type that can and will change across different versions of the platform, with no regards for backward compatibility.
*
*/
typedef struct _taskPoolCache
{
IotListDouble_t freeList; /**< @brief A list ot hold cached jobs. */
uint32_t freeCount; /**< @brief A counter to track the number of jobs in the cache. */
} _taskPoolCache_t;
/**
* @brief The task pool data structure keeps track of the internal state and the signals for the dispatcher threads.
* The task pool is a thread safe data structure.
*
* @warning This is a system-level data type that should not be modified or used directly in any application.
* @warning This is a system-level data type that can and will change across different versions of the platform, with no regards for backward compatibility.
*
*/
typedef struct _taskPool
{
IotDeQueue_t dispatchQueue; /**< @brief The queue for the jobs waiting to be executed. */
IotListDouble_t timerEventsList; /**< @brief The timeouts queue for all deferred jobs waiting to be executed. */
_taskPoolCache_t jobsCache; /**< @brief A cache to re-use jobs in order to limit memory allocations. */
uint32_t activeThreads; /**< @brief The number of threads in the task pool at any given time. */
int32_t priority; /**< @brief The priority for all task pool threads. */
SemaphoreHandle_t dispatchSignal; /**< @brief The synchronization object on which threads are waiting for incoming jobs. */
StaticSemaphore_t dispatchSignalBuffer; /**< @brief The semaphore buffer. */
StaticSemaphore_t startStopSignalBuffer; /**< @brief The semaphore buffer. */
TimerHandle_t timer; /**< @brief The timer for deferred jobs. */
StaticTimer_t timerBuffer; /**< @brief The timer buffer. */
bool running; /**< @brief A flag to track whether the task pool is operational or should shut down. */
} _taskPool_t;
/**
* @brief The job data structure keeps track of the user callback and context, as well as the status of the job.
*
* @warning This is a system-level data type that should not be modified or used directly in any application.
* @warning This is a system-level data type that can and will change across different versions of the platform, with no regards for backward compatibility.
*
*/
typedef struct _taskPoolJob
{
IotLink_t link; /**< @brief The link to insert the job in the dispatch queue. */
IotTaskPoolRoutine_t userCallback; /**< @brief The user provided callback. */
void * pUserContext; /**< @brief The user provided context. */
uint32_t flags; /**< @brief Internal flags. */
IotTaskPoolJobStatus_t status; /**< @brief The status for the job. */
} _taskPoolJob_t;
/**
* @brief Represents an operation that is subject to a timer.
*
* These events are queued per MQTT connection. They are sorted by their
* expiration time.
*/
typedef struct _taskPoolTimerEvent
{
IotLink_t link; /**< @brief List link member. */
TickType_t expirationTime; /**< @brief When this event should be processed. */
IotTaskPoolJob_t job; /**< @brief The task pool job associated with this event. */
} _taskPoolTimerEvent_t;
#endif /* ifndef IOT_TASKPOOL_INTERNAL_H_ */

View file

@ -0,0 +1,362 @@
/*
* Amazon FreeRTOS Common V1.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_taskpool_types.h
* @brief Types of the task pool.
*/
#ifndef IOT_TASKPOOL_TYPES_H_
#define IOT_TASKPOOL_TYPES_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdbool.h>
#include <stdint.h>
/* Platform types includes. */
#include "types/iot_platform_types.h"
/* Linear containers (lists and queues) include. */
#include "iot_linear_containers.h"
/*-------------------------- Task pool enumerated types --------------------------*/
/**
* @ingroup taskpool_datatypes_enums
* @brief Return codes of [task pool functions](@ref taskpool_functions).
*/
typedef enum IotTaskPoolError
{
/**
* @brief Task pool operation completed successfully.
*
* Functions that may return this value:
* - @ref taskpool_function_createsystemtaskpool
* - @ref taskpool_function_create
* - @ref taskpool_function_destroy
* - @ref taskpool_function_setmaxthreads
* - @ref taskpool_function_createjob
* - @ref taskpool_function_createrecyclablejob
* - @ref taskpool_function_destroyrecyclablejob
* - @ref taskpool_function_recyclejob
* - @ref taskpool_function_schedule
* - @ref taskpool_function_scheduledeferred
* - @ref taskpool_function_getstatus
* - @ref taskpool_function_trycancel
*
*/
IOT_TASKPOOL_SUCCESS = 0,
/**
* @brief Task pool operation failed because at least one parameter is invalid.
*
* Functions that may return this value:
* - @ref taskpool_function_createsystemtaskpool
* - @ref taskpool_function_create
* - @ref taskpool_function_destroy
* - @ref taskpool_function_setmaxthreads
* - @ref taskpool_function_createjob
* - @ref taskpool_function_createrecyclablejob
* - @ref taskpool_function_destroyrecyclablejob
* - @ref taskpool_function_recyclejob
* - @ref taskpool_function_schedule
* - @ref taskpool_function_scheduledeferred
* - @ref taskpool_function_getstatus
* - @ref taskpool_function_trycancel
*
*/
IOT_TASKPOOL_BAD_PARAMETER,
/**
* @brief Task pool operation failed because it is illegal.
*
* Functions that may return this value:
* - @ref taskpool_function_createjob
* - @ref taskpool_function_createrecyclablejob
* - @ref taskpool_function_destroyrecyclablejob
* - @ref taskpool_function_recyclejob
* - @ref taskpool_function_schedule
* - @ref taskpool_function_scheduledeferred
* - @ref taskpool_function_trycancel
*
*/
IOT_TASKPOOL_ILLEGAL_OPERATION,
/**
* @brief Task pool operation failed because allocating memory failed.
*
* Functions that may return this value:
* - @ref taskpool_function_createsystemtaskpool
* - @ref taskpool_function_create
* - @ref taskpool_function_setmaxthreads
* - @ref taskpool_function_createrecyclablejob
* - @ref taskpool_function_scheduledeferred
* - @ref taskpool_function_getstatus
*
*/
IOT_TASKPOOL_NO_MEMORY,
/**
* @brief Task pool operation failed because of an invalid parameter.
*
* Functions that may return this value:
* - @ref taskpool_function_setmaxthreads
* - @ref taskpool_function_createrecyclablejob
* - @ref taskpool_function_destroyrecyclablejob
* - @ref taskpool_function_recyclejob
* - @ref taskpool_function_schedule
* - @ref taskpool_function_scheduledeferred
* - @ref taskpool_function_getstatus
* - @ref taskpool_function_trycancel
*
*/
IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS,
/**
* @brief Task pool cancellation failed.
*
* Functions that may return this value:
* - @ref taskpool_function_trycancel
*
*/
IOT_TASKPOOL_CANCEL_FAILED,
} IotTaskPoolError_t;
/**
* @enums{taskpool,Task pool library}
*/
/**
* @ingroup taskpool_datatypes_enums
* @brief Status codes of [task pool Job](@ref IotTaskPoolJob_t).
*
*/
typedef enum IotTaskPoolJobStatus
{
/**
* @brief Job is ready to be scheduled.
*
*/
IOT_TASKPOOL_STATUS_READY = 0,
/**
* @brief Job has been queued for execution.
*
*/
IOT_TASKPOOL_STATUS_SCHEDULED,
/**
* @brief Job has been scheduled for deferred execution.
*
*/
IOT_TASKPOOL_STATUS_DEFERRED,
/**
* @brief Job is executing.
*
*/
IOT_TASKPOOL_STATUS_COMPLETED,
/**
* @brief Job has been canceled before executing.
*
*/
IOT_TASKPOOL_STATUS_CANCELED,
/**
* @brief Job status is undefined.
*
*/
IOT_TASKPOOL_STATUS_UNDEFINED,
} IotTaskPoolJobStatus_t;
/*------------------------- Task pool types and handles --------------------------*/
/**
* @ingroup taskpool_datatypes_handles
* @brief Opaque handle of a Task Pool instance.
*
* This type identifies a Task Pool instance, which is valid after a successful call
* to @ref taskpool_function_createsystemtaskpool or @ref taskpool_function_create. A
* variable of this type is passed as the first
* argument to [Task Pool library functions](@ref taskpool_functions) to identify which
* task pool that function acts on.
*
* A call to @ref taskpool_function_destroy makes a task pool handle invalid. Once
* @ref taskpool_function_destroy returns, the task handle should no longer
* be used.
*
* @initializer{IotTaskPool_t,IOT_TASKPOOL_INITIALIZER}
*/
typedef struct _taskPool * IotTaskPool_t;
/**
* @ingroup taskpool_datatypes_structs
* @brief The job storage data structure provides the storage for a statically allocated Task Pool Job instance.
*
* @warning This is a system-level data type that should not be modified or used directly in any application.
* @warning This is a system-level data type that can and will change across different versions of the platform, with no regards for backward compatibility.
*
*/
typedef struct IotTaskPoolJobStorage
{
IotLink_t link; /**< @brief Placeholder. */
void * dummy2; /**< @brief Placeholder. */
void * dummy3; /**< @brief Placeholder. */
uint32_t dummy4; /**< @brief Placeholder. */
IotTaskPoolJobStatus_t status; /**< @brief Placeholder. */
} IotTaskPoolJobStorage_t;
/**
* @ingroup taskpool_datatypes_handles
* @brief Opaque handle of a Task Pool Job.
*
* This type identifies a Task Pool Job instance, which is valid after a successful call
* to @ref taskpool_function_createjob or @ref taskpool_function_createrecyclablejob.
*
* A call to @ref taskpool_function_recyclejob or @ref taskpool_function_destroyrecyclablejob makes a
* task pool job handle invalid. Once @ref taskpool_function_recyclejob or
* @ref taskpool_function_destroyrecyclablejob returns, the task job handle should no longer be used.
*
* @initializer{IotTaskPoolJob_t,IOT_TASKPOOL_JOB_INITIALIZER}
*
*/
typedef struct _taskPoolJob * IotTaskPoolJob_t;
/*------------------------- Task pool parameter structs --------------------------*/
/**
* @ingroup taskpool_datatypes_functionpointers
* @brief Callback type for a user callback.
*
* This type identifies the user callback signature to execute a task pool job. This callback will be invoked
* by the task pool threads with the `pUserContext` parameter, as specified by the user when
* calling @ref IotTaskPool_Schedule.
*
*/
typedef void ( * IotTaskPoolRoutine_t )( IotTaskPool_t pTaskPool,
IotTaskPoolJob_t pJob,
void * pUserContext );
/**
* @ingroup taskpool_datatypes_paramstructs
* @brief Initialization information to create one task pool instance.
*
* @paramfor @ref taskpool_function_createsystemtaskpool @ref taskpool_function_create.
*
* Passed as an argument to @ref taskpool_function_create.
*
* @initializer{IotTaskPoolInfo_t,IOT_TASKPOOL_INFO_INITIALIZER}
*/
typedef struct IotTaskPoolInfo
{
/**
* @brief Specifies the operating parameters for a task pool.
*
* @attention #IotTaskPoolInfo_t.minThreads <b>MUST</b> be at least 1.
* #IotTaskPoolInfo_t.maxThreads <b>MUST</b> be greater or equal to #IotTaskPoolInfo_t.minThreads.
* If the minimum number of threads is same as the maximum, then the task pool will not try and grow the
* number of worker threads at run time.
*/
uint32_t minThreads; /**< @brief Minimum number of threads in a task pool. These threads will be created when the task pool is first created with @ref taskpool_function_create. */
uint32_t maxThreads; /**< @brief Maximum number of threads in a task pool. A task pool may try and grow the number of active threads up to #IotTaskPoolInfo_t.maxThreads. */
uint32_t stackSize; /**< @brief Stack size for every task pool thread. The stack size for each thread is fixed after the task pool is created and cannot be changed. */
int32_t priority; /**< @brief priority for every task pool thread. The priority for each thread is fixed after the task pool is created and cannot be changed. */
} IotTaskPoolInfo_t;
/*------------------------- TASKPOOL defined constants --------------------------*/
/**
* @constantspage{taskpool,task pool library}
*
* @section taskpool_constants_initializers Task pool Initializers
* @brief Provides default values for initializing the data types of the task pool library.
*
* @snippet this define_taskpool_initializers
*
* All user-facing data types of the task pool library can be initialized using
* one of the following.
*
* @warning Failure to initialize a task pool data type with the appropriate initializer
* may result in a runtime error!
* @note The initializers may change at any time in future versions, but their
* names will remain the same.
*
* <b>Example</b>
* @code{c}
*
* IotTaskPool_t * pTaskPool;
*
* const IotTaskPoolInfo_t tpInfo = IOT_TASKPOOL_INFO_INITIALIZER_LARGE;
*
* IotTaskPoolError_t error = IotTaskPool_Create( &tpInfo, &pTaskPool );
*
* // Use the task pool
* // ...
*
* @endcode
*
*/
/* @[define_taskpool_initializers] */
/** @brief Initializer for a small #IotTaskPoolInfo_t. */
#define IOT_TASKPOOL_INFO_INITIALIZER_SMALL { .minThreads = 1, .maxThreads = 1, .stackSize = IOT_THREAD_DEFAULT_STACK_SIZE, .priority = IOT_THREAD_DEFAULT_PRIORITY }
/** @brief Initializer for a medium #IotTaskPoolInfo_t. */
#define IOT_TASKPOOL_INFO_INITIALIZER_MEDIUM { .minThreads = 1, .maxThreads = 2, .stackSize = IOT_THREAD_DEFAULT_STACK_SIZE, .priority = IOT_THREAD_DEFAULT_PRIORITY }
/** @brief Initializer for a large #IotTaskPoolInfo_t. */
#define IOT_TASKPOOL_INFO_INITIALIZER_LARGE { .minThreads = 2, .maxThreads = 3, .stackSize = IOT_THREAD_DEFAULT_STACK_SIZE, .priority = IOT_THREAD_DEFAULT_PRIORITY }
/** @brief Initializer for a very large #IotTaskPoolInfo_t. */
#define IOT_TASKPOOL_INFO_INITIALIZER_XLARGE { .minThreads = 2, .maxThreads = 4, .stackSize = IOT_THREAD_DEFAULT_STACK_SIZE, .priority = IOT_THREAD_DEFAULT_PRIORITY }
/** @brief Initializer for a typical #IotTaskPoolInfo_t. */
#define IOT_TASKPOOL_INFO_INITIALIZER IOT_TASKPOOL_INFO_INITIALIZER_MEDIUM
/** @brief Initializer for a #IotTaskPool_t. */
#define IOT_TASKPOOL_INITIALIZER NULL
/** @brief Initializer for a #IotTaskPoolJobStorage_t. */
#define IOT_TASKPOOL_JOB_STORAGE_INITIALIZER { { NULL, NULL }, NULL, NULL, 0, IOT_TASKPOOL_STATUS_UNDEFINED }
/** @brief Initializer for a #IotTaskPoolJob_t. */
#define IOT_TASKPOOL_JOB_INITIALIZER NULL
/* @[define_taskpool_initializers] */
/**
* @brief Flag for scheduling a job to execute immediately, even if the maximum number of threads in the
* task pool was reached already.
*
* @warning This flag may cause the task pool to create a worker to serve the job immediately, and
* therefore using this flag may incur in additional memory usage and potentially fail scheduling the job.
*/
#define IOT_TASKPOOL_JOB_HIGH_PRIORITY ( ( uint32_t ) 0x00000001 )
/**
* @brief Allows the use of the handle to the system task pool.
*
* @warning The task pool handle is not valid unless @ref IotTaskPool_CreateSystemTaskPool is
* called before the handle is used.
*/
#define IOT_SYSTEM_TASKPOOL ( IotTaskPool_GetSystemTaskPool() )
#endif /* ifndef IOT_TASKPOOL_TYPES_H_ */

View file

@ -0,0 +1,454 @@
/*
* Amazon FreeRTOS Common V1.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_logging.c
* @brief Implementation of logging functions from iot_logging.h
*/
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
/* Platform clock include. */
#include "platform/iot_clock.h"
/* Logging includes. */
#include "private/iot_logging.h"
/*-----------------------------------------------------------*/
/* This implementation assumes the following values for the log level constants.
* Ensure that the values have not been modified. */
#if IOT_LOG_NONE != 0
#error "IOT_LOG_NONE must be 0."
#endif
#if IOT_LOG_ERROR != 1
#error "IOT_LOG_ERROR must be 1."
#endif
#if IOT_LOG_WARN != 2
#error "IOT_LOG_WARN must be 2."
#endif
#if IOT_LOG_INFO != 3
#error "IOT_LOG_INFO must be 3."
#endif
#if IOT_LOG_DEBUG != 4
#error "IOT_LOG_DEBUG must be 4."
#endif
/**
* @def IotLogging_Puts( message )
* @brief Function the logging library uses to print a line.
*
* This function can be set by using a define. By default, the standard library
* [puts](http://pubs.opengroup.org/onlinepubs/9699919799/functions/puts.html)
* function is used.
*/
#ifndef IotLogging_Puts
#define IotLogging_Puts puts
#endif
/*
* Provide default values for undefined memory allocation functions based on
* the usage of dynamic memory allocation.
*/
#if IOT_STATIC_MEMORY_ONLY == 1
/* Static memory allocation header. */
#include "private/iot_static_memory.h"
/**
* @brief Allocate a new logging buffer. This function must have the same
* signature as [malloc](http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html).
*/
#ifndef IotLogging_Malloc
#define IotLogging_Malloc Iot_MallocMessageBuffer
#endif
/**
* @brief Free a logging buffer. This function must have the same signature
* as [free](http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html).
*/
#ifndef IotLogging_Free
#define IotLogging_Free Iot_FreeMessageBuffer
#endif
/**
* @brief Get the size of a logging buffer. Statically-allocated buffers
* should all have the same size.
*/
#ifndef IotLogging_StaticBufferSize
#define IotLogging_StaticBufferSize Iot_MessageBufferSize
#endif
#else /* if IOT_STATIC_MEMORY_ONLY == 1 */
#ifndef IotLogging_Malloc
#include <stdlib.h>
#define IotLogging_Malloc malloc
#endif
#ifndef IotLogging_Free
#include <stdlib.h>
#define IotLogging_Free free
#endif
#endif /* if IOT_STATIC_MEMORY_ONLY == 1 */
/**
* @brief A guess of the maximum length of a timestring.
*
* There's no way for this logging library to know the length of a timestring
* before it's generated. Therefore, the logging library will assume a maximum
* length of any timestring it may get. This value should be generous enough
* to accommodate the vast majority of timestrings.
*
* @see @ref platform_clock_function_gettimestring
*/
#define MAX_TIMESTRING_LENGTH ( 64 )
/**
* @brief The longest string in #_pLogLevelStrings (below), plus 3 to accommodate
* `[]` and a null-terminator.
*/
#define MAX_LOG_LEVEL_LENGTH ( 8 )
/**
* @brief How many bytes @ref logging_function_genericprintbuffer should output on
* each line.
*/
#define BYTES_PER_LINE ( 16 )
/*-----------------------------------------------------------*/
/**
* @brief Lookup table for log levels.
*
* Converts one of the @ref logging_constants_levels to a string.
*/
static const char * const _pLogLevelStrings[ 5 ] =
{
"", /* IOT_LOG_NONE */
"ERROR", /* IOT_LOG_ERROR */
"WARN ", /* IOT_LOG_WARN */
"INFO ", /* IOT_LOG_INFO */
"DEBUG" /* IOT_LOG_DEBUG */
};
/*-----------------------------------------------------------*/
#if !defined( IOT_STATIC_MEMORY_ONLY ) || ( IOT_STATIC_MEMORY_ONLY == 0 )
static bool _reallocLoggingBuffer( void ** pOldBuffer,
size_t newSize,
size_t oldSize )
{
bool status = false;
/* Allocate a new, larger buffer. */
void * pNewBuffer = IotLogging_Malloc( newSize );
/* Ensure that memory allocation succeeded. */
if( pNewBuffer != NULL )
{
/* Copy the data from the old buffer to the new buffer. */
( void ) memcpy( pNewBuffer, *pOldBuffer, oldSize );
/* Free the old buffer and update the pointer. */
IotLogging_Free( *pOldBuffer );
*pOldBuffer = pNewBuffer;
status = true;
}
return status;
}
#endif /* if !defined( IOT_STATIC_MEMORY_ONLY ) || ( IOT_STATIC_MEMORY_ONLY == 0 ) */
/*-----------------------------------------------------------*/
void IotLog_Generic( int libraryLogSetting,
const char * const pLibraryName,
int messageLevel,
const IotLogConfig_t * const pLogConfig,
const char * const pFormat,
... )
{
int requiredMessageSize = 0;
size_t bufferSize = 0,
bufferPosition = 0, timestringLength = 0;
char * pLoggingBuffer = NULL;
va_list args;
/* If the library's log level setting is lower than the message level,
* return without doing anything. */
if( ( messageLevel == 0 ) || ( messageLevel > libraryLogSetting ) )
{
return;
}
if( ( pLogConfig == NULL ) || ( pLogConfig->hideLogLevel == false ) )
{
/* Add length of log level if requested. */
bufferSize += MAX_LOG_LEVEL_LENGTH;
}
/* Estimate the amount of buffer needed for this log message. */
if( ( pLogConfig == NULL ) || ( pLogConfig->hideLibraryName == false ) )
{
/* Add size of library name if requested. Add 2 to accommodate "[]". */
bufferSize += strlen( pLibraryName ) + 2;
}
if( ( pLogConfig == NULL ) || ( pLogConfig->hideTimestring == false ) )
{
/* Add length of timestring if requested. */
bufferSize += MAX_TIMESTRING_LENGTH;
}
/* Add 64 as an initial (arbitrary) guess for the length of the message. */
bufferSize += 64;
/* In static memory mode, check that the log message will fit in the a
* static buffer. */
#if IOT_STATIC_MEMORY_ONLY == 1
if( bufferSize >= IotLogging_StaticBufferSize() )
{
/* If the static buffers are likely too small to fit the log message,
* return. */
return;
}
/* Otherwise, update the buffer size to the size of a static buffer. */
bufferSize = IotLogging_StaticBufferSize();
#endif
/* Allocate memory for the logging buffer. */
pLoggingBuffer = ( char * ) IotLogging_Malloc( bufferSize );
if( pLoggingBuffer == NULL )
{
return;
}
/* Print the message log level if requested. */
if( ( pLogConfig == NULL ) || ( pLogConfig->hideLogLevel == false ) )
{
/* Ensure that message level is valid. */
if( ( messageLevel >= IOT_LOG_NONE ) && ( messageLevel <= IOT_LOG_DEBUG ) )
{
/* Add the log level string to the logging buffer. */
requiredMessageSize = snprintf( pLoggingBuffer + bufferPosition,
bufferSize - bufferPosition,
"[%s]",
_pLogLevelStrings[ messageLevel ] );
/* Check for encoding errors. */
if( requiredMessageSize <= 0 )
{
IotLogging_Free( pLoggingBuffer );
return;
}
/* Update the buffer position. */
bufferPosition += ( size_t ) requiredMessageSize;
}
}
/* Print the library name if requested. */
if( ( pLogConfig == NULL ) || ( pLogConfig->hideLibraryName == false ) )
{
/* Add the library name to the logging buffer. */
requiredMessageSize = snprintf( pLoggingBuffer + bufferPosition,
bufferSize - bufferPosition,
"[%s]",
pLibraryName );
/* Check for encoding errors. */
if( requiredMessageSize <= 0 )
{
IotLogging_Free( pLoggingBuffer );
return;
}
/* Update the buffer position. */
bufferPosition += ( size_t ) requiredMessageSize;
}
/* Print the timestring if requested. */
if( ( pLogConfig == NULL ) || ( pLogConfig->hideTimestring == false ) )
{
/* Add the opening '[' enclosing the timestring. */
pLoggingBuffer[ bufferPosition ] = '[';
bufferPosition++;
/* Generate the timestring and add it to the buffer. */
if( IotClock_GetTimestring( pLoggingBuffer + bufferPosition,
bufferSize - bufferPosition,
&timestringLength ) == true )
{
/* If the timestring was successfully generated, add the closing "]". */
bufferPosition += timestringLength;
pLoggingBuffer[ bufferPosition ] = ']';
bufferPosition++;
}
else
{
/* Sufficient memory for a timestring should have been allocated. A timestring
* probably failed to generate due to a clock read error; remove the opening '['
* from the logging buffer. */
bufferPosition--;
pLoggingBuffer[ bufferPosition ] = '\0';
}
}
/* Add a padding space between the last closing ']' and the message, unless
* the logging buffer is empty. */
if( bufferPosition > 0 )
{
pLoggingBuffer[ bufferPosition ] = ' ';
bufferPosition++;
}
va_start( args, pFormat );
/* Add the log message to the logging buffer. */
requiredMessageSize = vsnprintf( pLoggingBuffer + bufferPosition,
bufferSize - bufferPosition,
pFormat,
args );
va_end( args );
/* If the logging buffer was too small to fit the log message, reallocate
* a larger logging buffer. */
if( ( size_t ) requiredMessageSize >= bufferSize - bufferPosition )
{
#if IOT_STATIC_MEMORY_ONLY == 1
/* There's no point trying to allocate a larger static buffer. Return
* immediately. */
IotLogging_Free( pLoggingBuffer );
return;
#else
if( _reallocLoggingBuffer( ( void ** ) &pLoggingBuffer,
( size_t ) requiredMessageSize + bufferPosition + 1,
bufferSize ) == false )
{
/* If buffer reallocation failed, return. */
IotLogging_Free( pLoggingBuffer );
return;
}
/* Reallocation successful, update buffer size. */
bufferSize = ( size_t ) requiredMessageSize + bufferPosition + 1;
/* Add the log message to the buffer. Now that the buffer has been
* reallocated, this should succeed. */
va_start( args, pFormat );
requiredMessageSize = vsnprintf( pLoggingBuffer + bufferPosition,
bufferSize - bufferPosition,
pFormat,
args );
va_end( args );
#endif /* if IOT_STATIC_MEMORY_ONLY == 1 */
}
/* Check for encoding errors. */
if( requiredMessageSize <= 0 )
{
IotLogging_Free( pLoggingBuffer );
return;
}
/* Print the logging buffer to stdout. */
IotLogging_Puts( pLoggingBuffer );
/* Free the logging buffer. */
IotLogging_Free( pLoggingBuffer );
}
/*-----------------------------------------------------------*/
void IotLog_GenericPrintBuffer( const char * const pLibraryName,
const char * const pHeader,
const uint8_t * const pBuffer,
size_t bufferSize )
{
size_t i = 0, offset = 0;
/* Allocate memory to hold each line of the log message. Since each byte
* of pBuffer is printed in 4 characters (2 digits, a space, and a null-
* terminator), the size of each line is 4 * BYTES_PER_LINE. */
char * pMessageBuffer = IotLogging_Malloc( 4 * BYTES_PER_LINE );
/* Exit if no memory is available. */
if( pMessageBuffer == NULL )
{
return;
}
/* Print pHeader before printing pBuffer. */
if( pHeader != NULL )
{
IotLog_Generic( IOT_LOG_DEBUG,
pLibraryName,
IOT_LOG_DEBUG,
NULL,
pHeader );
}
/* Print each byte in pBuffer. */
for( i = 0; i < bufferSize; i++ )
{
/* Print a line if BYTES_PER_LINE is reached. But don't print a line
* at the beginning (when i=0). */
if( ( i % BYTES_PER_LINE == 0 ) && ( i != 0 ) )
{
IotLogging_Puts( pMessageBuffer );
/* Reset offset so that pMessageBuffer is filled from the beginning. */
offset = 0;
}
/* Print a single byte into pMessageBuffer. */
( void ) snprintf( pMessageBuffer + offset, 4, "%02x ", pBuffer[ i ] );
/* Move the offset where the next character is printed. */
offset += 3;
}
/* Print the final line of bytes. This line isn't printed by the for-loop above. */
IotLogging_Puts( pMessageBuffer );
/* Free memory used by this function. */
IotLogging_Free( pMessageBuffer );
}
/*-----------------------------------------------------------*/

View file

@ -0,0 +1,250 @@
/*
* Amazon FreeRTOS Common V1.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
*/
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
/* Logging includes. */
#include "iot_logging_task.h"
/* Standard includes. */
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
/* Sanity check all the definitions required by this file are set. */
#ifndef configPRINT_STRING
#error configPRINT_STRING( x ) must be defined in FreeRTOSConfig.h to use this logging file. Set configPRINT_STRING( x ) to a function that outputs a string, where X is the string. For example, #define configPRINT_STRING( x ) MyUARTWriteString( X )
#endif
#ifndef configLOGGING_MAX_MESSAGE_LENGTH
#error configLOGGING_MAX_MESSAGE_LENGTH must be defined in FreeRTOSConfig.h to use this logging file. configLOGGING_MAX_MESSAGE_LENGTH sets the size of the buffer into which formatted text is written, so also sets the maximum log message length.
#endif
#ifndef configLOGGING_INCLUDE_TIME_AND_TASK_NAME
#error configLOGGING_INCLUDE_TIME_AND_TASK_NAME must be defined in FreeRTOSConfig.h to use this logging file. Set configLOGGING_INCLUDE_TIME_AND_TASK_NAME to 1 to prepend a time stamp, message number and the name of the calling task to each logged message. Otherwise set to 0.
#endif
/* A block time of 0 just means don't block. */
#define loggingDONT_BLOCK 0
/*-----------------------------------------------------------*/
/*
* The task that actually performs the print output. Using a separate task
* enables the use of slow output, such as as a UART, without the task that is
* outputting the log message having to wait for the message to be completely
* written. Using a separate task also serializes access to the output port.
*
* The structure of this task is very simple; it blocks on a queue to wait for
* a pointer to a string, sending any received strings to a macro that performs
* the actual output. The macro is port specific, so implemented outside of
* this file. This version uses dynamic memory, so the buffer that contained
* the log message is freed after it has been output.
*/
static void prvLoggingTask( void * pvParameters );
/*-----------------------------------------------------------*/
/*
* The queue used to pass pointers to log messages from the task that created
* the message to the task that will performs the output.
*/
static QueueHandle_t xQueue = NULL;
/*-----------------------------------------------------------*/
BaseType_t xLoggingTaskInitialize( uint16_t usStackSize,
UBaseType_t uxPriority,
UBaseType_t uxQueueLength )
{
BaseType_t xReturn = pdFAIL;
/* Ensure the logging task has not been created already. */
if( xQueue == NULL )
{
/* Create the queue used to pass pointers to strings to the logging task. */
xQueue = xQueueCreate( uxQueueLength, sizeof( char ** ) );
if( xQueue != NULL )
{
if( xTaskCreate( prvLoggingTask, "Logging", usStackSize, NULL, uxPriority, NULL ) == pdPASS )
{
xReturn = pdPASS;
}
else
{
/* Could not create the task, so delete the queue again. */
vQueueDelete( xQueue );
}
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
static void prvLoggingTask( void * pvParameters )
{
char * pcReceivedString = NULL;
for( ; ; )
{
/* Block to wait for the next string to print. */
if( xQueueReceive( xQueue, &pcReceivedString, portMAX_DELAY ) == pdPASS )
{
configPRINT_STRING( pcReceivedString );
vPortFree( ( void * ) pcReceivedString );
}
}
}
/*-----------------------------------------------------------*/
/*!
* \brief Formats a string to be printed and sends it
* to the print queue.
*
* Appends the message number, time (in ticks), and task
* that called vLoggingPrintf to the beginning of each
* print statement.
*
*/
void vLoggingPrintf( const char * pcFormat,
... )
{
size_t xLength = 0;
int32_t xLength2 = 0;
va_list args;
char * pcPrintString = NULL;
/* The queue is created by xLoggingTaskInitialize(). Check
* xLoggingTaskInitialize() has been called. */
configASSERT( xQueue );
/* Allocate a buffer to hold the log message. */
pcPrintString = pvPortMalloc( configLOGGING_MAX_MESSAGE_LENGTH );
if( pcPrintString != NULL )
{
/* There are a variable number of parameters. */
va_start( args, pcFormat );
if( strcmp( pcFormat, "\n" ) != 0 )
{
#if ( configLOGGING_INCLUDE_TIME_AND_TASK_NAME == 1 )
{
const char * pcTaskName;
const char * pcNoTask = "None";
static BaseType_t xMessageNumber = 0;
/* Add a time stamp and the name of the calling task to the
* start of the log. */
if( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )
{
pcTaskName = pcTaskGetName( NULL );
}
else
{
pcTaskName = pcNoTask;
}
xLength = snprintf( pcPrintString, configLOGGING_MAX_MESSAGE_LENGTH, "%lu %lu [%s] ",
( unsigned long ) xMessageNumber++,
( unsigned long ) xTaskGetTickCount(),
pcTaskName );
}
#else /* if ( configLOGGING_INCLUDE_TIME_AND_TASK_NAME == 1 ) */
{
xLength = 0;
}
#endif /* if ( configLOGGING_INCLUDE_TIME_AND_TASK_NAME == 1 ) */
}
xLength2 = vsnprintf( pcPrintString + xLength, configLOGGING_MAX_MESSAGE_LENGTH - xLength, pcFormat, args );
if( xLength2 < 0 )
{
/* vsnprintf() failed. Restore the terminating NULL
* character of the first part. Note that the first
* part of the buffer may be empty if the value of
* configLOGGING_INCLUDE_TIME_AND_TASK_NAME is not
* 1 and as a result, the whole buffer may be empty.
* That's the reason we have a check for xLength > 0
* before sending the buffer to the logging task.
*/
xLength2 = 0;
pcPrintString[ xLength ] = '\0';
}
xLength += ( size_t ) xLength2;
va_end( args );
/* Only send the buffer to the logging task if it is
* not empty. */
if( xLength > 0 )
{
/* Send the string to the logging task for IO. */
if( xQueueSend( xQueue, &pcPrintString, loggingDONT_BLOCK ) != pdPASS )
{
/* The buffer was not sent so must be freed again. */
vPortFree( ( void * ) pcPrintString );
}
}
else
{
/* The buffer was not sent, so it must be
* freed. */
vPortFree( ( void * ) pcPrintString );
}
}
}
/*-----------------------------------------------------------*/
void vLoggingPrint( const char * pcMessage )
{
char * pcPrintString = NULL;
size_t xLength = 0;
/* The queue is created by xLoggingTaskInitialize(). Check
* xLoggingTaskInitialize() has been called. */
configASSERT( xQueue );
xLength = strlen( pcMessage ) + 1;
pcPrintString = pvPortMalloc( xLength );
if( pcPrintString != NULL )
{
strncpy( pcPrintString, pcMessage, xLength );
/* Send the string to the logging task for IO. */
if( xQueueSend( xQueue, &pcPrintString, loggingDONT_BLOCK ) != pdPASS )
{
/* The buffer was not sent so must be freed again. */
vPortFree( ( void * ) pcPrintString );
}
}
}

View file

@ -0,0 +1,175 @@
/*
* Amazon FreeRTOS Common V1.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_taskpool_static_memory.c
* @brief Implementation of task pool static memory functions.
*/
/* The config header is always included first. */
#include "iot_config.h"
/* This file should only be compiled if dynamic memory allocation is forbidden. */
#if IOT_STATIC_MEMORY_ONLY == 1
/* Standard includes. */
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
/* Static memory include. */
#include "private/iot_static_memory.h"
/* Task pool internal include. */
#include "private/iot_taskpool_internal.h"
/*-----------------------------------------------------------*/
/* Validate static memory configuration settings. */
#if IOT_TASKPOOL_JOBS_RECYCLE_LIMIT <= 0
#error "IOT_TASKPOOL_JOBS_RECYCLE_LIMIT cannot be 0 or negative."
#endif
/*-----------------------------------------------------------*/
/*
* Static memory buffers and flags, allocated and zeroed at compile-time.
*/
static bool _pInUseTaskPools[ IOT_TASKPOOLS ] = { 0 }; /**< @brief Task pools in-use flags. */
static _taskPool_t _pTaskPools[ IOT_TASKPOOLS ] = { { .dispatchQueue = IOT_DEQUEUE_INITIALIZER } }; /**< @brief Task pools. */
static bool _pInUseTaskPoolJobs[ IOT_TASKPOOL_JOBS_RECYCLE_LIMIT ] = { 0 }; /**< @brief Task pool jobs in-use flags. */
static _taskPoolJob_t _pTaskPoolJobs[ IOT_TASKPOOL_JOBS_RECYCLE_LIMIT ] = { { .link = IOT_LINK_INITIALIZER } }; /**< @brief Task pool jobs. */
static bool _pInUseTaskPoolTimerEvents[ IOT_TASKPOOL_JOBS_RECYCLE_LIMIT ] = { 0 }; /**< @brief Task pool timer event in-use flags. */
static _taskPoolTimerEvent_t _pTaskPoolTimerEvents[ IOT_TASKPOOL_JOBS_RECYCLE_LIMIT ] = { { .link = { 0 } } }; /**< @brief Task pool timer events. */
/*-----------------------------------------------------------*/
void * IotTaskPool_MallocTaskPool( size_t size )
{
int freeIndex = -1;
void * pNewTaskPool = NULL;
/* Check size argument. */
if( size == sizeof( _taskPool_t ) )
{
/* Find a free task pool job. */
freeIndex = IotStaticMemory_FindFree( _pInUseTaskPools, IOT_TASKPOOLS );
if( freeIndex != -1 )
{
pNewTaskPool = &( _pTaskPools[ freeIndex ] );
}
}
return pNewTaskPool;
}
/*-----------------------------------------------------------*/
void IotTaskPool_FreeTaskPool( void * ptr )
{
/* Return the in-use task pool job. */
IotStaticMemory_ReturnInUse( ptr,
_pTaskPools,
_pInUseTaskPools,
IOT_TASKPOOLS,
sizeof( _taskPool_t ) );
}
/*-----------------------------------------------------------*/
void * IotTaskPool_MallocJob( size_t size )
{
int32_t freeIndex = -1;
void * pNewJob = NULL;
/* Check size argument. */
if( size == sizeof( _taskPoolJob_t ) )
{
/* Find a free task pool job. */
freeIndex = IotStaticMemory_FindFree( _pInUseTaskPoolJobs,
IOT_TASKPOOL_JOBS_RECYCLE_LIMIT );
if( freeIndex != -1 )
{
pNewJob = &( _pTaskPoolJobs[ freeIndex ] );
}
}
return pNewJob;
}
/*-----------------------------------------------------------*/
void IotTaskPool_FreeJob( void * ptr )
{
/* Return the in-use task pool job. */
IotStaticMemory_ReturnInUse( ptr,
_pTaskPoolJobs,
_pInUseTaskPoolJobs,
IOT_TASKPOOL_JOBS_RECYCLE_LIMIT,
sizeof( _taskPoolJob_t ) );
}
/*-----------------------------------------------------------*/
void * IotTaskPool_MallocTimerEvent( size_t size )
{
int32_t freeIndex = -1;
void * pNewTimerEvent = NULL;
/* Check size argument. */
if( size == sizeof( _taskPoolTimerEvent_t ) )
{
/* Find a free task pool timer event. */
freeIndex = IotStaticMemory_FindFree( _pInUseTaskPoolTimerEvents,
IOT_TASKPOOL_JOBS_RECYCLE_LIMIT );
if( freeIndex != -1 )
{
pNewTimerEvent = &( _pTaskPoolTimerEvents[ freeIndex ] );
}
}
return pNewTimerEvent;
}
/*-----------------------------------------------------------*/
void IotTaskPool_FreeTimerEvent( void * ptr )
{
/* Return the in-use task pool timer event. */
IotStaticMemory_ReturnInUse( ptr,
_pTaskPoolTimerEvents,
_pInUseTaskPoolTimerEvents,
IOT_TASKPOOL_JOBS_RECYCLE_LIMIT,
sizeof( _taskPoolTimerEvent_t ) );
}
/*-----------------------------------------------------------*/
#endif

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_ */

View file

@ -0,0 +1,794 @@
/*
* 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.c
* @brief MQTT Agent implementation. Provides backwards compatibility between
* MQTT v2 and MQTT v1.
*/
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "semphr.h"
/* MQTT v1 includes. */
#include "iot_mqtt_agent.h"
#include "iot_mqtt_agent_config.h"
#include "iot_mqtt_agent_config_defaults.h"
/* MQTT v2 include. */
#include "iot_mqtt.h"
/* Platform network include. */
#include "platform/iot_network_freertos.h"
/*-----------------------------------------------------------*/
/**
* @brief Converts FreeRTOS ticks to milliseconds.
*/
#define mqttTICKS_TO_MS( xTicks ) ( xTicks * 1000 / configTICK_RATE_HZ )
/*-----------------------------------------------------------*/
/**
* @brief Stores data to convert between the MQTT v1 subscription callback
* and the MQTT v2 subscription callback.
*/
#if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 )
typedef struct MQTTCallback
{
BaseType_t xInUse; /**< Whether this instance is in-use. */
MQTTPublishCallback_t xFunction; /**< MQTT v1 callback function. */
void * pvParameter; /**< Parameter to xFunction. */
uint16_t usTopicFilterLength; /**< Length of pcTopicFilter. */
char pcTopicFilter[ mqttconfigSUBSCRIPTION_MANAGER_MAX_TOPIC_LENGTH ]; /**< Topic filter. */
} MQTTCallback_t;
#endif
/**
* @brief Stores data on an active MQTT connection.
*/
typedef struct MQTTConnection
{
IotMqttConnection_t xMQTTConnection; /**< MQTT v2 connection handle. */
MQTTAgentCallback_t pxCallback; /**< MQTT v1 global callback. */
void * pvUserData; /**< Parameter to pxCallback. */
StaticSemaphore_t xConnectionMutex; /**< Protects from concurrent accesses. */
#if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 )
MQTTCallback_t xCallbacks /**< Conversion table of MQTT v1 to MQTT v2 subscription callbacks. */
[ mqttconfigSUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS ];
#endif
} MQTTConnection_t;
/*-----------------------------------------------------------*/
/**
* @brief Convert an MQTT v2 return code to an MQTT v1 return code.
*
* @param[in] xMqttStatus The MQTT v2 return code.
*
* @return An equivalent MQTT v1 return code.
*/
static inline MQTTAgentReturnCode_t prvConvertReturnCode( IotMqttError_t xMqttStatus );
/**
* @brief Wraps an MQTT v1 publish callback.
*
* @param[in] pvParameter The MQTT connection.
* @param[in] pxPublish Information about the incoming publish.
*/
static void prvPublishCallbackWrapper( void * pvParameter,
IotMqttCallbackParam_t * const pxPublish );
/**
* @brief Wraps an MQTT v1 disconnect callback.
*
* @param[in] pvCallbackContext The MQTT connection.
* @param[in] pxDisconnect Information about the disconnect.
*/
static void prvDisconnectCallbackWrapper( void * pvParameter,
IotMqttCallbackParam_t * pxDisconnect );
#if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 )
/**
* @brief Store an MQTT v1 callback in the conversion table.
*
* @param[in] pxConnection Where to store the callback.
* @param[in] pcTopicFilter Topic filter to store.
* @param[in] usTopicFilterLength Length of pcTopicFilter.
* @param[in] xCallback MQTT v1 callback to store.
* @param[in] pvParameter Parameter to xCallback.
*
* @return pdPASS if the callback was successfully stored; pdFAIL otherwise.
*/
static BaseType_t prvStoreCallback( MQTTConnection_t * const pxConnection,
const char * const pcTopicFilter,
uint16_t usTopicFilterLength,
MQTTPublishCallback_t xCallback,
void * pvParameter );
/**
* @brief Search the callback conversion table for the given topic filter.
*
* @param[in] pxConnection The connection containing the conversion table.
* @param[in] pcTopicFilter The topic filter to search for.
* @param[in] usTopicFilterLength The length of pcTopicFilter.
*
* @return A pointer to the callback entry if found; NULL otherwise.
* @note This function should be called with pxConnection->xConnectionMutex
* locked.
*/
static MQTTCallback_t * prvFindCallback( MQTTConnection_t * const pxConnection,
const char * const pcTopicFilter,
uint16_t usTopicFilterLength );
/**
* @brief Remove a topic filter from the callback conversion table.
*
* @param[in] pxConnection The connection containing the conversion table.
* @param[in] pcTopicFilter The topic filter to remove.
* @param[in] usTopicFilterLength The length of pcTopic.
*/
static void prvRemoveCallback( MQTTConnection_t * const pxConnection,
const char * const pcTopicFilter,
uint16_t usTopicFilterLength );
#endif /* if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 ) */
/*-----------------------------------------------------------*/
/**
* @brief The number of available MQTT brokers, controlled by the constant
* mqttconfigMAX_BROKERS;
*/
static UBaseType_t uxAvailableBrokers = mqttconfigMAX_BROKERS;
/*-----------------------------------------------------------*/
static inline MQTTAgentReturnCode_t prvConvertReturnCode( IotMqttError_t xMqttStatus )
{
MQTTAgentReturnCode_t xStatus = eMQTTAgentSuccess;
switch( xMqttStatus )
{
case IOT_MQTT_SUCCESS:
case IOT_MQTT_STATUS_PENDING:
xStatus = eMQTTAgentSuccess;
break;
case IOT_MQTT_TIMEOUT:
xStatus = eMQTTAgentTimeout;
break;
default:
xStatus = eMQTTAgentFailure;
break;
}
return xStatus;
}
/*-----------------------------------------------------------*/
static void prvPublishCallbackWrapper( void * pvParameter,
IotMqttCallbackParam_t * const pxPublish )
{
BaseType_t xStatus = pdPASS;
size_t xBufferSize = 0;
uint8_t * pucMqttBuffer = NULL;
MQTTBool_t xCallbackReturn = eMQTTFalse;
MQTTConnection_t * pxConnection = ( MQTTConnection_t * ) pvParameter;
MQTTAgentCallbackParams_t xPublishData = { .xMQTTEvent = eMQTTAgentPublish };
/* Calculate the size of the MQTT buffer that must be allocated. */
if( xStatus == pdPASS )
{
xBufferSize = pxPublish->u.message.info.topicNameLength +
pxPublish->u.message.info.payloadLength;
/* Check for overflow. */
if( ( xBufferSize < pxPublish->u.message.info.topicNameLength ) ||
( xBufferSize < pxPublish->u.message.info.payloadLength ) )
{
mqttconfigDEBUG_LOG( ( "Incoming PUBLISH message and topic name length too large.\r\n" ) );
xStatus = pdFAIL;
}
}
/* Allocate an MQTT buffer for the callback. */
if( xStatus == pdPASS )
{
pucMqttBuffer = pvPortMalloc( xBufferSize );
if( pucMqttBuffer == NULL )
{
mqttconfigDEBUG_LOG( ( "Failed to allocate memory for MQTT buffer.\r\n" ) );
xStatus = pdFAIL;
}
else
{
/* Copy the topic name and payload. The topic name and payload must be
* copied in case the user decides to take ownership of the MQTT buffer.
* The original buffer containing the MQTT topic name and payload may
* contain further unprocessed packets and must remain property of the
* MQTT library. Therefore, the topic name and payload are copied into
* another buffer for the user. */
( void ) memcpy( pucMqttBuffer,
pxPublish->u.message.info.pTopicName,
pxPublish->u.message.info.topicNameLength );
( void ) memcpy( pucMqttBuffer + pxPublish->u.message.info.topicNameLength,
pxPublish->u.message.info.pPayload,
pxPublish->u.message.info.payloadLength );
/* Set the members of the callback parameter. */
xPublishData.xMQTTEvent = eMQTTAgentPublish;
xPublishData.u.xPublishData.pucTopic = pucMqttBuffer;
xPublishData.u.xPublishData.usTopicLength = pxPublish->u.message.info.topicNameLength;
xPublishData.u.xPublishData.pvData = pucMqttBuffer + pxPublish->u.message.info.topicNameLength;
xPublishData.u.xPublishData.ulDataLength = ( uint32_t ) pxPublish->u.message.info.payloadLength;
xPublishData.u.xPublishData.xQos = ( MQTTQoS_t ) pxPublish->u.message.info.qos;
xPublishData.u.xPublishData.xBuffer = pucMqttBuffer;
}
}
if( xStatus == pdPASS )
{
#if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 )
/* When subscription management is enabled, search for a matching subscription. */
MQTTCallback_t * pxCallbackEntry = prvFindCallback( pxConnection,
pxPublish->u.message.pTopicFilter,
pxPublish->u.message.topicFilterLength );
/* Check if a matching MQTT v1 subscription was found. */
if( pxCallbackEntry != NULL )
{
/* Invoke the topic-specific callback if it exists. */
if( pxCallbackEntry->xFunction != NULL )
{
xCallbackReturn = pxCallbackEntry->xFunction( pxCallbackEntry->pvParameter,
&( xPublishData.u.xPublishData ) );
}
else
{
/* Otherwise, invoke the global callback. */
if( pxConnection->pxCallback != NULL )
{
xCallbackReturn = ( MQTTBool_t ) pxConnection->pxCallback( pxConnection->pvUserData,
&xPublishData );
}
}
}
#else /* if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 ) */
/* When subscription management is disabled, invoke the global callback
* if one exists. */
/* When subscription management is disabled, the topic filter must be "#". */
mqttconfigASSERT( *( xPublish.message.pTopicFilter ) == '#' );
mqttconfigASSERT( xPublish.message.topicFilterLength == 1 );
if( pxConnection->pxCallback != NULL )
{
xCallbackReturn = ( MQTTBool_t ) pxConnection->pxCallback( pxConnection->pvUserData,
&xPublishData );
}
#endif /* if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 ) */
}
/* Free the MQTT buffer if the user did not take ownership of it. */
if( ( xCallbackReturn == eMQTTFalse ) && ( pucMqttBuffer != NULL ) )
{
vPortFree( pucMqttBuffer );
}
}
/*-----------------------------------------------------------*/
static void prvDisconnectCallbackWrapper( void * pvParameter,
IotMqttCallbackParam_t * pxDisconnect )
{
MQTTConnection_t * pxConnection = ( MQTTConnection_t * ) pvParameter;
MQTTAgentCallbackParams_t xCallbackParams = { .xMQTTEvent = eMQTTAgentDisconnect };
( void ) pxDisconnect;
/* This function should only be called if a callback was set. */
mqttconfigASSERT( pxConnection->pxCallback != NULL );
/* Invoke the MQTT v1 callback. Ignore the return value. */
pxConnection->pxCallback( pxConnection->pvUserData,
&xCallbackParams );
}
/*-----------------------------------------------------------*/
#if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 )
static BaseType_t prvStoreCallback( MQTTConnection_t * const pxConnection,
const char * const pcTopicFilter,
uint16_t usTopicFilterLength,
MQTTPublishCallback_t xCallback,
void * pvParameter )
{
MQTTCallback_t * pxCallback = NULL;
BaseType_t xStatus = pdFAIL, i = 0;
/* Prevent other tasks from modifying stored callbacks while this function
* runs. */
if( xSemaphoreTake( ( QueueHandle_t ) &( pxConnection->xConnectionMutex ),
portMAX_DELAY ) == pdTRUE )
{
/* Check if the topic filter already has an entry. */
pxCallback = prvFindCallback( pxConnection, pcTopicFilter, usTopicFilterLength );
if( pxCallback == NULL )
{
/* If no entry was found, find a free entry. */
for( i = 0; i < mqttconfigSUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS; i++ )
{
if( pxConnection->xCallbacks[ i ].xInUse == pdFALSE )
{
pxConnection->xCallbacks[ i ].xInUse = pdTRUE;
pxCallback = &( pxConnection->xCallbacks[ i ] );
break;
}
}
}
/* Set the members of the callback entry. */
if( i < mqttconfigSUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS )
{
pxCallback->pvParameter = pvParameter;
pxCallback->usTopicFilterLength = usTopicFilterLength;
pxCallback->xFunction = xCallback;
( void ) strncpy( pxCallback->pcTopicFilter, pcTopicFilter, usTopicFilterLength );
xStatus = pdPASS;
}
( void ) xSemaphoreGive( ( QueueHandle_t ) &( pxConnection->xConnectionMutex ) );
}
return xStatus;
}
/*-----------------------------------------------------------*/
static MQTTCallback_t * prvFindCallback( MQTTConnection_t * const pxConnection,
const char * const pcTopicFilter,
uint16_t usTopicFilterLength )
{
BaseType_t i = 0;
MQTTCallback_t * pxResult = NULL;
/* Search the callback conversion table for the topic filter. */
for( i = 0; i < mqttconfigSUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS; i++ )
{
if( ( pxConnection->xCallbacks[ i ].usTopicFilterLength == usTopicFilterLength ) &&
( strncmp( pxConnection->xCallbacks[ i ].pcTopicFilter,
pcTopicFilter,
usTopicFilterLength ) == 0 ) )
{
pxResult = &( pxConnection->xCallbacks[ i ] );
break;
}
}
return pxResult;
}
/*-----------------------------------------------------------*/
static void prvRemoveCallback( MQTTConnection_t * const pxConnection,
const char * const pcTopicFilter,
uint16_t usTopicFilterLength )
{
MQTTCallback_t * pxCallback = NULL;
/* Prevent other tasks from modifying stored callbacks while this function
* runs. */
if( xSemaphoreTake( ( QueueHandle_t ) &( pxConnection->xConnectionMutex ),
portMAX_DELAY ) == pdTRUE )
{
/* Find the given topic filter. */
pxCallback = prvFindCallback( pxConnection, pcTopicFilter, usTopicFilterLength );
if( pxCallback != NULL )
{
/* Clear the callback entry. */
mqttconfigASSERT( pxCallback->xInUse == pdTRUE );
( void ) memset( pxCallback, 0x00, sizeof( MQTTCallback_t ) );
}
( void ) xSemaphoreGive( ( QueueHandle_t ) &( pxConnection->xConnectionMutex ) );
}
}
#endif /* if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 ) */
/*-----------------------------------------------------------*/
IotMqttConnection_t MQTT_AGENT_Getv2Connection( MQTTAgentHandle_t xMQTTHandle )
{
MQTTConnection_t * pxConnection = ( MQTTConnection_t * ) xMQTTHandle;
return pxConnection->xMQTTConnection;
}
/*-----------------------------------------------------------*/
BaseType_t MQTT_AGENT_Init( void )
{
BaseType_t xStatus = pdFALSE;
/* Call the initialization function of MQTT v2. */
if( IotMqtt_Init() == IOT_MQTT_SUCCESS )
{
xStatus = pdTRUE;
}
return xStatus;
}
/*-----------------------------------------------------------*/
MQTTAgentReturnCode_t MQTT_AGENT_Create( MQTTAgentHandle_t * const pxMQTTHandle )
{
MQTTConnection_t * pxNewConnection = NULL;
MQTTAgentReturnCode_t xStatus = eMQTTAgentSuccess;
/* Check how many brokers are available; fail if all brokers are in use. */
taskENTER_CRITICAL();
{
if( uxAvailableBrokers == 0 )
{
xStatus = eMQTTAgentFailure;
}
else
{
uxAvailableBrokers--;
mqttconfigASSERT( uxAvailableBrokers <= mqttconfigMAX_BROKERS );
}
}
taskEXIT_CRITICAL();
/* Allocate memory for an MQTT connection. */
if( xStatus == eMQTTAgentSuccess )
{
pxNewConnection = pvPortMalloc( sizeof( MQTTConnection_t ) );
if( pxNewConnection == NULL )
{
xStatus = eMQTTAgentFailure;
taskENTER_CRITICAL();
{
uxAvailableBrokers++;
mqttconfigASSERT( uxAvailableBrokers <= mqttconfigMAX_BROKERS );
}
taskEXIT_CRITICAL();
}
else
{
( void ) memset( pxNewConnection, 0x00, sizeof( MQTTConnection_t ) );
pxNewConnection->xMQTTConnection = IOT_MQTT_CONNECTION_INITIALIZER;
}
}
/* Create the connection mutex and set the output parameter. */
if( xStatus == eMQTTAgentSuccess )
{
( void ) xSemaphoreCreateMutexStatic( &( pxNewConnection->xConnectionMutex ) );
*pxMQTTHandle = ( MQTTAgentHandle_t ) pxNewConnection;
}
return xStatus;
}
/*-----------------------------------------------------------*/
MQTTAgentReturnCode_t MQTT_AGENT_Delete( MQTTAgentHandle_t xMQTTHandle )
{
MQTTConnection_t * pxConnection = ( MQTTConnection_t * ) xMQTTHandle;
/* Clean up any allocated MQTT or network resources. */
if( pxConnection->xMQTTConnection != IOT_MQTT_CONNECTION_INITIALIZER )
{
IotMqtt_Disconnect( pxConnection->xMQTTConnection, IOT_MQTT_FLAG_CLEANUP_ONLY );
pxConnection->xMQTTConnection = IOT_MQTT_CONNECTION_INITIALIZER;
}
/* Free memory used by the MQTT connection. */
vPortFree( pxConnection );
/* Increment the number of available brokers. */
taskENTER_CRITICAL();
{
uxAvailableBrokers++;
mqttconfigASSERT( uxAvailableBrokers <= mqttconfigMAX_BROKERS );
}
taskEXIT_CRITICAL();
return eMQTTAgentSuccess;
}
/*-----------------------------------------------------------*/
MQTTAgentReturnCode_t MQTT_AGENT_Connect( MQTTAgentHandle_t xMQTTHandle,
const MQTTAgentConnectParams_t * const pxConnectParams,
TickType_t xTimeoutTicks )
{
MQTTAgentReturnCode_t xStatus = eMQTTAgentSuccess;
IotMqttError_t xMqttStatus = IOT_MQTT_STATUS_PENDING;
MQTTConnection_t * pxConnection = ( MQTTConnection_t * ) xMQTTHandle;
IotNetworkServerInfo_t xServerInfo = { 0 };
IotNetworkCredentials_t xCredentials = AWS_IOT_NETWORK_CREDENTIALS_AFR_INITIALIZER, * pxCredentials = NULL;
IotMqttNetworkInfo_t xNetworkInfo = IOT_MQTT_NETWORK_INFO_INITIALIZER;
IotMqttConnectInfo_t xMqttConnectInfo = IOT_MQTT_CONNECT_INFO_INITIALIZER;
/* Copy the global callback and parameter. */
pxConnection->pxCallback = pxConnectParams->pxCallback;
pxConnection->pvUserData = pxConnectParams->pvUserData;
/* Set the TLS info for a secured connection. */
if( ( pxConnectParams->xSecuredConnection == pdTRUE ) ||
( ( pxConnectParams->xFlags & mqttagentREQUIRE_TLS ) == mqttagentREQUIRE_TLS ) )
{
pxCredentials = &xCredentials;
/* Set the server certificate. Other credentials are set by the initializer. */
xCredentials.pRootCa = pxConnectParams->pcCertificate;
xCredentials.rootCaSize = ( size_t ) pxConnectParams->ulCertificateSize;
/* Disable ALPN if requested. */
if( ( pxConnectParams->xFlags & mqttagentUSE_AWS_IOT_ALPN_443 ) == 0 )
{
xCredentials.pAlpnProtos = NULL;
}
/* Disable SNI if requested. */
if( ( pxConnectParams->xURLIsIPAddress == pdTRUE ) ||
( ( pxConnectParams->xFlags & mqttagentURL_IS_IP_ADDRESS ) == mqttagentURL_IS_IP_ADDRESS ) )
{
xCredentials.disableSni = true;
}
}
/* Set the server info. */
xServerInfo.pHostName = pxConnectParams->pcURL;
xServerInfo.port = pxConnectParams->usPort;
/* Set the members of the network info. */
xNetworkInfo.createNetworkConnection = true;
xNetworkInfo.u.setup.pNetworkServerInfo = &xServerInfo;
xNetworkInfo.u.setup.pNetworkCredentialInfo = pxCredentials;
xNetworkInfo.pNetworkInterface = IOT_NETWORK_INTERFACE_AFR;
if( pxConnectParams->pxCallback != NULL )
{
xNetworkInfo.disconnectCallback.function = prvDisconnectCallbackWrapper;
xNetworkInfo.disconnectCallback.pCallbackContext = pxConnection;
}
/* Set the members of the MQTT connect info. */
xMqttConnectInfo.awsIotMqttMode = true;
xMqttConnectInfo.cleanSession = true;
xMqttConnectInfo.pClientIdentifier = ( const char * ) ( pxConnectParams->pucClientId );
xMqttConnectInfo.clientIdentifierLength = pxConnectParams->usClientIdLength;
xMqttConnectInfo.keepAliveSeconds = mqttconfigKEEP_ALIVE_INTERVAL_SECONDS;
/* Call MQTT v2's CONNECT function. */
xMqttStatus = IotMqtt_Connect( &xNetworkInfo,
&xMqttConnectInfo,
mqttTICKS_TO_MS( xTimeoutTicks ),
&( pxConnection->xMQTTConnection ) );
xStatus = prvConvertReturnCode( xMqttStatus );
/* Add a subscription to "#" to support the global callback when subscription
* manager is disabled. */
#if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 0 )
IotMqttSubscription_t xGlobalSubscription = IOT_MQTT_SUBSCRIPTION_INITIALIZER;
IotMqttReference_t xGlobalSubscriptionRef = IOT_MQTT_REFERENCE_INITIALIZER;
if( xStatus == eMQTTAgentSuccess )
{
xGlobalSubscription.pTopicFilter = "#";
xGlobalSubscription.topicFilterLength = 1;
xGlobalSubscription.qos = 0;
xGlobalSubscription.callback.param1 = pxConnection;
xGlobalSubscription.callback.function = prvPublishCallbackWrapper;
xMqttStatus = IotMqtt_Subscribe( pxConnection->xMQTTConnection,
&xGlobalSubscription,
1,
IOT_MQTT_FLAG_WAITABLE,
NULL,
&xGlobalSubscriptionRef );
xStatus = prvConvertReturnCode( xMqttStatus );
}
/* Wait for the subscription to "#" to complete. */
if( xStatus == eMQTTAgentSuccess )
{
xMqttStatus = IotMqtt_Wait( xGlobalSubscriptionRef,
mqttTICKS_TO_MS( xTimeoutTicks ) );
xStatus = prvConvertReturnCode( xMqttStatus );
}
#endif /* if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 ) */
return xStatus;
}
/*-----------------------------------------------------------*/
MQTTAgentReturnCode_t MQTT_AGENT_Disconnect( MQTTAgentHandle_t xMQTTHandle,
TickType_t xTimeoutTicks )
{
MQTTConnection_t * pxConnection = ( MQTTConnection_t * ) xMQTTHandle;
/* MQTT v2's DISCONNECT function does not have a timeout argument. */
( void ) xTimeoutTicks;
/* Check that the connection is established. */
if( pxConnection->xMQTTConnection != IOT_MQTT_CONNECTION_INITIALIZER )
{
/* Call MQTT v2's DISCONNECT function. */
IotMqtt_Disconnect( pxConnection->xMQTTConnection,
0 );
pxConnection->xMQTTConnection = IOT_MQTT_CONNECTION_INITIALIZER;
}
return eMQTTAgentSuccess;
}
/*-----------------------------------------------------------*/
MQTTAgentReturnCode_t MQTT_AGENT_Subscribe( MQTTAgentHandle_t xMQTTHandle,
const MQTTAgentSubscribeParams_t * const pxSubscribeParams,
TickType_t xTimeoutTicks )
{
MQTTAgentReturnCode_t xStatus = eMQTTAgentSuccess;
IotMqttError_t xMqttStatus = IOT_MQTT_STATUS_PENDING;
MQTTConnection_t * pxConnection = ( MQTTConnection_t * ) xMQTTHandle;
IotMqttSubscription_t xSubscription = IOT_MQTT_SUBSCRIPTION_INITIALIZER;
/* Store the topic filter if subscription management is enabled. */
#if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 )
/* Check topic filter length. */
if( pxSubscribeParams->usTopicLength > mqttconfigSUBSCRIPTION_MANAGER_MAX_TOPIC_LENGTH )
{
xStatus = eMQTTAgentFailure;
}
/* Store the subscription. */
if( prvStoreCallback( pxConnection,
( const char * ) pxSubscribeParams->pucTopic,
pxSubscribeParams->usTopicLength,
pxSubscribeParams->pxPublishCallback,
pxSubscribeParams->pvPublishCallbackContext ) == pdFAIL )
{
xStatus = eMQTTAgentFailure;
}
#endif /* if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 ) */
/* Call MQTT v2 blocking SUBSCRIBE function. */
if( xStatus == eMQTTAgentSuccess )
{
/* Set the members of the MQTT subscription. */
xSubscription.pTopicFilter = ( const char * ) ( pxSubscribeParams->pucTopic );
xSubscription.topicFilterLength = pxSubscribeParams->usTopicLength;
xSubscription.qos = ( IotMqttQos_t ) pxSubscribeParams->xQoS;
xSubscription.callback.pCallbackContext = pxConnection;
xSubscription.callback.function = prvPublishCallbackWrapper;
xMqttStatus = IotMqtt_TimedSubscribe( pxConnection->xMQTTConnection,
&xSubscription,
1,
0,
mqttTICKS_TO_MS( xTimeoutTicks ) );
xStatus = prvConvertReturnCode( xMqttStatus );
}
return xStatus;
}
/*-----------------------------------------------------------*/
MQTTAgentReturnCode_t MQTT_AGENT_Unsubscribe( MQTTAgentHandle_t xMQTTHandle,
const MQTTAgentUnsubscribeParams_t * const pxUnsubscribeParams,
TickType_t xTimeoutTicks )
{
IotMqttError_t xMqttStatus = IOT_MQTT_STATUS_PENDING;
MQTTConnection_t * pxConnection = ( MQTTConnection_t * ) xMQTTHandle;
IotMqttSubscription_t xSubscription = IOT_MQTT_SUBSCRIPTION_INITIALIZER;
/* Remove any subscription callback that may be registered. */
#if ( mqttconfigENABLE_SUBSCRIPTION_MANAGEMENT == 1 )
prvRemoveCallback( pxConnection,
( const char * ) ( pxUnsubscribeParams->pucTopic ),
pxUnsubscribeParams->usTopicLength );
#endif
/* Set the members of the subscription to remove. */
xSubscription.pTopicFilter = ( const char * ) ( pxUnsubscribeParams->pucTopic );
xSubscription.topicFilterLength = pxUnsubscribeParams->usTopicLength;
xSubscription.callback.pCallbackContext = pxConnection;
xSubscription.callback.function = prvPublishCallbackWrapper;
/* Call MQTT v2 blocking UNSUBSCRIBE function. */
xMqttStatus = IotMqtt_TimedUnsubscribe( pxConnection->xMQTTConnection,
&xSubscription,
1,
0,
mqttTICKS_TO_MS( xTimeoutTicks ) );
return prvConvertReturnCode( xMqttStatus );
}
/*-----------------------------------------------------------*/
MQTTAgentReturnCode_t MQTT_AGENT_Publish( MQTTAgentHandle_t xMQTTHandle,
const MQTTAgentPublishParams_t * const pxPublishParams,
TickType_t xTimeoutTicks )
{
IotMqttError_t xMqttStatus = IOT_MQTT_STATUS_PENDING;
MQTTConnection_t * pxConnection = ( MQTTConnection_t * ) xMQTTHandle;
IotMqttPublishInfo_t xPublishInfo = IOT_MQTT_PUBLISH_INFO_INITIALIZER;
/* Set the members of the publish info. */
xPublishInfo.pTopicName = ( const char * ) pxPublishParams->pucTopic;
xPublishInfo.topicNameLength = pxPublishParams->usTopicLength;
xPublishInfo.qos = ( IotMqttQos_t ) pxPublishParams->xQoS;
xPublishInfo.pPayload = ( const void * ) pxPublishParams->pvData;
xPublishInfo.payloadLength = pxPublishParams->ulDataLength;
/* Call the MQTT v2 blocking PUBLISH function. */
xMqttStatus = IotMqtt_TimedPublish( pxConnection->xMQTTConnection,
&xPublishInfo,
0,
mqttTICKS_TO_MS( xTimeoutTicks ) );
return prvConvertReturnCode( xMqttStatus );
}
/*-----------------------------------------------------------*/
MQTTAgentReturnCode_t MQTT_AGENT_ReturnBuffer( MQTTAgentHandle_t xMQTTHandle,
MQTTBufferHandle_t xBufferHandle )
{
( void ) xMQTTHandle;
/* Free the MQTT buffer. */
vPortFree( xBufferHandle );
return eMQTTAgentSuccess;
}
/*-----------------------------------------------------------*/

View file

@ -0,0 +1,912 @@
/*
* 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_network.c
* @brief Implements functions involving transport layer connections.
*/
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <string.h>
/* Error handling include. */
#include "private/iot_error.h"
/* MQTT internal include. */
#include "private/iot_mqtt_internal.h"
/* Platform layer includes. */
#include "platform/iot_threads.h"
/*-----------------------------------------------------------*/
/**
* @brief Check if an incoming packet type is valid.
*
* @param[in] packetType The packet type to check.
*
* @return `true` if the packet type is valid; `false` otherwise.
*/
static bool _incomingPacketValid( uint8_t packetType );
/**
* @brief Get an incoming MQTT packet from the network.
*
* @param[in] pNetworkConnection Network connection to use for receive, which
* may be different from the network connection associated with the MQTT connection.
* @param[in] pMqttConnection The associated MQTT connection.
* @param[out] pIncomingPacket Output parameter for the incoming packet.
*
* @return #IOT_MQTT_SUCCESS, #IOT_MQTT_NO_MEMORY or #IOT_MQTT_BAD_RESPONSE.
*/
static IotMqttError_t _getIncomingPacket( void * pNetworkConnection,
const _mqttConnection_t * pMqttConnection,
_mqttPacket_t * pIncomingPacket );
/**
* @brief Deserialize a packet received from the network.
*
* @param[in] pMqttConnection The associated MQTT connection.
* @param[in] pIncomingPacket The packet received from the network.
*
* @return #IOT_MQTT_SUCCESS, #IOT_MQTT_NO_MEMORY, #IOT_MQTT_NETWORK_ERROR,
* #IOT_MQTT_SCHEDULING_ERROR, #IOT_MQTT_BAD_RESPONSE, or #IOT_MQTT_SERVER_REFUSED.
*/
static IotMqttError_t _deserializeIncomingPacket( _mqttConnection_t * pMqttConnection,
_mqttPacket_t * pIncomingPacket );
/**
* @brief Send a PUBACK for a received QoS 1 PUBLISH packet.
*
* @param[in] pMqttConnection Which connection the PUBACK should be sent over.
* @param[in] packetIdentifier Which packet identifier to include in PUBACK.
*/
static void _sendPuback( _mqttConnection_t * pMqttConnection,
uint16_t packetIdentifier );
/*-----------------------------------------------------------*/
static bool _incomingPacketValid( uint8_t packetType )
{
bool status = true;
/* Check packet type. Mask out lower bits to ignore flags. */
switch( packetType & 0xf0 )
{
/* Valid incoming packet types. */
case MQTT_PACKET_TYPE_CONNACK:
case MQTT_PACKET_TYPE_PUBLISH:
case MQTT_PACKET_TYPE_PUBACK:
case MQTT_PACKET_TYPE_SUBACK:
case MQTT_PACKET_TYPE_UNSUBACK:
case MQTT_PACKET_TYPE_PINGRESP:
break;
/* Any other packet type is invalid. */
default:
status = false;
break;
}
return status;
}
/*-----------------------------------------------------------*/
static IotMqttError_t _getIncomingPacket( void * pNetworkConnection,
const _mqttConnection_t * pMqttConnection,
_mqttPacket_t * pIncomingPacket )
{
IOT_FUNCTION_ENTRY( IotMqttError_t, IOT_MQTT_SUCCESS );
size_t dataBytesRead = 0;
/* Default functions for retrieving packet type and length. */
uint8_t ( * getPacketType )( void *,
const IotNetworkInterface_t * ) = _IotMqtt_GetPacketType;
size_t ( * getRemainingLength )( void *,
const IotNetworkInterface_t * ) = _IotMqtt_GetRemainingLength;
/* No buffer for remaining data should be allocated. */
IotMqtt_Assert( pIncomingPacket->pRemainingData == NULL );
IotMqtt_Assert( pIncomingPacket->remainingLength == 0 );
/* Choose packet type and length functions. */
#if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1
if( pMqttConnection->pSerializer != NULL )
{
if( pMqttConnection->pSerializer->getPacketType != NULL )
{
getPacketType = pMqttConnection->pSerializer->getPacketType;
}
else
{
EMPTY_ELSE_MARKER;
}
if( pMqttConnection->pSerializer->getRemainingLength != NULL )
{
getRemainingLength = pMqttConnection->pSerializer->getRemainingLength;
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
#endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */
/* Read the packet type, which is the first byte available. */
pIncomingPacket->type = getPacketType( pNetworkConnection,
pMqttConnection->pNetworkInterface );
/* Check that the incoming packet type is valid. */
if( _incomingPacketValid( pIncomingPacket->type ) == false )
{
IotLogError( "(MQTT connection %p) Unknown packet type %02x received.",
pMqttConnection,
pIncomingPacket->type );
IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_BAD_RESPONSE );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Read the remaining length. */
pIncomingPacket->remainingLength = getRemainingLength( pNetworkConnection,
pMqttConnection->pNetworkInterface );
if( pIncomingPacket->remainingLength == MQTT_REMAINING_LENGTH_INVALID )
{
IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_BAD_RESPONSE );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Allocate a buffer for the remaining data and read the data. */
if( pIncomingPacket->remainingLength > 0 )
{
pIncomingPacket->pRemainingData = IotMqtt_MallocMessage( pIncomingPacket->remainingLength );
if( pIncomingPacket->pRemainingData == NULL )
{
IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_NO_MEMORY );
}
else
{
EMPTY_ELSE_MARKER;
}
dataBytesRead = pMqttConnection->pNetworkInterface->receive( pNetworkConnection,
pIncomingPacket->pRemainingData,
pIncomingPacket->remainingLength );
if( dataBytesRead != pIncomingPacket->remainingLength )
{
IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_BAD_RESPONSE );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Clean up on error. */
IOT_FUNCTION_CLEANUP_BEGIN();
if( status != IOT_MQTT_SUCCESS )
{
if( pIncomingPacket->pRemainingData != NULL )
{
IotMqtt_FreeMessage( pIncomingPacket->pRemainingData );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
IOT_FUNCTION_CLEANUP_END();
}
/*-----------------------------------------------------------*/
static IotMqttError_t _deserializeIncomingPacket( _mqttConnection_t * pMqttConnection,
_mqttPacket_t * pIncomingPacket )
{
IotMqttError_t status = IOT_MQTT_STATUS_PENDING;
_mqttOperation_t * pOperation = NULL;
/* Deserializer function. */
IotMqttError_t ( * deserialize )( _mqttPacket_t * ) = NULL;
/* A buffer for remaining data must be allocated if remaining length is not 0. */
IotMqtt_Assert( ( pIncomingPacket->remainingLength > 0 ) ==
( pIncomingPacket->pRemainingData != NULL ) );
/* Only valid packets should be given to this function. */
IotMqtt_Assert( _incomingPacketValid( pIncomingPacket->type ) == true );
/* Mask out the low bits of packet type to ignore flags. */
switch( ( pIncomingPacket->type & 0xf0 ) )
{
case MQTT_PACKET_TYPE_CONNACK:
IotLogDebug( "(MQTT connection %p) CONNACK in data stream.", pMqttConnection );
/* Choose CONNACK deserializer. */
deserialize = _IotMqtt_DeserializeConnack;
#if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1
if( pMqttConnection->pSerializer != NULL )
{
if( pMqttConnection->pSerializer->deserialize.connack != NULL )
{
deserialize = pMqttConnection->pSerializer->deserialize.connack;
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
#endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */
/* Deserialize CONNACK and notify of result. */
status = deserialize( pIncomingPacket );
pOperation = _IotMqtt_FindOperation( pMqttConnection,
IOT_MQTT_CONNECT,
NULL );
if( pOperation != NULL )
{
pOperation->u.operation.status = status;
_IotMqtt_Notify( pOperation );
}
else
{
EMPTY_ELSE_MARKER;
}
break;
case MQTT_PACKET_TYPE_PUBLISH:
IotLogDebug( "(MQTT connection %p) PUBLISH in data stream.", pMqttConnection );
/* Allocate memory to handle the incoming PUBLISH. */
pOperation = IotMqtt_MallocOperation( sizeof( _mqttOperation_t ) );
if( pOperation == NULL )
{
IotLogWarn( "Failed to allocate memory for incoming PUBLISH." );
status = IOT_MQTT_NO_MEMORY;
break;
}
else
{
/* Set the members of the incoming PUBLISH operation. */
( void ) memset( pOperation, 0x00, sizeof( _mqttOperation_t ) );
pOperation->incomingPublish = true;
pOperation->pMqttConnection = pMqttConnection;
pIncomingPacket->u.pIncomingPublish = pOperation;
}
/* Choose a PUBLISH deserializer. */
deserialize = _IotMqtt_DeserializePublish;
#if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1
if( pMqttConnection->pSerializer != NULL )
{
if( pMqttConnection->pSerializer->deserialize.publish != NULL )
{
deserialize = pMqttConnection->pSerializer->deserialize.publish;
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
#endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */
/* Deserialize incoming PUBLISH. */
status = deserialize( pIncomingPacket );
if( status == IOT_MQTT_SUCCESS )
{
/* Send a PUBACK for QoS 1 PUBLISH. */
if( pOperation->u.publish.publishInfo.qos == IOT_MQTT_QOS_1 )
{
_sendPuback( pMqttConnection, pIncomingPacket->packetIdentifier );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Transfer ownership of the received MQTT packet to the PUBLISH operation. */
pOperation->u.publish.pReceivedData = pIncomingPacket->pRemainingData;
pIncomingPacket->pRemainingData = NULL;
/* Add the PUBLISH to the list of operations pending processing. */
IotMutex_Lock( &( pMqttConnection->referencesMutex ) );
IotListDouble_InsertHead( &( pMqttConnection->pendingProcessing ),
&( pOperation->link ) );
IotMutex_Unlock( &( pMqttConnection->referencesMutex ) );
/* Increment the MQTT connection reference count before scheduling an
* incoming PUBLISH. */
if( _IotMqtt_IncrementConnectionReferences( pMqttConnection ) == true )
{
/* Schedule PUBLISH for callback invocation. */
status = _IotMqtt_ScheduleOperation( pOperation, _IotMqtt_ProcessIncomingPublish, 0 );
}
else
{
status = IOT_MQTT_NETWORK_ERROR;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Free PUBLISH operation on error. */
if( status != IOT_MQTT_SUCCESS )
{
/* Check ownership of the received MQTT packet. */
if( pOperation->u.publish.pReceivedData != NULL )
{
/* Retrieve the pointer MQTT packet pointer so it may be freed later. */
IotMqtt_Assert( pIncomingPacket->pRemainingData == NULL );
pIncomingPacket->pRemainingData = ( uint8_t * ) pOperation->u.publish.pReceivedData;
}
else
{
EMPTY_ELSE_MARKER;
}
/* Remove operation from pending processing list. */
IotMutex_Lock( &( pMqttConnection->referencesMutex ) );
if( IotLink_IsLinked( &( pOperation->link ) ) == true )
{
IotListDouble_Remove( &( pOperation->link ) );
}
else
{
EMPTY_ELSE_MARKER;
}
IotMutex_Unlock( &( pMqttConnection->referencesMutex ) );
IotMqtt_Assert( pOperation != NULL );
IotMqtt_FreeOperation( pOperation );
}
else
{
EMPTY_ELSE_MARKER;
}
break;
case MQTT_PACKET_TYPE_PUBACK:
IotLogDebug( "(MQTT connection %p) PUBACK in data stream.", pMqttConnection );
/* Choose PUBACK deserializer. */
deserialize = _IotMqtt_DeserializePuback;
#if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1
if( pMqttConnection->pSerializer != NULL )
{
if( pMqttConnection->pSerializer->deserialize.puback != NULL )
{
deserialize = pMqttConnection->pSerializer->deserialize.puback;
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
#endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */
/* Deserialize PUBACK and notify of result. */
status = deserialize( pIncomingPacket );
pOperation = _IotMqtt_FindOperation( pMqttConnection,
IOT_MQTT_PUBLISH_TO_SERVER,
&( pIncomingPacket->packetIdentifier ) );
if( pOperation != NULL )
{
pOperation->u.operation.status = status;
_IotMqtt_Notify( pOperation );
}
else
{
EMPTY_ELSE_MARKER;
}
break;
case MQTT_PACKET_TYPE_SUBACK:
IotLogDebug( "(MQTT connection %p) SUBACK in data stream.", pMqttConnection );
/* Choose SUBACK deserializer. */
deserialize = _IotMqtt_DeserializeSuback;
#if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1
if( pMqttConnection->pSerializer != NULL )
{
if( pMqttConnection->pSerializer->deserialize.suback != NULL )
{
deserialize = pMqttConnection->pSerializer->deserialize.suback;
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
#endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */
/* Deserialize SUBACK and notify of result. */
pIncomingPacket->u.pMqttConnection = pMqttConnection;
status = deserialize( pIncomingPacket );
pOperation = _IotMqtt_FindOperation( pMqttConnection,
IOT_MQTT_SUBSCRIBE,
&( pIncomingPacket->packetIdentifier ) );
if( pOperation != NULL )
{
pOperation->u.operation.status = status;
_IotMqtt_Notify( pOperation );
}
else
{
EMPTY_ELSE_MARKER;
}
break;
case MQTT_PACKET_TYPE_UNSUBACK:
IotLogDebug( "(MQTT connection %p) UNSUBACK in data stream.", pMqttConnection );
/* Choose UNSUBACK deserializer. */
deserialize = _IotMqtt_DeserializeUnsuback;
#if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1
if( pMqttConnection->pSerializer != NULL )
{
if( pMqttConnection->pSerializer->deserialize.unsuback != NULL )
{
deserialize = pMqttConnection->pSerializer->deserialize.unsuback;
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
#endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */
/* Deserialize UNSUBACK and notify of result. */
status = deserialize( pIncomingPacket );
pOperation = _IotMqtt_FindOperation( pMqttConnection,
IOT_MQTT_UNSUBSCRIBE,
&( pIncomingPacket->packetIdentifier ) );
if( pOperation != NULL )
{
pOperation->u.operation.status = status;
_IotMqtt_Notify( pOperation );
}
else
{
EMPTY_ELSE_MARKER;
}
break;
default:
/* The only remaining valid type is PINGRESP. */
IotMqtt_Assert( ( pIncomingPacket->type & 0xf0 ) == MQTT_PACKET_TYPE_PINGRESP );
IotLogDebug( "(MQTT connection %p) PINGRESP in data stream.", pMqttConnection );
/* Choose PINGRESP deserializer. */
deserialize = _IotMqtt_DeserializePingresp;
#if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1
if( pMqttConnection->pSerializer != NULL )
{
if( pMqttConnection->pSerializer->deserialize.pingresp != NULL )
{
deserialize = pMqttConnection->pSerializer->deserialize.pingresp;
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
#endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */
/* Deserialize PINGRESP. */
status = deserialize( pIncomingPacket );
if( status == IOT_MQTT_SUCCESS )
{
IotMutex_Lock( &( pMqttConnection->referencesMutex ) );
if( pMqttConnection->keepAliveFailure == false )
{
IotLogWarn( "(MQTT connection %p) Unexpected PINGRESP received.",
pMqttConnection );
}
else
{
IotLogDebug( "(MQTT connection %p) PINGRESP successfully parsed.",
pMqttConnection );
pMqttConnection->keepAliveFailure = false;
}
IotMutex_Unlock( &( pMqttConnection->referencesMutex ) );
}
else
{
EMPTY_ELSE_MARKER;
}
break;
}
if( status != IOT_MQTT_SUCCESS )
{
IotLogError( "(MQTT connection %p) Packet parser status %s.",
pMqttConnection,
IotMqtt_strerror( status ) );
}
else
{
EMPTY_ELSE_MARKER;
}
return status;
}
/*-----------------------------------------------------------*/
static void _sendPuback( _mqttConnection_t * pMqttConnection,
uint16_t packetIdentifier )
{
IotMqttError_t serializeStatus = IOT_MQTT_SUCCESS;
uint8_t * pPuback = NULL;
size_t pubackSize = 0, bytesSent = 0;
/* Default PUBACK serializer and free packet functions. */
IotMqttError_t ( * serializePuback )( uint16_t,
uint8_t **,
size_t * ) = _IotMqtt_SerializePuback;
void ( * freePacket )( uint8_t * ) = _IotMqtt_FreePacket;
IotLogDebug( "(MQTT connection %p) Sending PUBACK for received PUBLISH %hu.",
pMqttConnection,
packetIdentifier );
/* Choose PUBACK serializer and free packet functions. */
#if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1
if( pMqttConnection->pSerializer != NULL )
{
if( pMqttConnection->pSerializer->serialize.puback != NULL )
{
serializePuback = pMqttConnection->pSerializer->serialize.puback;
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
#endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */
#if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1
if( pMqttConnection->pSerializer != NULL )
{
if( pMqttConnection->pSerializer->freePacket != NULL )
{
freePacket = pMqttConnection->pSerializer->freePacket;
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
#endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */
/* Generate a PUBACK packet from the packet identifier. */
serializeStatus = serializePuback( packetIdentifier,
&pPuback,
&pubackSize );
if( serializeStatus != IOT_MQTT_SUCCESS )
{
IotLogWarn( "(MQTT connection %p) Failed to generate PUBACK packet for "
"received PUBLISH %hu.",
pMqttConnection,
packetIdentifier );
}
else
{
bytesSent = pMqttConnection->pNetworkInterface->send( pMqttConnection->pNetworkConnection,
pPuback,
pubackSize );
if( bytesSent != pubackSize )
{
IotLogWarn( "(MQTT connection %p) Failed to send PUBACK for received"
" PUBLISH %hu.",
pMqttConnection,
packetIdentifier );
}
else
{
IotLogDebug( "(MQTT connection %p) PUBACK for received PUBLISH %hu sent.",
pMqttConnection,
packetIdentifier );
}
freePacket( pPuback );
}
}
/*-----------------------------------------------------------*/
bool _IotMqtt_GetNextByte( void * pNetworkConnection,
const IotNetworkInterface_t * pNetworkInterface,
uint8_t * pIncomingByte )
{
bool status = false;
uint8_t incomingByte = 0;
size_t bytesReceived = 0;
/* Attempt to read 1 byte. */
bytesReceived = pNetworkInterface->receive( pNetworkConnection,
&incomingByte,
1 );
/* Set the output parameter and return success if 1 byte was read. */
if( bytesReceived == 1 )
{
*pIncomingByte = incomingByte;
status = true;
}
else
{
/* Network receive must return 0 on failure. */
IotMqtt_Assert( bytesReceived == 0 );
}
return status;
}
/*-----------------------------------------------------------*/
void _IotMqtt_CloseNetworkConnection( IotMqttDisconnectReason_t disconnectReason,
_mqttConnection_t * pMqttConnection )
{
IotTaskPoolError_t taskPoolStatus = IOT_TASKPOOL_SUCCESS;
IotNetworkError_t closeStatus = IOT_NETWORK_SUCCESS;
IotMqttCallbackParam_t callbackParam = { .u.message = { 0 } };
/* Mark the MQTT connection as disconnected and the keep-alive as failed. */
IotMutex_Lock( &( pMqttConnection->referencesMutex ) );
pMqttConnection->disconnected = true;
pMqttConnection->keepAliveFailure = true;
if( pMqttConnection->keepAliveMs != 0 )
{
/* Keep-alive must have a PINGREQ allocated. */
IotMqtt_Assert( pMqttConnection->pPingreqPacket != NULL );
IotMqtt_Assert( pMqttConnection->pingreqPacketSize != 0 );
/* PINGREQ provides a reference to the connection, so reference count must
* be nonzero. */
IotMqtt_Assert( pMqttConnection->references > 0 );
/* Attempt to cancel the keep-alive job. */
taskPoolStatus = IotTaskPool_TryCancel( IOT_SYSTEM_TASKPOOL,
pMqttConnection->keepAliveJob,
NULL );
/* If the keep-alive job was not canceled, it must be already executing.
* Any other return value is invalid. */
IotMqtt_Assert( ( taskPoolStatus == IOT_TASKPOOL_SUCCESS ) ||
( taskPoolStatus == IOT_TASKPOOL_CANCEL_FAILED ) );
/* Clean up keep-alive if its job was successfully canceled. Otherwise,
* the executing keep-alive job will clean up itself. */
if( taskPoolStatus == IOT_TASKPOOL_SUCCESS )
{
/* Clean up PINGREQ packet and job. */
_IotMqtt_FreePacket( pMqttConnection->pPingreqPacket );
/* Clear data about the keep-alive. */
pMqttConnection->keepAliveMs = 0;
pMqttConnection->pPingreqPacket = NULL;
pMqttConnection->pingreqPacketSize = 0;
/* Keep-alive is cleaned up; decrement reference count. Since this
* function must be followed with a call to DISCONNECT, a check to
* destroy the connection is not done here. */
pMqttConnection->references--;
IotLogDebug( "(MQTT connection %p) Keep-alive job canceled and cleaned up.",
pMqttConnection );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
IotMutex_Unlock( &( pMqttConnection->referencesMutex ) );
/* Close the network connection. */
if( pMqttConnection->pNetworkInterface->close != NULL )
{
closeStatus = pMqttConnection->pNetworkInterface->close( pMqttConnection->pNetworkConnection );
if( closeStatus == IOT_NETWORK_SUCCESS )
{
IotLogInfo( "(MQTT connection %p) Network connection closed.", pMqttConnection );
}
else
{
IotLogWarn( "(MQTT connection %p) Failed to close network connection, error %d.",
pMqttConnection,
closeStatus );
}
}
else
{
IotLogWarn( "(MQTT connection %p) No network close function was set. Network connection"
" not closed.", pMqttConnection );
}
/* Invoke the disconnect callback. */
if( pMqttConnection->disconnectCallback.function != NULL )
{
/* Set the members of the callback parameter. */
callbackParam.mqttConnection = pMqttConnection;
callbackParam.u.disconnectReason = disconnectReason;
pMqttConnection->disconnectCallback.function( pMqttConnection->disconnectCallback.pCallbackContext,
&callbackParam );
}
else
{
EMPTY_ELSE_MARKER;
}
}
/*-----------------------------------------------------------*/
void IotMqtt_ReceiveCallback( void * pNetworkConnection,
void * pReceiveContext )
{
IotMqttError_t status = IOT_MQTT_SUCCESS;
_mqttPacket_t incomingPacket = { .u.pMqttConnection = NULL };
/* Cast context to correct type. */
_mqttConnection_t * pMqttConnection = ( _mqttConnection_t * ) pReceiveContext;
/* Read an MQTT packet from the network. */
status = _getIncomingPacket( pNetworkConnection,
pMqttConnection,
&incomingPacket );
if( status == IOT_MQTT_SUCCESS )
{
/* Deserialize the received packet. */
status = _deserializeIncomingPacket( pMqttConnection,
&incomingPacket );
/* Free any buffers allocated for the MQTT packet. */
if( incomingPacket.pRemainingData != NULL )
{
IotMqtt_FreeMessage( incomingPacket.pRemainingData );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Close the network connection on a bad response. */
if( status == IOT_MQTT_BAD_RESPONSE )
{
IotLogError( "(MQTT connection %p) Error processing incoming data. Closing connection.",
pMqttConnection );
_IotMqtt_CloseNetworkConnection( IOT_MQTT_BAD_PACKET_RECEIVED,
pMqttConnection );
}
else
{
EMPTY_ELSE_MARKER;
}
}
/*-----------------------------------------------------------*/

View file

@ -0,0 +1,207 @@
/*
* 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_static_memory.c
* @brief Implementation of MQTT static memory functions.
*/
/* The config header is always included first. */
#include "iot_config.h"
/* This file should only be compiled if dynamic memory allocation is forbidden. */
#if IOT_STATIC_MEMORY_ONLY == 1
/* Standard includes. */
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
/* Static memory include. */
#include "private/iot_static_memory.h"
/* MQTT internal include. */
#include "private/iot_mqtt_internal.h"
/*-----------------------------------------------------------*/
/**
* @cond DOXYGEN_IGNORE
* Doxygen should ignore this section.
*
* Provide default values for undefined configuration constants.
*/
#ifndef IOT_MQTT_CONNECTIONS
#define IOT_MQTT_CONNECTIONS ( 1 )
#endif
#ifndef IOT_MQTT_MAX_IN_PROGRESS_OPERATIONS
#define IOT_MQTT_MAX_IN_PROGRESS_OPERATIONS ( 10 )
#endif
#ifndef IOT_MQTT_SUBSCRIPTIONS
#define IOT_MQTT_SUBSCRIPTIONS ( 8 )
#endif
/** @endcond */
/* Validate static memory configuration settings. */
#if IOT_MQTT_CONNECTIONS <= 0
#error "IOT_MQTT_CONNECTIONS cannot be 0 or negative."
#endif
#if IOT_MQTT_MAX_IN_PROGRESS_OPERATIONS <= 0
#error "IOT_MQTT_MAX_IN_PROGRESS_OPERATIONS cannot be 0 or negative."
#endif
#if IOT_MQTT_SUBSCRIPTIONS <= 0
#error "IOT_MQTT_SUBSCRIPTIONS cannot be 0 or negative."
#endif
/**
* @brief The size of a static memory MQTT subscription.
*
* Since the pTopic member of #_mqttSubscription_t is variable-length, the constant
* #AWS_IOT_MQTT_SERVER_MAX_TOPIC_LENGTH is used for the length of
* #_mqttSubscription_t.pTopicFilter.
*/
#define MQTT_SUBSCRIPTION_SIZE ( sizeof( _mqttSubscription_t ) + AWS_IOT_MQTT_SERVER_MAX_TOPIC_LENGTH )
/*-----------------------------------------------------------*/
/*
* Static memory buffers and flags, allocated and zeroed at compile-time.
*/
static bool _pInUseMqttConnections[ IOT_MQTT_CONNECTIONS ] = { 0 }; /**< @brief MQTT connection in-use flags. */
static _mqttConnection_t _pMqttConnections[ IOT_MQTT_CONNECTIONS ] = { { 0 } }; /**< @brief MQTT connections. */
static bool _pInUseMqttOperations[ IOT_MQTT_MAX_IN_PROGRESS_OPERATIONS ] = { 0 }; /**< @brief MQTT operation in-use flags. */
static _mqttOperation_t _pMqttOperations[ IOT_MQTT_MAX_IN_PROGRESS_OPERATIONS ] = { { .link = { 0 } } }; /**< @brief MQTT operations. */
static bool _pInUseMqttSubscriptions[ IOT_MQTT_SUBSCRIPTIONS ] = { 0 }; /**< @brief MQTT subscription in-use flags. */
static char _pMqttSubscriptions[ IOT_MQTT_SUBSCRIPTIONS ][ MQTT_SUBSCRIPTION_SIZE ] = { { 0 } }; /**< @brief MQTT subscriptions. */
/*-----------------------------------------------------------*/
void * IotMqtt_MallocConnection( size_t size )
{
int32_t freeIndex = -1;
void * pNewConnection = NULL;
/* Check size argument. */
if( size == sizeof( _mqttConnection_t ) )
{
/* Find a free MQTT connection. */
freeIndex = IotStaticMemory_FindFree( _pInUseMqttConnections,
IOT_MQTT_CONNECTIONS );
if( freeIndex != -1 )
{
pNewConnection = &( _pMqttConnections[ freeIndex ] );
}
}
return pNewConnection;
}
/*-----------------------------------------------------------*/
void IotMqtt_FreeConnection( void * ptr )
{
/* Return the in-use MQTT connection. */
IotStaticMemory_ReturnInUse( ptr,
_pMqttConnections,
_pInUseMqttConnections,
IOT_MQTT_CONNECTIONS,
sizeof( _mqttConnection_t ) );
}
/*-----------------------------------------------------------*/
void * IotMqtt_MallocOperation( size_t size )
{
int32_t freeIndex = -1;
void * pNewOperation = NULL;
/* Check size argument. */
if( size == sizeof( _mqttOperation_t ) )
{
/* Find a free MQTT operation. */
freeIndex = IotStaticMemory_FindFree( _pInUseMqttOperations,
IOT_MQTT_MAX_IN_PROGRESS_OPERATIONS );
if( freeIndex != -1 )
{
pNewOperation = &( _pMqttOperations[ freeIndex ] );
}
}
return pNewOperation;
}
/*-----------------------------------------------------------*/
void IotMqtt_FreeOperation( void * ptr )
{
/* Return the in-use MQTT operation. */
IotStaticMemory_ReturnInUse( ptr,
_pMqttOperations,
_pInUseMqttOperations,
IOT_MQTT_MAX_IN_PROGRESS_OPERATIONS,
sizeof( _mqttOperation_t ) );
}
/*-----------------------------------------------------------*/
void * IotMqtt_MallocSubscription( size_t size )
{
int32_t freeIndex = -1;
void * pNewSubscription = NULL;
if( size <= MQTT_SUBSCRIPTION_SIZE )
{
/* Get the index of a free MQTT subscription. */
freeIndex = IotStaticMemory_FindFree( _pInUseMqttSubscriptions,
IOT_MQTT_SUBSCRIPTIONS );
if( freeIndex != -1 )
{
pNewSubscription = &( _pMqttSubscriptions[ freeIndex ][ 0 ] );
}
}
return pNewSubscription;
}
/*-----------------------------------------------------------*/
void IotMqtt_FreeSubscription( void * ptr )
{
/* Return the in-use MQTT subscription. */
IotStaticMemory_ReturnInUse( ptr,
_pMqttSubscriptions,
_pInUseMqttSubscriptions,
IOT_MQTT_SUBSCRIPTIONS,
MQTT_SUBSCRIPTION_SIZE );
}
/*-----------------------------------------------------------*/
#endif

View file

@ -0,0 +1,648 @@
/*
* 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_subscription.c
* @brief Implements functions that manage subscriptions for an MQTT connection.
*/
/* The config header is always included first. */
#include "iot_config.h"
/* Standard includes. */
#include <stdbool.h>
#include <string.h>
/* Error handling include. */
#include "private/iot_error.h"
/* MQTT internal include. */
#include "private/iot_mqtt_internal.h"
/* Platform layer includes. */
#include "platform/iot_threads.h"
/*-----------------------------------------------------------*/
/**
* @brief First parameter to #_topicMatch.
*/
typedef struct _topicMatchParams
{
const char * pTopicName; /**< @brief The topic name to parse. */
uint16_t topicNameLength; /**< @brief Length of #_topicMatchParams_t.pTopicName. */
bool exactMatchOnly; /**< @brief Whether to allow wildcards or require exact matches. */
} _topicMatchParams_t;
/**
* @brief First parameter to #_packetMatch.
*/
typedef struct _packetMatchParams
{
uint16_t packetIdentifier; /**< Packet identifier to match. */
int32_t order; /**< Order to match. Set to `-1` to ignore. */
} _packetMatchParams_t;
/*-----------------------------------------------------------*/
/**
* @brief Matches a topic name (from a publish) with a topic filter (from a
* subscription).
*
* @param[in] pSubscriptionLink Pointer to the link member of an #_mqttSubscription_t.
* @param[in] pMatch Pointer to a #_topicMatchParams_t.
*
* @return `true` if the arguments match the subscription topic filter; `false`
* otherwise.
*/
static bool _topicMatch( const IotLink_t * pSubscriptionLink,
void * pMatch );
/**
* @brief Matches a packet identifier and order.
*
* @param[in] pSubscriptionLink Pointer to the link member of an #_mqttSubscription_t.
* @param[in] pMatch Pointer to a #_packetMatchParams_t.
*
* @return `true` if the arguments match the subscription's packet info; `false`
* otherwise.
*/
static bool _packetMatch( const IotLink_t * pSubscriptionLink,
void * pMatch );
/*-----------------------------------------------------------*/
static bool _topicMatch( const IotLink_t * pSubscriptionLink,
void * pMatch )
{
IOT_FUNCTION_ENTRY( bool, false );
uint16_t nameIndex = 0, filterIndex = 0;
/* Because this function is called from a container function, the given link
* must never be NULL. */
IotMqtt_Assert( pSubscriptionLink != NULL );
_mqttSubscription_t * pSubscription = IotLink_Container( _mqttSubscription_t,
pSubscriptionLink,
link );
_topicMatchParams_t * pParam = ( _topicMatchParams_t * ) pMatch;
/* Extract the relevant strings and lengths from parameters. */
const char * pTopicName = pParam->pTopicName;
const char * pTopicFilter = pSubscription->pTopicFilter;
const uint16_t topicNameLength = pParam->topicNameLength;
const uint16_t topicFilterLength = pSubscription->topicFilterLength;
/* Check for an exact match. */
if( topicNameLength == topicFilterLength )
{
status = ( strncmp( pTopicName, pTopicFilter, topicNameLength ) == 0 );
IOT_GOTO_CLEANUP();
}
else
{
EMPTY_ELSE_MARKER;
}
/* If the topic lengths are different but an exact match is required, return
* false. */
if( pParam->exactMatchOnly == true )
{
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
while( ( nameIndex < topicNameLength ) && ( filterIndex < topicFilterLength ) )
{
/* Check if the character in the topic name matches the corresponding
* character in the topic filter string. */
if( pTopicName[ nameIndex ] == pTopicFilter[ filterIndex ] )
{
/* Handle special corner cases as documented by the MQTT protocol spec. */
/* Filter "sport/#" also matches "sport" since # includes the parent level. */
if( nameIndex == topicNameLength - 1 )
{
if( filterIndex == topicFilterLength - 3 )
{
if( pTopicFilter[ filterIndex + 1 ] == '/' )
{
if( pTopicFilter[ filterIndex + 2 ] == '#' )
{
IOT_SET_AND_GOTO_CLEANUP( true );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Filter "sport/+" also matches the "sport/" but not "sport". */
if( nameIndex == topicNameLength - 1 )
{
if( filterIndex == topicFilterLength - 2 )
{
if( pTopicFilter[ filterIndex + 1 ] == '+' )
{
IOT_SET_AND_GOTO_CLEANUP( true );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
/* Check for wildcards. */
if( pTopicFilter[ filterIndex ] == '+' )
{
/* Move topic name index to the end of the current level.
* This is identified by '/'. */
while( nameIndex < topicNameLength && pTopicName[ nameIndex ] != '/' )
{
nameIndex++;
}
/* Increment filter index to skip '/'. */
filterIndex++;
continue;
}
else if( pTopicFilter[ filterIndex ] == '#' )
{
/* Subsequent characters don't need to be checked if the for the
* multi-level wildcard. */
IOT_SET_AND_GOTO_CLEANUP( true );
}
else
{
/* Any character mismatch other than '+' or '#' means the topic
* name does not match the topic filter. */
IOT_SET_AND_GOTO_CLEANUP( false );
}
}
/* Increment indexes. */
nameIndex++;
filterIndex++;
}
/* If the end of both strings has been reached, they match. */
if( ( nameIndex == topicNameLength ) && ( filterIndex == topicFilterLength ) )
{
IOT_SET_AND_GOTO_CLEANUP( true );
}
else
{
EMPTY_ELSE_MARKER;
}
IOT_FUNCTION_EXIT_NO_CLEANUP();
}
/*-----------------------------------------------------------*/
static bool _packetMatch( const IotLink_t * pSubscriptionLink,
void * pMatch )
{
bool match = false;
/* Because this function is called from a container function, the given link
* must never be NULL. */
IotMqtt_Assert( pSubscriptionLink != NULL );
_mqttSubscription_t * pSubscription = IotLink_Container( _mqttSubscription_t,
pSubscriptionLink,
link );
_packetMatchParams_t * pParam = ( _packetMatchParams_t * ) pMatch;
/* Compare packet identifiers. */
if( pParam->packetIdentifier == pSubscription->packetInfo.identifier )
{
/* Compare orders if order is not -1. */
if( pParam->order == -1 )
{
match = true;
}
else
{
match = ( ( size_t ) pParam->order ) == pSubscription->packetInfo.order;
}
}
/* If this subscription should be removed, check the reference count. */
if( match == true )
{
/* Reference count must not be negative. */
IotMqtt_Assert( pSubscription->references >= 0 );
/* If the reference count is positive, this subscription cannot be
* removed yet because there are subscription callbacks using it. */
if( pSubscription->references > 0 )
{
match = false;
/* Set the unsubscribed flag. The last active subscription callback
* will remove and clean up this subscription. */
pSubscription->unsubscribed = true;
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
return match;
}
/*-----------------------------------------------------------*/
IotMqttError_t _IotMqtt_AddSubscriptions( _mqttConnection_t * pMqttConnection,
uint16_t subscribePacketIdentifier,
const IotMqttSubscription_t * pSubscriptionList,
size_t subscriptionCount )
{
IotMqttError_t status = IOT_MQTT_SUCCESS;
size_t i = 0;
_mqttSubscription_t * pNewSubscription = NULL;
IotLink_t * pSubscriptionLink = NULL;
_topicMatchParams_t topicMatchParams = { .exactMatchOnly = true };
IotMutex_Lock( &( pMqttConnection->subscriptionMutex ) );
for( i = 0; i < subscriptionCount; i++ )
{
/* Check if this topic filter is already registered. */
topicMatchParams.pTopicName = pSubscriptionList[ i ].pTopicFilter;
topicMatchParams.topicNameLength = pSubscriptionList[ i ].topicFilterLength;
pSubscriptionLink = IotListDouble_FindFirstMatch( &( pMqttConnection->subscriptionList ),
NULL,
_topicMatch,
&topicMatchParams );
if( pSubscriptionLink != NULL )
{
pNewSubscription = IotLink_Container( _mqttSubscription_t, pSubscriptionLink, link );
/* The lengths of exactly matching topic filters must match. */
IotMqtt_Assert( pNewSubscription->topicFilterLength == pSubscriptionList[ i ].topicFilterLength );
/* Replace the callback and packet info with the new parameters. */
pNewSubscription->callback = pSubscriptionList[ i ].callback;
pNewSubscription->packetInfo.identifier = subscribePacketIdentifier;
pNewSubscription->packetInfo.order = i;
}
else
{
/* Allocate memory for a new subscription. */
pNewSubscription = IotMqtt_MallocSubscription( sizeof( _mqttSubscription_t ) +
pSubscriptionList[ i ].topicFilterLength );
if( pNewSubscription == NULL )
{
status = IOT_MQTT_NO_MEMORY;
break;
}
else
{
/* Clear the new subscription. */
( void ) memset( pNewSubscription,
0x00,
sizeof( _mqttSubscription_t ) + pSubscriptionList[ i ].topicFilterLength );
/* Set the members of the new subscription and add it to the list. */
pNewSubscription->packetInfo.identifier = subscribePacketIdentifier;
pNewSubscription->packetInfo.order = i;
pNewSubscription->callback = pSubscriptionList[ i ].callback;
pNewSubscription->topicFilterLength = pSubscriptionList[ i ].topicFilterLength;
( void ) memcpy( pNewSubscription->pTopicFilter,
pSubscriptionList[ i ].pTopicFilter,
( size_t ) ( pSubscriptionList[ i ].topicFilterLength ) );
IotListDouble_InsertHead( &( pMqttConnection->subscriptionList ),
&( pNewSubscription->link ) );
}
}
}
IotMutex_Unlock( &( pMqttConnection->subscriptionMutex ) );
/* If memory allocation failed, remove all previously added subscriptions. */
if( status != IOT_MQTT_SUCCESS )
{
_IotMqtt_RemoveSubscriptionByTopicFilter( pMqttConnection,
pSubscriptionList,
i );
}
else
{
EMPTY_ELSE_MARKER;
}
return status;
}
/*-----------------------------------------------------------*/
void _IotMqtt_InvokeSubscriptionCallback( _mqttConnection_t * pMqttConnection,
IotMqttCallbackParam_t * pCallbackParam )
{
_mqttSubscription_t * pSubscription = NULL;
IotLink_t * pCurrentLink = NULL, * pNextLink = NULL;
void * pCallbackContext = NULL;
void ( * callbackFunction )( void *,
IotMqttCallbackParam_t * ) = NULL;
_topicMatchParams_t topicMatchParams =
{
.pTopicName = pCallbackParam->u.message.info.pTopicName,
.topicNameLength = pCallbackParam->u.message.info.topicNameLength,
.exactMatchOnly = false
};
/* Prevent any other thread from modifying the subscription list while this
* function is searching. */
IotMutex_Lock( &( pMqttConnection->subscriptionMutex ) );
/* Search the subscription list for all matching subscriptions starting at
* the list head. */
while( true )
{
pCurrentLink = IotListDouble_FindFirstMatch( &( pMqttConnection->subscriptionList ),
pCurrentLink,
_topicMatch,
&topicMatchParams );
/* No subscription found. Exit loop. */
if( pCurrentLink == NULL )
{
break;
}
else
{
EMPTY_ELSE_MARKER;
}
/* Subscription found. Calculate pointer to subscription object. */
pSubscription = IotLink_Container( _mqttSubscription_t, pCurrentLink, link );
/* Subscription validation should not have allowed a NULL callback function. */
IotMqtt_Assert( pSubscription->callback.function != NULL );
/* Increment the subscription's reference count. */
( pSubscription->references )++;
/* Copy the necessary members of the subscription before releasing the
* subscription list mutex. */
pCallbackContext = pSubscription->callback.pCallbackContext;
callbackFunction = pSubscription->callback.function;
/* Unlock the subscription list mutex. */
IotMutex_Unlock( &( pMqttConnection->subscriptionMutex ) );
/* Set the members of the callback parameter. */
pCallbackParam->mqttConnection = pMqttConnection;
pCallbackParam->u.message.pTopicFilter = pSubscription->pTopicFilter;
pCallbackParam->u.message.topicFilterLength = pSubscription->topicFilterLength;
/* Invoke the subscription callback. */
callbackFunction( pCallbackContext, pCallbackParam );
/* Lock the subscription list mutex to decrement the reference count. */
IotMutex_Lock( &( pMqttConnection->subscriptionMutex ) );
/* Decrement the reference count. It must still be positive. */
( pSubscription->references )--;
IotMqtt_Assert( pSubscription->references >= 0 );
/* Save the pointer to the next link in case this subscription is freed. */
pNextLink = pCurrentLink->pNext;
/* Remove this subscription if it has no references and the unsubscribed
* flag is set. */
if( pSubscription->unsubscribed == true )
{
/* An unsubscribed subscription should have been removed from the list. */
IotMqtt_Assert( IotLink_IsLinked( &( pSubscription->link ) ) == false );
/* Free subscriptions with no references. */
if( pSubscription->references == 0 )
{
IotMqtt_FreeSubscription( pSubscription );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Move current link pointer. */
pCurrentLink = pNextLink;
}
IotMutex_Unlock( &( pMqttConnection->subscriptionMutex ) );
_IotMqtt_DecrementConnectionReferences( pMqttConnection );
}
/*-----------------------------------------------------------*/
void _IotMqtt_RemoveSubscriptionByPacket( _mqttConnection_t * pMqttConnection,
uint16_t packetIdentifier,
int32_t order )
{
const _packetMatchParams_t packetMatchParams =
{
.packetIdentifier = packetIdentifier,
.order = order
};
IotMutex_Lock( &( pMqttConnection->subscriptionMutex ) );
IotListDouble_RemoveAllMatches( &( pMqttConnection->subscriptionList ),
_packetMatch,
( void * ) ( &packetMatchParams ),
IotMqtt_FreeSubscription,
offsetof( _mqttSubscription_t, link ) );
IotMutex_Unlock( &( pMqttConnection->subscriptionMutex ) );
}
/*-----------------------------------------------------------*/
void _IotMqtt_RemoveSubscriptionByTopicFilter( _mqttConnection_t * pMqttConnection,
const IotMqttSubscription_t * pSubscriptionList,
size_t subscriptionCount )
{
size_t i = 0;
_mqttSubscription_t * pSubscription = NULL;
IotLink_t * pSubscriptionLink = NULL;
_topicMatchParams_t topicMatchParams = { 0 };
/* Prevent any other thread from modifying the subscription list while this
* function is running. */
IotMutex_Lock( &( pMqttConnection->subscriptionMutex ) );
/* Find and remove each topic filter from the list. */
for( i = 0; i < subscriptionCount; i++ )
{
topicMatchParams.pTopicName = pSubscriptionList[ i ].pTopicFilter;
topicMatchParams.topicNameLength = pSubscriptionList[ i ].topicFilterLength;
topicMatchParams.exactMatchOnly = true;
pSubscriptionLink = IotListDouble_FindFirstMatch( &( pMqttConnection->subscriptionList ),
NULL,
_topicMatch,
&topicMatchParams );
if( pSubscriptionLink != NULL )
{
pSubscription = IotLink_Container( _mqttSubscription_t, pSubscriptionLink, link );
/* Reference count must not be negative. */
IotMqtt_Assert( pSubscription->references >= 0 );
/* Remove subscription from list. */
IotListDouble_Remove( pSubscriptionLink );
/* Check the reference count. This subscription cannot be removed if
* there are subscription callbacks using it. */
if( pSubscription->references > 0 )
{
/* Set the unsubscribed flag. The last active subscription callback
* will remove and clean up this subscription. */
pSubscription->unsubscribed = true;
}
else
{
/* Free a subscription with no references. */
IotMqtt_FreeSubscription( pSubscription );
}
}
else
{
EMPTY_ELSE_MARKER;
}
}
IotMutex_Unlock( &( pMqttConnection->subscriptionMutex ) );
}
/*-----------------------------------------------------------*/
bool IotMqtt_IsSubscribed( IotMqttConnection_t mqttConnection,
const char * pTopicFilter,
uint16_t topicFilterLength,
IotMqttSubscription_t * pCurrentSubscription )
{
bool status = false;
_mqttSubscription_t * pSubscription = NULL;
IotLink_t * pSubscriptionLink = NULL;
_topicMatchParams_t topicMatchParams =
{
.pTopicName = pTopicFilter,
.topicNameLength = topicFilterLength,
.exactMatchOnly = true
};
/* Prevent any other thread from modifying the subscription list while this
* function is running. */
IotMutex_Lock( &( mqttConnection->subscriptionMutex ) );
/* Search for a matching subscription. */
pSubscriptionLink = IotListDouble_FindFirstMatch( &( mqttConnection->subscriptionList ),
NULL,
_topicMatch,
&topicMatchParams );
/* Check if a matching subscription was found. */
if( pSubscriptionLink != NULL )
{
pSubscription = IotLink_Container( _mqttSubscription_t, pSubscriptionLink, link );
/* Copy the matching subscription to the output parameter. */
if( pCurrentSubscription != NULL )
{
pCurrentSubscription->pTopicFilter = pTopicFilter;
pCurrentSubscription->topicFilterLength = topicFilterLength;
pCurrentSubscription->qos = IOT_MQTT_QOS_0;
pCurrentSubscription->callback = pSubscription->callback;
}
else
{
EMPTY_ELSE_MARKER;
}
status = true;
}
else
{
EMPTY_ELSE_MARKER;
}
IotMutex_Unlock( &( mqttConnection->subscriptionMutex ) );
return status;
}
/*-----------------------------------------------------------*/
/* Provide access to internal functions and variables if testing. */
#if IOT_BUILD_TESTS == 1
#include "iot_test_access_mqtt_subscription.c"
#endif

View file

@ -0,0 +1,593 @@
/*
* 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_validate.c
* @brief Implements functions that validate the structs of the MQTT library.
*/
/* The config header is always included first. */
#include "iot_config.h"
/* Error handling include. */
#include "private/iot_error.h"
/* MQTT internal include. */
#include "private/iot_mqtt_internal.h"
/*-----------------------------------------------------------*/
bool _IotMqtt_ValidateConnect( const IotMqttConnectInfo_t * pConnectInfo )
{
IOT_FUNCTION_ENTRY( bool, true );
/* Check for NULL. */
if( pConnectInfo == NULL )
{
IotLogError( "MQTT connection information cannot be NULL." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check that a client identifier was set. */
if( pConnectInfo->pClientIdentifier == NULL )
{
IotLogError( "Client identifier must be set." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check for a zero-length client identifier. Zero-length client identifiers
* are not allowed with clean sessions. */
if( pConnectInfo->clientIdentifierLength == 0 )
{
IotLogWarn( "A zero-length client identifier was provided." );
if( pConnectInfo->cleanSession == true )
{
IotLogError( "A zero-length client identifier cannot be used with a clean session." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check that the number of persistent session subscriptions is valid. */
if( pConnectInfo->cleanSession == false )
{
if( pConnectInfo->pPreviousSubscriptions != NULL )
{
if( pConnectInfo->previousSubscriptionCount == 0 )
{
IotLogError( "Previous subscription count cannot be 0." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* In MQTT 3.1.1, servers are not obligated to accept client identifiers longer
* than 23 characters. */
if( pConnectInfo->clientIdentifierLength > 23 )
{
IotLogWarn( "A client identifier length of %hu is longer than 23, which is "
"the longest client identifier a server must accept.",
pConnectInfo->clientIdentifierLength );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check for compatibility with the AWS IoT MQTT service limits. */
if( pConnectInfo->awsIotMqttMode == true )
{
/* Check that client identifier is within the service limit. */
if( pConnectInfo->clientIdentifierLength > AWS_IOT_MQTT_SERVER_MAX_CLIENTID )
{
IotLogError( "AWS IoT does not support client identifiers longer than %d bytes.",
AWS_IOT_MQTT_SERVER_MAX_CLIENTID );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check for compliance with AWS IoT keep-alive limits. */
if( pConnectInfo->keepAliveSeconds == 0 )
{
IotLogWarn( "AWS IoT does not support disabling keep-alive. Default keep-alive "
"of %d seconds will be used.",
AWS_IOT_MQTT_SERVER_MAX_KEEPALIVE );
}
else if( pConnectInfo->keepAliveSeconds < AWS_IOT_MQTT_SERVER_MIN_KEEPALIVE )
{
IotLogWarn( "AWS IoT does not support keep-alive intervals less than %d seconds. "
"An interval of %d seconds will be used.",
AWS_IOT_MQTT_SERVER_MIN_KEEPALIVE,
AWS_IOT_MQTT_SERVER_MIN_KEEPALIVE );
}
else if( pConnectInfo->keepAliveSeconds > AWS_IOT_MQTT_SERVER_MAX_KEEPALIVE )
{
IotLogWarn( "AWS IoT does not support keep-alive intervals greater than %d seconds. "
"An interval of %d seconds will be used.",
AWS_IOT_MQTT_SERVER_MAX_KEEPALIVE,
AWS_IOT_MQTT_SERVER_MAX_KEEPALIVE );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
IOT_FUNCTION_EXIT_NO_CLEANUP();
}
/*-----------------------------------------------------------*/
bool _IotMqtt_ValidatePublish( bool awsIotMqttMode,
const IotMqttPublishInfo_t * pPublishInfo )
{
IOT_FUNCTION_ENTRY( bool, true );
/* Check for NULL. */
if( pPublishInfo == NULL )
{
IotLogError( "Publish information cannot be NULL." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check topic name for NULL or zero-length. */
if( pPublishInfo->pTopicName == NULL )
{
IotLogError( "Publish topic name must be set." );
}
else
{
EMPTY_ELSE_MARKER;
}
if( pPublishInfo->topicNameLength == 0 )
{
IotLogError( "Publish topic name length cannot be 0." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Only allow NULL payloads with zero length. */
if( pPublishInfo->pPayload == NULL )
{
if( pPublishInfo->payloadLength != 0 )
{
IotLogError( "Nonzero payload length cannot have a NULL payload." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check for a valid QoS. */
if( pPublishInfo->qos != IOT_MQTT_QOS_0 )
{
if( pPublishInfo->qos != IOT_MQTT_QOS_1 )
{
IotLogError( "Publish QoS must be either 0 or 1." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check the retry parameters. */
if( pPublishInfo->retryLimit > 0 )
{
if( pPublishInfo->retryMs == 0 )
{
IotLogError( "Publish retry time must be positive." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check for compatibility with AWS IoT MQTT server. */
if( awsIotMqttMode == true )
{
/* Check for retained message. */
if( pPublishInfo->retain == true )
{
IotLogError( "AWS IoT does not support retained publish messages." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check topic name length. */
if( pPublishInfo->topicNameLength > AWS_IOT_MQTT_SERVER_MAX_TOPIC_LENGTH )
{
IotLogError( "AWS IoT does not support topic names longer than %d bytes.",
AWS_IOT_MQTT_SERVER_MAX_TOPIC_LENGTH );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
IOT_FUNCTION_EXIT_NO_CLEANUP();
}
/*-----------------------------------------------------------*/
bool _IotMqtt_ValidateOperation( IotMqttOperation_t operation )
{
IOT_FUNCTION_ENTRY( bool, true );
/* Check for NULL. */
if( operation == NULL )
{
IotLogError( "Operation reference cannot be NULL." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check that reference is waitable. */
if( ( operation->u.operation.flags & IOT_MQTT_FLAG_WAITABLE ) != IOT_MQTT_FLAG_WAITABLE )
{
IotLogError( "Operation is not waitable." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
IOT_FUNCTION_EXIT_NO_CLEANUP();
}
/*-----------------------------------------------------------*/
bool _IotMqtt_ValidateSubscriptionList( IotMqttOperationType_t operation,
bool awsIotMqttMode,
const IotMqttSubscription_t * pListStart,
size_t listSize )
{
IOT_FUNCTION_ENTRY( bool, true );
size_t i = 0;
uint16_t j = 0;
const IotMqttSubscription_t * pListElement = NULL;
/* Operation must be either subscribe or unsubscribe. */
IotMqtt_Assert( ( operation == IOT_MQTT_SUBSCRIBE ) ||
( operation == IOT_MQTT_UNSUBSCRIBE ) );
/* Check for empty list. */
if( pListStart == NULL )
{
IotLogError( "Subscription list pointer cannot be NULL." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
if( listSize == 0 )
{
IotLogError( "Empty subscription list." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
/* AWS IoT supports at most 8 topic filters in a single SUBSCRIBE packet. */
if( awsIotMqttMode == true )
{
if( listSize > AWS_IOT_MQTT_SERVER_MAX_TOPIC_FILTERS_PER_SUBSCRIBE )
{
IotLogError( "AWS IoT does not support more than %d topic filters per "
"subscription request.",
AWS_IOT_MQTT_SERVER_MAX_TOPIC_FILTERS_PER_SUBSCRIBE );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
for( i = 0; i < listSize; i++ )
{
pListElement = &( pListStart[ i ] );
/* Check for a valid QoS and callback function when subscribing. */
if( operation == IOT_MQTT_SUBSCRIBE )
{
if( pListElement->qos != IOT_MQTT_QOS_0 )
{
if( pListElement->qos != IOT_MQTT_QOS_1 )
{
IotLogError( "Subscription QoS must be either 0 or 1." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
if( pListElement->callback.function == NULL )
{
IotLogError( "Callback function must be set." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check subscription topic filter. */
if( pListElement->pTopicFilter == NULL )
{
IotLogError( "Subscription topic filter cannot be NULL." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
if( pListElement->topicFilterLength == 0 )
{
IotLogError( "Subscription topic filter length cannot be 0." );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check for compatibility with AWS IoT MQTT server. */
if( awsIotMqttMode == true )
{
/* Check topic filter length. */
if( pListElement->topicFilterLength > AWS_IOT_MQTT_SERVER_MAX_TOPIC_LENGTH )
{
IotLogError( "AWS IoT does not support topic filters longer than %d bytes.",
AWS_IOT_MQTT_SERVER_MAX_TOPIC_LENGTH );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Check that the wildcards '+' and '#' are being used correctly. */
for( j = 0; j < pListElement->topicFilterLength; j++ )
{
switch( pListElement->pTopicFilter[ j ] )
{
/* Check that the single level wildcard '+' is used correctly. */
case '+':
/* Unless '+' is the first character in the filter, it must be preceded by '/'. */
if( j > 0 )
{
if( pListElement->pTopicFilter[ j - 1 ] != '/' )
{
IotLogError( "Invalid topic filter %.*s -- '+' must be preceded by '/'.",
pListElement->topicFilterLength,
pListElement->pTopicFilter );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
/* Unless '+' is the last character in the filter, it must be succeeded by '/'. */
if( j < pListElement->topicFilterLength - 1 )
{
if( pListElement->pTopicFilter[ j + 1 ] != '/' )
{
IotLogError( "Invalid topic filter %.*s -- '+' must be succeeded by '/'.",
pListElement->topicFilterLength,
pListElement->pTopicFilter );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
break;
/* Check that the multi-level wildcard '#' is used correctly. */
case '#':
/* '#' must be the last character in the filter. */
if( j != pListElement->topicFilterLength - 1 )
{
IotLogError( "Invalid topic filter %.*s -- '#' must be the last character.",
pListElement->topicFilterLength,
pListElement->pTopicFilter );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
/* Unless '#' is standalone, it must be preceded by '/'. */
if( pListElement->topicFilterLength > 1 )
{
if( pListElement->pTopicFilter[ j - 1 ] != '/' )
{
IotLogError( "Invalid topic filter %.*s -- '#' must be preceded by '/'.",
pListElement->topicFilterLength,
pListElement->pTopicFilter );
IOT_SET_AND_GOTO_CLEANUP( false );
}
else
{
EMPTY_ELSE_MARKER;
}
}
else
{
EMPTY_ELSE_MARKER;
}
break;
default:
break;
}
}
}
IOT_FUNCTION_EXIT_NO_CLEANUP();
}
/*-----------------------------------------------------------*/

View file

@ -0,0 +1,915 @@
/*
* 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_internal.h
* @brief Internal header of MQTT library. This header should not be included in
* typical application code.
*/
#ifndef IOT_MQTT_INTERNAL_H_
#define IOT_MQTT_INTERNAL_H_
/* The config header is always included first. */
#include "iot_config.h"
/* Linear containers (lists and queues) include. */
#include "iot_linear_containers.h"
/* MQTT include. */
#include "iot_mqtt.h"
/* Task pool include. */
#include "iot_taskpool.h"
/**
* @def IotMqtt_Assert( expression )
* @brief Assertion macro for the MQTT library.
*
* Set @ref IOT_MQTT_ENABLE_ASSERTS to `1` to enable assertions in the MQTT
* library.
*
* @param[in] expression Expression to be evaluated.
*/
#if IOT_MQTT_ENABLE_ASSERTS == 1
#ifndef IotMqtt_Assert
#include <assert.h>
#define IotMqtt_Assert( expression ) assert( expression )
#endif
#else
#define IotMqtt_Assert( expression )
#endif
/* Configure logs for MQTT functions. */
#ifdef IOT_LOG_LEVEL_MQTT
#define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_MQTT
#else
#ifdef IOT_LOG_LEVEL_GLOBAL
#define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_GLOBAL
#else
#define LIBRARY_LOG_LEVEL IOT_LOG_NONE
#endif
#endif
#define LIBRARY_LOG_NAME ( "MQTT" )
#include "iot_logging_setup.h"
/*
* Provide default values for undefined memory allocation functions based on
* the usage of dynamic memory allocation.
*/
#if IOT_STATIC_MEMORY_ONLY == 1
#include "private/iot_static_memory.h"
/**
* @brief Allocate an #_mqttConnection_t. This function should have the same
* signature as [malloc]
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html).
*/
void * IotMqtt_MallocConnection( size_t size );
/**
* @brief Free an #_mqttConnection_t. This function should have the same
* signature as [free]
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html).
*/
void IotMqtt_FreeConnection( void * ptr );
/**
* @brief Allocate memory for an MQTT packet. This function should have the
* same signature as [malloc]
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html).
*/
#define IotMqtt_MallocMessage Iot_MallocMessageBuffer
/**
* @brief Free an MQTT packet. This function should have the same signature
* as [free]
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html).
*/
#define IotMqtt_FreeMessage Iot_FreeMessageBuffer
/**
* @brief Allocate an #_mqttOperation_t. This function should have the same
* signature as [malloc]
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html).
*/
void * IotMqtt_MallocOperation( size_t size );
/**
* @brief Free an #_mqttOperation_t. This function should have the same
* signature as [free]
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html).
*/
void IotMqtt_FreeOperation( void * ptr );
/**
* @brief Allocate an #_mqttSubscription_t. This function should have the
* same signature as [malloc]
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html).
*/
void * IotMqtt_MallocSubscription( size_t size );
/**
* @brief Free an #_mqttSubscription_t. This function should have the same
* signature as [free]
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html).
*/
void IotMqtt_FreeSubscription( void * ptr );
#else /* if IOT_STATIC_MEMORY_ONLY == 1 */
#include <stdlib.h>
#ifndef IotMqtt_MallocConnection
#define IotMqtt_MallocConnection malloc
#endif
#ifndef IotMqtt_FreeConnection
#define IotMqtt_FreeConnection free
#endif
#ifndef IotMqtt_MallocMessage
#define IotMqtt_MallocMessage malloc
#endif
#ifndef IotMqtt_FreeMessage
#define IotMqtt_FreeMessage free
#endif
#ifndef IotMqtt_MallocOperation
#define IotMqtt_MallocOperation malloc
#endif
#ifndef IotMqtt_FreeOperation
#define IotMqtt_FreeOperation free
#endif
#ifndef IotMqtt_MallocSubscription
#define IotMqtt_MallocSubscription malloc
#endif
#ifndef IotMqtt_FreeSubscription
#define IotMqtt_FreeSubscription free
#endif
#endif /* if IOT_STATIC_MEMORY_ONLY == 1 */
/**
* @cond DOXYGEN_IGNORE
* Doxygen should ignore this section.
*
* Provide default values for undefined configuration constants.
*/
#ifndef AWS_IOT_MQTT_ENABLE_METRICS
#define AWS_IOT_MQTT_ENABLE_METRICS ( 1 )
#endif
#ifndef IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES
#define IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES ( 0 )
#endif
#ifndef IOT_MQTT_RESPONSE_WAIT_MS
#define IOT_MQTT_RESPONSE_WAIT_MS ( 1000 )
#endif
#ifndef IOT_MQTT_RETRY_MS_CEILING
#define IOT_MQTT_RETRY_MS_CEILING ( 60000 )
#endif
/** @endcond */
/**
* @brief Marks the empty statement of an `else` branch.
*
* Does nothing, but allows test coverage to detect branches not taken. By default,
* this is defined to nothing. When running code coverage testing, this is defined
* to an assembly NOP.
*/
#ifndef EMPTY_ELSE_MARKER
#define EMPTY_ELSE_MARKER
#endif
/*
* Constants related to limits defined in AWS Service Limits.
*
* For details, see
* https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html
*
* Used to validate parameters if when connecting to an AWS IoT MQTT server.
*/
#define AWS_IOT_MQTT_SERVER_MIN_KEEPALIVE ( 30 ) /**< @brief Minumum keep-alive interval accepted by AWS IoT. */
#define AWS_IOT_MQTT_SERVER_MAX_KEEPALIVE ( 1200 ) /**< @brief Maximum keep-alive interval accepted by AWS IoT. */
#define AWS_IOT_MQTT_SERVER_MAX_CLIENTID ( 128 ) /**< @brief Maximum length of client identifier accepted by AWS IoT. */
#define AWS_IOT_MQTT_SERVER_MAX_TOPIC_LENGTH ( 256 ) /**< @brief Maximum length of topic names or filters accepted by AWS IoT. */
#define AWS_IOT_MQTT_SERVER_MAX_TOPIC_FILTERS_PER_SUBSCRIBE ( 8 ) /**< @brief Maximum number of topic filters in a single SUBSCRIBE packet. */
/*
* MQTT control packet type and flags. Always the first byte of an MQTT
* packet.
*
* For details, see
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/csprd02/mqtt-v3.1.1-csprd02.html#_Toc385349757
*/
#define MQTT_PACKET_TYPE_CONNECT ( ( uint8_t ) 0x10U ) /**< @brief CONNECT (client-to-server). */
#define MQTT_PACKET_TYPE_CONNACK ( ( uint8_t ) 0x20U ) /**< @brief CONNACK (server-to-client). */
#define MQTT_PACKET_TYPE_PUBLISH ( ( uint8_t ) 0x30U ) /**< @brief PUBLISH (bi-directional). */
#define MQTT_PACKET_TYPE_PUBACK ( ( uint8_t ) 0x40U ) /**< @brief PUBACK (server-to-client). */
#define MQTT_PACKET_TYPE_SUBSCRIBE ( ( uint8_t ) 0x82U ) /**< @brief SUBSCRIBE (client-to-server). */
#define MQTT_PACKET_TYPE_SUBACK ( ( uint8_t ) 0x90U ) /**< @brief SUBACK (server-to-client). */
#define MQTT_PACKET_TYPE_UNSUBSCRIBE ( ( uint8_t ) 0xa2U ) /**< @brief UNSUBSCRIBE (client-to-server). */
#define MQTT_PACKET_TYPE_UNSUBACK ( ( uint8_t ) 0xb0U ) /**< @brief UNSUBACK (server-to-client). */
#define MQTT_PACKET_TYPE_PINGREQ ( ( uint8_t ) 0xc0U ) /**< @brief PINGREQ (client-to-server). */
#define MQTT_PACKET_TYPE_PINGRESP ( ( uint8_t ) 0xd0U ) /**< @brief PINGRESP (server-to-client). */
#define MQTT_PACKET_TYPE_DISCONNECT ( ( uint8_t ) 0xe0U ) /**< @brief DISCONNECT (client-to-server). */
/**
* @brief A value that represents an invalid remaining length.
*
* This value is greater than what is allowed by the MQTT specification.
*/
#define MQTT_REMAINING_LENGTH_INVALID ( ( size_t ) 268435456 )
/*---------------------- MQTT internal data structures ----------------------*/
/**
* @brief Represents an MQTT connection.
*/
typedef struct _mqttConnection
{
bool awsIotMqttMode; /**< @brief Specifies if this connection is to an AWS IoT MQTT server. */
bool ownNetworkConnection; /**< @brief Whether this MQTT connection owns its network connection. */
void * pNetworkConnection; /**< @brief References the transport-layer network connection. */
const IotNetworkInterface_t * pNetworkInterface; /**< @brief Network interface provided to @ref mqtt_function_connect. */
IotMqttCallbackInfo_t disconnectCallback; /**< @brief A function to invoke when this connection is disconnected. */
#if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1
const IotMqttSerializer_t * pSerializer; /**< @brief MQTT packet serializer overrides. */
#endif
bool disconnected; /**< @brief Tracks if this connection has been disconnected. */
IotMutex_t referencesMutex; /**< @brief Recursive mutex. Grants access to connection state and operation lists. */
int32_t references; /**< @brief Counts callbacks and operations using this connection. */
IotListDouble_t pendingProcessing; /**< @brief List of operations waiting to be processed by a task pool routine. */
IotListDouble_t pendingResponse; /**< @brief List of processed operations awaiting a server response. */
IotListDouble_t subscriptionList; /**< @brief Holds subscriptions associated with this connection. */
IotMutex_t subscriptionMutex; /**< @brief Grants exclusive access to the subscription list. */
bool keepAliveFailure; /**< @brief Failure flag for keep-alive operation. */
uint32_t keepAliveMs; /**< @brief Keep-alive interval in milliseconds. Its max value (per spec) is 65,535,000. */
uint32_t nextKeepAliveMs; /**< @brief Relative delay for next keep-alive job. */
IotTaskPoolJobStorage_t keepAliveJobStorage; /**< @brief Task pool job for processing this connection's keep-alive. */
IotTaskPoolJob_t keepAliveJob; /**< @brief Task pool job for processing this connection's keep-alive. */
uint8_t * pPingreqPacket; /**< @brief An MQTT PINGREQ packet, allocated if keep-alive is active. */
size_t pingreqPacketSize; /**< @brief The size of an allocated PINGREQ packet. */
} _mqttConnection_t;
/**
* @brief Represents a subscription stored in an MQTT connection.
*/
typedef struct _mqttSubscription
{
IotLink_t link; /**< @brief List link member. */
int32_t references; /**< @brief How many subscription callbacks are using this subscription. */
/**
* @brief Tracks whether @ref mqtt_function_unsubscribe has been called for
* this subscription.
*
* If there are active subscription callbacks, @ref mqtt_function_unsubscribe
* cannot remove this subscription. Instead, it will set this flag, which
* schedules the removal of this subscription once all subscription callbacks
* terminate.
*/
bool unsubscribed;
struct
{
uint16_t identifier; /**< @brief Packet identifier. */
size_t order; /**< @brief Order in the packet's list of subscriptions. */
} packetInfo; /**< @brief Information about the SUBSCRIBE packet that registered this subscription. */
IotMqttCallbackInfo_t callback; /**< @brief Callback information for this subscription. */
uint16_t topicFilterLength; /**< @brief Length of #_mqttSubscription_t.pTopicFilter. */
char pTopicFilter[]; /**< @brief The subscription topic filter. */
} _mqttSubscription_t;
/**
* @brief Internal structure representing a single MQTT operation, such as
* CONNECT, SUBSCRIBE, PUBLISH, etc.
*
* Queues of these structures keeps track of all in-progress MQTT operations.
*/
typedef struct _mqttOperation
{
/* Pointers to neighboring queue elements. */
IotLink_t link; /**< @brief List link member. */
bool incomingPublish; /**< @brief Set to true if this operation an incoming PUBLISH. */
_mqttConnection_t * pMqttConnection; /**< @brief MQTT connection associated with this operation. */
IotTaskPoolJobStorage_t jobStorage; /**< @brief Task pool job storage associated with this operation. */
IotTaskPoolJob_t job; /**< @brief Task pool job associated with this operation. */
union
{
/* If incomingPublish is false, this struct is valid. */
struct
{
/* Basic operation information. */
int32_t jobReference; /**< @brief Tracks if a job is using this operation. Must always be 0, 1, or 2. */
IotMqttOperationType_t type; /**< @brief What operation this structure represents. */
uint32_t flags; /**< @brief Flags passed to the function that created this operation. */
uint16_t packetIdentifier; /**< @brief The packet identifier used with this operation. */
/* Serialized packet and size. */
uint8_t * pMqttPacket; /**< @brief The MQTT packet to send over the network. */
uint8_t * pPacketIdentifierHigh; /**< @brief The location of the high byte of the packet identifier in the MQTT packet. */
size_t packetSize; /**< @brief Size of `pMqttPacket`. */
/* How to notify of an operation's completion. */
union
{
IotSemaphore_t waitSemaphore; /**< @brief Semaphore to be used with @ref mqtt_function_wait. */
IotMqttCallbackInfo_t callback; /**< @brief User-provided callback function and parameter. */
} notify; /**< @brief How to notify of this operation's completion. */
IotMqttError_t status; /**< @brief Result of this operation. This is reported once a response is received. */
struct
{
uint32_t count;
uint32_t limit;
uint32_t nextPeriod;
} retry;
} operation;
/* If incomingPublish is true, this struct is valid. */
struct
{
IotMqttPublishInfo_t publishInfo; /**< @brief Deserialized PUBLISH. */
const void * pReceivedData; /**< @brief Any buffer associated with this PUBLISH that should be freed. */
} publish;
} u; /**< @brief Valid member depends on _mqttOperation_t.incomingPublish. */
} _mqttOperation_t;
/**
* @brief Represents an MQTT packet received from the network.
*
* This struct is used to hold parameters for the deserializers so that all
* deserializers have the same function signature.
*/
typedef struct _mqttPacket
{
union
{
/**
* @brief (Input) MQTT connection associated with this packet. Only used
* when deserializing SUBACKs.
*/
_mqttConnection_t * pMqttConnection;
/**
* @brief (Output) Operation representing an incoming PUBLISH. Only used
* when deserializing PUBLISHes.
*/
_mqttOperation_t * pIncomingPublish;
} u; /**< @brief Valid member depends on packet being decoded. */
uint8_t * pRemainingData; /**< @brief (Input) The remaining data in MQTT packet. */
size_t remainingLength; /**< @brief (Input) Length of the remaining data in the MQTT packet. */
uint16_t packetIdentifier; /**< @brief (Output) MQTT packet identifier. */
uint8_t type; /**< @brief (Input) A value identifying the packet type. */
} _mqttPacket_t;
/*-------------------- MQTT struct validation functions ---------------------*/
/**
* @brief Check that an #IotMqttConnectInfo_t is valid.
*
* @param[in] pConnectInfo The #IotMqttConnectInfo_t to validate.
*
* @return `true` if `pConnectInfo` is valid; `false` otherwise.
*/
bool _IotMqtt_ValidateConnect( const IotMqttConnectInfo_t * pConnectInfo );
/**
* @brief Check that an #IotMqttPublishInfo_t is valid.
*
* @param[in] awsIotMqttMode Specifies if this PUBLISH packet is being sent to
* an AWS IoT MQTT server.
* @param[in] pPublishInfo The #IotMqttPublishInfo_t to validate.
*
* @return `true` if `pPublishInfo` is valid; `false` otherwise.
*/
bool _IotMqtt_ValidatePublish( bool awsIotMqttMode,
const IotMqttPublishInfo_t * pPublishInfo );
/**
* @brief Check that an #IotMqttOperation_t is valid and waitable.
*
* @param[in] operation The #IotMqttOperation_t to validate.
*
* @return `true` if `operation` is valid; `false` otherwise.
*/
bool _IotMqtt_ValidateOperation( IotMqttOperation_t operation );
/**
* @brief Check that a list of #IotMqttSubscription_t is valid.
*
* @param[in] operation Either #IOT_MQTT_SUBSCRIBE or #IOT_MQTT_UNSUBSCRIBE.
* Some parameters are not validated for #IOT_MQTT_UNSUBSCRIBE.
* @param[in] awsIotMqttMode Specifies if this SUBSCRIBE packet is being sent to
* an AWS IoT MQTT server.
* @param[in] pListStart First element of the list to validate.
* @param[in] listSize Number of elements in the subscription list.
*
* @return `true` if every element in the list is valid; `false` otherwise.
*/
bool _IotMqtt_ValidateSubscriptionList( IotMqttOperationType_t operation,
bool awsIotMqttMode,
const IotMqttSubscription_t * pListStart,
size_t listSize );
/*-------------------- MQTT packet serializer functions ---------------------*/
/**
* @brief Get the MQTT packet type from a stream of bytes off the network.
*
* @param[in] pNetworkConnection Reference to the network connection.
* @param[in] pNetworkInterface Function pointers used to interact with the
* network.
*
* @return One of the server-to-client MQTT packet types.
*
* @note This function is only used for incoming packets, and may not work
* correctly for outgoing packets.
*/
uint8_t _IotMqtt_GetPacketType( void * pNetworkConnection,
const IotNetworkInterface_t * pNetworkInterface );
/**
* @brief Get the remaining length from a stream of bytes off the network.
*
* @param[in] pNetworkConnection Reference to the network connection.
* @param[in] pNetworkInterface Function pointers used to interact with the
* network.
*
* @return The remaining length; #MQTT_REMAINING_LENGTH_INVALID on error.
*/
size_t _IotMqtt_GetRemainingLength( void * pNetworkConnection,
const IotNetworkInterface_t * pNetworkInterface );
/**
* @brief Generate a CONNECT packet from the given parameters.
*
* @param[in] pConnectInfo User-provided CONNECT information.
* @param[out] pConnectPacket Where the CONNECT packet is written.
* @param[out] pPacketSize Size of the packet written to `pConnectPacket`.
*
* @return #IOT_MQTT_SUCCESS or #IOT_MQTT_NO_MEMORY.
*/
IotMqttError_t _IotMqtt_SerializeConnect( const IotMqttConnectInfo_t * pConnectInfo,
uint8_t ** pConnectPacket,
size_t * pPacketSize );
/**
* @brief Deserialize a CONNACK packet.
*
* Converts the packet from a stream of bytes to an #IotMqttError_t. Also
* prints out debug log messages about the packet.
*
* @param[in,out] pConnack Pointer to an MQTT packet struct representing a CONNACK.
*
* @return #IOT_MQTT_SUCCESS if CONNACK specifies that CONNECT was accepted;
* #IOT_MQTT_SERVER_REFUSED if CONNACK specifies that CONNECT was rejected;
* #IOT_MQTT_BAD_RESPONSE if the CONNACK packet doesn't follow MQTT spec.
*/
IotMqttError_t _IotMqtt_DeserializeConnack( _mqttPacket_t * pConnack );
/**
* @brief Generate a PUBLISH packet from the given parameters.
*
* @param[in] pPublishInfo User-provided PUBLISH information.
* @param[out] pPublishPacket Where the PUBLISH packet is written.
* @param[out] pPacketSize Size of the packet written to `pPublishPacket`.
* @param[out] pPacketIdentifier The packet identifier generated for this PUBLISH.
* @param[out] pPacketIdentifierHigh Where the high byte of the packet identifier
* is written.
*
* @return #IOT_MQTT_SUCCESS or #IOT_MQTT_NO_MEMORY.
*/
IotMqttError_t _IotMqtt_SerializePublish( const IotMqttPublishInfo_t * pPublishInfo,
uint8_t ** pPublishPacket,
size_t * pPacketSize,
uint16_t * pPacketIdentifier,
uint8_t ** pPacketIdentifierHigh );
/**
* @brief Set the DUP bit in a QoS 1 PUBLISH packet.
*
* @param[in] pPublishPacket Pointer to the PUBLISH packet to modify.
* @param[in] pPacketIdentifierHigh The high byte of any packet identifier to modify.
* @param[out] pNewPacketIdentifier Since AWS IoT does not support the DUP flag,
* a new packet identifier is generated and should be written here. This parameter
* is only used when connected to an AWS IoT MQTT server.
*
* @note See #IotMqttPublishInfo_t for caveats with retransmission to the
* AWS IoT MQTT server.
*/
void _IotMqtt_PublishSetDup( uint8_t * pPublishPacket,
uint8_t * pPacketIdentifierHigh,
uint16_t * pNewPacketIdentifier );
/**
* @brief Deserialize a PUBLISH packet received from the server.
*
* Converts the packet from a stream of bytes to an #IotMqttPublishInfo_t and
* extracts the packet identifier. Also prints out debug log messages about the
* packet.
*
* @param[in,out] pPublish Pointer to an MQTT packet struct representing a PUBLISH.
*
* @return #IOT_MQTT_SUCCESS if PUBLISH is valid; #IOT_MQTT_BAD_RESPONSE
* if the PUBLISH packet doesn't follow MQTT spec.
*/
IotMqttError_t _IotMqtt_DeserializePublish( _mqttPacket_t * pPublish );
/**
* @brief Generate a PUBACK packet for the given packet identifier.
*
* @param[in] packetIdentifier The packet identifier to place in PUBACK.
* @param[out] pPubackPacket Where the PUBACK packet is written.
* @param[out] pPacketSize Size of the packet written to `pPubackPacket`.
*
* @return #IOT_MQTT_SUCCESS or #IOT_MQTT_NO_MEMORY.
*/
IotMqttError_t _IotMqtt_SerializePuback( uint16_t packetIdentifier,
uint8_t ** pPubackPacket,
size_t * pPacketSize );
/**
* @brief Deserialize a PUBACK packet.
*
* Converts the packet from a stream of bytes to an #IotMqttError_t and extracts
* the packet identifier. Also prints out debug log messages about the packet.
*
* @param[in,out] pPuback Pointer to an MQTT packet struct representing a PUBACK.
*
* @return #IOT_MQTT_SUCCESS if PUBACK is valid; #IOT_MQTT_BAD_RESPONSE
* if the PUBACK packet doesn't follow MQTT spec.
*/
IotMqttError_t _IotMqtt_DeserializePuback( _mqttPacket_t * pPuback );
/**
* @brief Generate a SUBSCRIBE packet from the given parameters.
*
* @param[in] pSubscriptionList User-provided array of subscriptions.
* @param[in] subscriptionCount Size of `pSubscriptionList`.
* @param[out] pSubscribePacket Where the SUBSCRIBE packet is written.
* @param[out] pPacketSize Size of the packet written to `pSubscribePacket`.
* @param[out] pPacketIdentifier The packet identifier generated for this SUBSCRIBE.
*
* @return #IOT_MQTT_SUCCESS or #IOT_MQTT_NO_MEMORY.
*/
IotMqttError_t _IotMqtt_SerializeSubscribe( const IotMqttSubscription_t * pSubscriptionList,
size_t subscriptionCount,
uint8_t ** pSubscribePacket,
size_t * pPacketSize,
uint16_t * pPacketIdentifier );
/**
* @brief Deserialize a SUBACK packet.
*
* Converts the packet from a stream of bytes to an #IotMqttError_t and extracts
* the packet identifier. Also prints out debug log messages about the packet.
*
* @param[in,out] pSuback Pointer to an MQTT packet struct representing a SUBACK.
*
* @return #IOT_MQTT_SUCCESS if SUBACK is valid; #IOT_MQTT_BAD_RESPONSE
* if the SUBACK packet doesn't follow MQTT spec.
*/
IotMqttError_t _IotMqtt_DeserializeSuback( _mqttPacket_t * pSuback );
/**
* @brief Generate an UNSUBSCRIBE packet from the given parameters.
*
* @param[in] pSubscriptionList User-provided array of subscriptions to remove.
* @param[in] subscriptionCount Size of `pSubscriptionList`.
* @param[out] pUnsubscribePacket Where the UNSUBSCRIBE packet is written.
* @param[out] pPacketSize Size of the packet written to `pUnsubscribePacket`.
* @param[out] pPacketIdentifier The packet identifier generated for this UNSUBSCRIBE.
*
* @return #IOT_MQTT_SUCCESS or #IOT_MQTT_NO_MEMORY.
*/
IotMqttError_t _IotMqtt_SerializeUnsubscribe( const IotMqttSubscription_t * pSubscriptionList,
size_t subscriptionCount,
uint8_t ** pUnsubscribePacket,
size_t * pPacketSize,
uint16_t * pPacketIdentifier );
/**
* @brief Deserialize a UNSUBACK packet.
*
* Converts the packet from a stream of bytes to an #IotMqttError_t and extracts
* the packet identifier. Also prints out debug log messages about the packet.
*
* @param[in,out] pUnsuback Pointer to an MQTT packet struct representing an UNSUBACK.
*
* @return #IOT_MQTT_SUCCESS if UNSUBACK is valid; #IOT_MQTT_BAD_RESPONSE
* if the UNSUBACK packet doesn't follow MQTT spec.
*/
IotMqttError_t _IotMqtt_DeserializeUnsuback( _mqttPacket_t * pUnsuback );
/**
* @brief Generate a PINGREQ packet.
*
* @param[out] pPingreqPacket Where the PINGREQ packet is written.
* @param[out] pPacketSize Size of the packet written to `pPingreqPacket`.
*
* @return Always returns #IOT_MQTT_SUCCESS.
*/
IotMqttError_t _IotMqtt_SerializePingreq( uint8_t ** pPingreqPacket,
size_t * pPacketSize );
/**
* @brief Deserialize a PINGRESP packet.
*
* Converts the packet from a stream of bytes to an #IotMqttError_t. Also
* prints out debug log messages about the packet.
*
* @param[in,out] pPingresp Pointer to an MQTT packet struct representing a PINGRESP.
*
* @return #IOT_MQTT_SUCCESS if PINGRESP is valid; #IOT_MQTT_BAD_RESPONSE
* if the PINGRESP packet doesn't follow MQTT spec.
*/
IotMqttError_t _IotMqtt_DeserializePingresp( _mqttPacket_t * pPingresp );
/**
* @brief Generate a DISCONNECT packet.
*
* @param[out] pDisconnectPacket Where the DISCONNECT packet is written.
* @param[out] pPacketSize Size of the packet written to `pDisconnectPacket`.
*
* @return Always returns #IOT_MQTT_SUCCESS.
*/
IotMqttError_t _IotMqtt_SerializeDisconnect( uint8_t ** pDisconnectPacket,
size_t * pPacketSize );
/**
* @brief Free a packet generated by the serializer.
*
* @param[in] pPacket The packet to free.
*/
void _IotMqtt_FreePacket( uint8_t * pPacket );
/*-------------------- MQTT operation record functions ----------------------*/
/**
* @brief Create a record for a new in-progress MQTT operation.
*
* @param[in] pMqttConnection The MQTT connection to associate with the operation.
* @param[in] flags Flags variable passed to a user-facing MQTT function.
* @param[in] pCallbackInfo User-provided callback function and parameter.
* @param[out] pNewOperation Set to point to the new operation on success.
*
* @return #IOT_MQTT_SUCCESS, #IOT_MQTT_BAD_PARAMETER, or #IOT_MQTT_NO_MEMORY.
*/
IotMqttError_t _IotMqtt_CreateOperation( _mqttConnection_t * pMqttConnection,
uint32_t flags,
const IotMqttCallbackInfo_t * pCallbackInfo,
_mqttOperation_t ** pNewOperation );
/**
* @brief Decrement the job reference count of an MQTT operation and optionally
* cancel its job.
*
* Checks if the operation may be destroyed afterwards.
*
* @param[in] pOperation The MQTT operation with the job to cancel.
* @param[in] cancelJob Whether to attempt cancellation of the operation's job.
*
* @return `true` if the the operation may be safely destroyed; `false` otherwise.
*/
bool _IotMqtt_DecrementOperationReferences( _mqttOperation_t * pOperation,
bool cancelJob );
/**
* @brief Free resources used to record an MQTT operation. This is called when
* the operation completes.
*
* @param[in] pOperation The operation which completed.
*/
void _IotMqtt_DestroyOperation( _mqttOperation_t * pOperation );
/**
* @brief Task pool routine for processing an MQTT connection's keep-alive.
*
* @param[in] pTaskPool Pointer to the system task pool.
* @param[in] pKeepAliveJob Pointer the an MQTT connection's keep-alive job.
* @param[in] pContext Pointer to an MQTT connection, passed as an opaque context.
*/
void _IotMqtt_ProcessKeepAlive( IotTaskPool_t pTaskPool,
IotTaskPoolJob_t pKeepAliveJob,
void * pContext );
/**
* @brief Task pool routine for processing an incoming PUBLISH message.
*
* @param[in] pTaskPool Pointer to the system task pool.
* @param[in] pPublishJob Pointer to the incoming PUBLISH operation's job.
* @param[in] pContext Pointer to the incoming PUBLISH operation, passed as an
* opaque context.
*/
void _IotMqtt_ProcessIncomingPublish( IotTaskPool_t pTaskPool,
IotTaskPoolJob_t pPublishJob,
void * pContext );
/**
* @brief Task pool routine for processing an MQTT operation to send.
*
* @param[in] pTaskPool Pointer to the system task pool.
* @param[in] pSendJob Pointer to an operation's job.
* @param[in] pContext Pointer to the operation to send, passed as an opaque
* context.
*/
void _IotMqtt_ProcessSend( IotTaskPool_t pTaskPool,
IotTaskPoolJob_t pSendJob,
void * pContext );
/**
* @brief Task pool routine for processing a completed MQTT operation.
*
* @param[in] pTaskPool Pointer to the system task pool.
* @param[in] pOperationJob Pointer to the completed operation's job.
* @param[in] pContext Pointer to the completed operation, passed as an opaque
* context.
*/
void _IotMqtt_ProcessCompletedOperation( IotTaskPool_t pTaskPool,
IotTaskPoolJob_t pOperationJob,
void * pContext );
/**
* @brief Schedule an operation for immediate processing.
*
* @param[in] pOperation The operation to schedule.
* @param[in] jobRoutine The routine to run for the job. Must be either
* #_IotMqtt_ProcessSend, #_IotMqtt_ProcessCompletedOperation, or
* #_IotMqtt_ProcessIncomingPublish.
* @param[in] delay A delay before the operation job should be executed. Pass
* `0` to execute ASAP.
*
* @return #IOT_MQTT_SUCCESS or #IOT_MQTT_SCHEDULING_ERROR.
*/
IotMqttError_t _IotMqtt_ScheduleOperation( _mqttOperation_t * pOperation,
IotTaskPoolRoutine_t jobRoutine,
uint32_t delay );
/**
* @brief Search a list of MQTT operations pending responses using an operation
* name and packet identifier. Removes a matching operation from the list if found.
*
* @param[in] pMqttConnection The connection associated with the operation.
* @param[in] type The operation type to look for.
* @param[in] pPacketIdentifier A packet identifier to match. Pass `NULL` to ignore.
*
* @return Pointer to any matching operation; `NULL` if no match was found.
*/
_mqttOperation_t * _IotMqtt_FindOperation( _mqttConnection_t * pMqttConnection,
IotMqttOperationType_t type,
const uint16_t * pPacketIdentifier );
/**
* @brief Notify of a completed MQTT operation.
*
* @param[in] pOperation The MQTT operation which completed.
*
* Depending on the parameters passed to a user-facing MQTT function, the
* notification will cause @ref mqtt_function_wait to return or invoke a
* user-provided callback.
*/
void _IotMqtt_Notify( _mqttOperation_t * pOperation );
/*----------------- MQTT subscription management functions ------------------*/
/**
* @brief Add an array of subscriptions to the subscription manager.
*
* @param[in] pMqttConnection The MQTT connection associated with the subscriptions.
* @param[in] subscribePacketIdentifier Packet identifier for the subscriptions'
* SUBSCRIBE packet.
* @param[in] pSubscriptionList The first element in the array.
* @param[in] subscriptionCount Number of elements in `pSubscriptionList`.
*
* @return #IOT_MQTT_SUCCESS or #IOT_MQTT_NO_MEMORY.
*/
IotMqttError_t _IotMqtt_AddSubscriptions( _mqttConnection_t * pMqttConnection,
uint16_t subscribePacketIdentifier,
const IotMqttSubscription_t * pSubscriptionList,
size_t subscriptionCount );
/**
* @brief Process a received PUBLISH from the server, invoking any subscription
* callbacks that have a matching topic filter.
*
* @param[in] pMqttConnection The MQTT connection associated with the received
* PUBLISH.
* @param[in] pCallbackParam The parameter to pass to a PUBLISH callback.
*/
void _IotMqtt_InvokeSubscriptionCallback( _mqttConnection_t * pMqttConnection,
IotMqttCallbackParam_t * pCallbackParam );
/**
* @brief Remove a single subscription from the subscription manager by
* packetIdentifier and order.
*
* @param[in] pMqttConnection The MQTT connection associated with the subscriptions.
* @param[in] packetIdentifier The packet identifier associated with the subscription's
* SUBSCRIBE packet.
* @param[in] order The order of the subscription in the SUBSCRIBE packet.
* Pass `-1` to ignore order and remove all subscriptions for `packetIdentifier`.
*/
void _IotMqtt_RemoveSubscriptionByPacket( _mqttConnection_t * pMqttConnection,
uint16_t packetIdentifier,
int32_t order );
/**
* @brief Remove an array of subscriptions from the subscription manager by
* topic filter.
*
* @param[in] pMqttConnection The MQTT connection associated with the subscriptions.
* @param[in] pSubscriptionList The first element in the array.
* @param[in] subscriptionCount Number of elements in `pSubscriptionList`.
*/
void _IotMqtt_RemoveSubscriptionByTopicFilter( _mqttConnection_t * pMqttConnection,
const IotMqttSubscription_t * pSubscriptionList,
size_t subscriptionCount );
/*------------------ MQTT connection management functions -------------------*/
/**
* @brief Attempt to increment the reference count of an MQTT connection.
*
* @param[in] pMqttConnection The referenced MQTT connection.
*
* @return `true` if the reference count was incremented; `false` otherwise. The
* reference count will not be incremented for a disconnected connection.
*/
bool _IotMqtt_IncrementConnectionReferences( _mqttConnection_t * pMqttConnection );
/**
* @brief Decrement the reference count of an MQTT connection.
*
* Also destroys an unreferenced MQTT connection.
*
* @param[in] pMqttConnection The referenced MQTT connection.
*/
void _IotMqtt_DecrementConnectionReferences( _mqttConnection_t * pMqttConnection );
/**
* @brief Read the next available byte on a network connection.
*
* @param[in] pNetworkConnection Reference to the network connection.
* @param[in] pNetworkInterface Function pointers used to interact with the
* network.
* @param[out] pIncomingByte The byte read from the network.
*
* @return `true` if a byte was successfully received from the network; `false`
* otherwise.
*/
bool _IotMqtt_GetNextByte( void * pNetworkConnection,
const IotNetworkInterface_t * pNetworkInterface,
uint8_t * pIncomingByte );
/**
* @brief Closes the network connection associated with an MQTT connection.
*
* A network disconnect function must be set in the network interface for the
* network connection to be closed.
*
* @param[in] disconnectReason A reason to pass to the connection's disconnect
* callback.
* @param[in] pMqttConnection The MQTT connection with the network connection
* to close.
*/
void _IotMqtt_CloseNetworkConnection( IotMqttDisconnectReason_t disconnectReason,
_mqttConnection_t * pMqttConnection );
#endif /* ifndef IOT_MQTT_INTERNAL_H_ */