diff --git a/.gitmodules b/.gitmodules index 77ca17f8fc..27be47e251 100644 --- a/.gitmodules +++ b/.gitmodules @@ -49,3 +49,6 @@ [submodule "FreeRTOS-Plus/Source/AWS/ota"] path = FreeRTOS-Plus/Source/AWS/ota url = https://github.com/aws/ota-for-aws-iot-embedded-sdk.git +[submodule "FreeRTOS-Plus/Source/Application-Protocols/coreSNTP"] + path = FreeRTOS-Plus/Source/Application-Protocols/coreSNTP + url = https://github.com/FreeRTOS/coreSNTP.git diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/DemoTasks/SNTPClientTask.c b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/DemoTasks/SNTPClientTask.c new file mode 100755 index 0000000000..e0501dc82b --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/DemoTasks/SNTPClientTask.c @@ -0,0 +1,802 @@ +/* + * FreeRTOS V202104.00 + * Copyright (C) 2021 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. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * This file is part of the demo project that shows use of the coreSNTP library to create + * an SNTP client (daemon) task for synchronizing system time with internet time and + * maintaining Coordinated Universal Time (UTC) (or wall-clock time) in the system. + * + * This file contains the SNTP client (daemon) task as well as functionality for + * maintaining wall-clock or UTC time in RAM. The SNTP client periodically synchronizes + * system clock with an SNTP/NTP servers. Any other task running an application in the + * system can query the system time. For an example of an application task querying time + * from the system, refer to the SampleAppTask.c file in this project. + * + * !!! NOTE !!! + * This SNTP demo does not authenticate the server nor the client. + * Hence, this demo should not be used as production ready code. + */ + +/* Standard includes. */ +#include +#include +#include +#include + +/* Kernel includes. */ +#include "FreeRTOS.h" +#include "task.h" + +/* Demo include. */ +#include "common_demo_include.h" + +/* SNTP library include. */ +#include "core_sntp_client.h" + +/* Synchronization primitive include. */ +#include "semphr.h" + +/* FreeRTOS+TCP includes */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_UDP_IP.h" +#include "FreeRTOS_Sockets.h" + +/*-----------------------------------------------------------*/ + +/* Compile time error for undefined configs. */ + +#ifndef democonfigLIST_OF_TIME_SERVERS + #error "Define the democonfigLIST_OF_TIME_SERVERS config by following the instructions in demo_config.h file." +#endif + +#ifndef democonfigDESIRED_CLOCK_ACCURACY_MS + #error "Define the democonfigDESIRED_CLOCK_ACCURACY_MS config by following instructions in demo_config.h file." +#endif + +#ifndef democonfigSYSTEM_CLOCK_TOLERANCE_PPM + #error "Define the democonfigSYSTEM_CLOCK_TOLERANCE_PPM config by following instructions in demo_config.h file." +#endif + +#ifndef democonfigSYSTEM_START_YEAR + #error "Define the democonfigSYSTEM_START_YEAR config by following instructions in demo_config.h file." +#endif + +/*-----------------------------------------------------------*/ +/* Default values for configuration . */ + +#ifndef democonfigSERVER_RESPONSE_TIMEOUT_MS + #define democonfigSERVER_RESPONSE_TIMEOUT_MS ( 5000 ) +#endif + +/** + * @brief The size for network buffer that is allocated for initializing the coreSNTP library in the + * demo. + * + * @note The size of the buffer MUST be large enough to hold an entire SNTP packet, which includes the standard SNTP + * packet data of 48 bytes and authentication data for security mechanism, if used, in communication with time server. + */ +#define SNTP_CONTEXT_NETWORK_BUFFER_SIZE ( SNTP_PACKET_BASE_SIZE ) + +/** + * @brief The constant for storing the number of milliseconds per FreeRTOS tick in the system. + * @note This value represents the time duration per tick from the perspective of the + * of Windows Simulator based FreeRTOS system that carries lagging clock drift in relation to + * internet time or UTC time. Thus, the actual time duration value per tick of the system will be + * larger from the perspective of internet time. + */ +#define MILLISECONDS_PER_TICK ( 1000 / configTICK_RATE_HZ ) + +/*-----------------------------------------------------------*/ + +/** + * @brief The definition of the @ref NetworkContext_t structure for the demo. + * The structure wraps a FreeRTOS+TCP socket that is used for UDP communication + * with time servers. + * + * @note The context is used in the @ref UdpTransportInterface_t interface required + * by the coreSNTP library. + * + */ +struct NetworkContext +{ + Socket_t socket; +}; + +/** + * @brief Structure aggregating state variables for RAM-based wall-clock time + * in Coordinated Universal Time (UTC) for system. + * + * @note This demo uses the following mathematical model to represent current + * time in RAM. + * + * BaseTime = Time set at boot or the last synchronized time + * Slew Rate = Number of seconds to adjust per system time second + * No. of ticks since last SNTP sync = Current FreeRTOS Tick Count - + * Tick count at last SNTP sync + * + * Time Elapsed since last SNTP sync = No. of ticks since last SNTP sync + * x + * Number of milliseconds per FreeRTOS tick + * + * Slew Adjustment = Slew Rate x Time Elapsed since last SNTP sync + * + * Current Time = Base Time + + * Time Elapsed since last SNTP sync + + * Slew Adjustment + */ +typedef struct SystemClock +{ + UTCTime_t baseTime; + TickType_t lastSyncTickCount; + uint32_t pollPeriod; + uint32_t slewRate; /* Seconds/Seconds */ + bool firstTimeSyncDone; +} SystemClock_t; + +/** + * @brief Shared global system clock object for representing UTC/wall-clock + * time in system. + */ +static SystemClock_t systemClock; + +/** + * @brief Mutex for protecting access to the shared memory of the + * system clock parameters. + */ +static SemaphoreHandle_t xMutex = NULL; +static StaticSemaphore_t xSemaphoreMutex; + +/*-----------------------------------------------------------*/ + +/** + * @brief Utility function to convert the passed year to UNIX time representation + * of seconds since 1st Jan 1970 00h:00m:00s seconds to 1st Jan 00h:00m:00s of the + * the passed year. + * + * This utility does account for leap years. + * + * @param[in] The year to translate. + */ +static uint32_t translateYearToUnixSeconds( uint16_t year ); + +/** + * @brief Calculates the current time in the system. + * It calculates the current time as: + * + * BaseTime = Time set at device boot or the last synchronized time + * SlewRate = Number of seconds to adjust per system time second + * + * Current Time = Base Time + + * Time since last SNTP Synchronization + + * Slew Adjustment (if slew rate > 0) for time period since + * last SNTP synchronization + * + * @param[in] pBaseTime The base time in the system clock parameters. + * @param[in] lastSyncTickCount The tick count at the last time synchronization + * with a time server. + * @param[in] slewRate The slew rate as seconds of clock adjustment per FreeRTOS + * system time second. + * @param[out] pCurrentTime This will be populated with the calculated current + * UTC time in the system. + */ +static void calculateCurrentTime( UTCTime_t * pBaseTime, + TickType_t lastSyncTickCount, + uint32_t slewRate, + UTCTime_t * pCurrentTime ); + +/** + * @brief Initializes the SNTP context for the SNTP client task. + * This function generates an array of the configured time servers, creates a FreeRTOS UDP socket + * for the UDP transport interface and initializes the passed SNTP context by calling the + * Sntp_Init() API of the coreSNTP library. + * + * @param[in, out] pContext The memory for the SNTP client context that will be initialized with + * Sntp_Init API. + * @param[in] pTimeServers The list of time servers configured through the democonfigLIST_OF_TIME_SERVERS + * macro in demo_config.h. + * @param[in] numOfServers The number of time servers configured in democonfigLIST_OF_TIME_SERVERS. + * @param[in] pContextBuffer The allocated network buffer that will be initialized in the SNTP context. + * @param[in] pUdpContext The memory for the network context for the UDP transport interface that will + * be passed to the SNTP client context. This will be filled with a UDP context created by this function. + * + * @return Returns `true` if initialization of SNTP client context is successful; otherwise `false`. + */ +static bool initializeSntpClient( SntpContext_t * pContext, + const char ** pTimeServers, + size_t numOfServers, + uint8_t * pContextBuffer, + size_t contextBufferSize, + NetworkContext_t * pUdpContext ); + +/** + * @brief The demo implementation of the @ref SntpResolveDns_t interface to + * allow the coreSNTP library to resolve DNS name of a time server being + * used for requesting time from. + * + * @param[in] pTimeServer The time-server whose IPv4 address is to be resolved. + * @param[out] pIpV4Addr This is filled with the resolved IPv4 address of + * @p pTimeServer. + */ +static bool resolveDns( const SntpServerInfo_t * pServerAddr, + uint32_t * pIpV4Addr ); + +/** + * @brief The demo implementation of the @ref UdpTransportSendTo_t function + * of the UDP transport interface to allow the coreSNTP library to perform + * network operation of sending time request over UDP to the provided time server. + * + * @param[in] pNetworkContext This will be the NetworkContext_t context object + * representing the FreeRTOS UDP socket to use for network send operation. + * @param[in] serverAddr The IPv4 address of the time server. + * @param[in] serverPort The port of the server to send data to. + * @param[in] pBuffer The demo-supplied network buffer of size, SNTP_CONTEXT_NETWORK_BUFFER_SIZE, + * containing the data to send over the network. + * @param[in] bytesToSend The size of data in @p pBuffer to send. + * + * @return Returns the return code of FreeRTOS UDP send API, FreeRTOS_sendto, which returns + * 0 for error or timeout OR the number of bytes sent over the network. + */ +static int32_t UdpTransport_Send( NetworkContext_t * pNetworkContext, + uint32_t serverAddr, + uint16_t serverPort, + const void * pBuffer, + size_t bytesToSend ); + +/** + * @brief The demo implementation of the @ref UdpTransportRecvFrom_t function + * of the UDP transport interface to allow the coreSNTP library to perform + * network operation of reading expected time response over UDP from + * provided time server. + * + * @param[in] pNetworkContext This will be the NetworkContext_t context object + * representing the FreeRTOS UDP socket to use for network read operation. + * @param[in] pTimeServer The IPv4 address of the time server to receive data from. + * @param[in] serverPort The port of the server to receive data from. + * @param[out] pBuffer The demo-supplied network buffer of size, SNTP_CONTEXT_NETWORK_BUFFER_SIZE, + * that will be filled with data received from the network. + * @param[in] bytesToRecv The expected number of bytes to receive from the network + * for the server response server. + * + * @return Returns one of the following: + * - 0 for timeout in receiving any data from the network (by translating the + * -pdFREERTOS_ERRNO_EWOULDBLOCK return code from FreeRTOS_recvfrom API ) + * OR + * - The number of bytes read from the network. + */ +static int32_t UdpTransport_Recv( NetworkContext_t * pNetworkContext, + uint32_t serverAddr, + uint16_t serverPort, + void * pBuffer, + size_t bytesToRecv ); + +/** + * @brief The demo implementation of the @ref SntpGetTime_t interface + * for obtaining system clock time for the coreSNTP library. + * + * @param[out] pTime This will be populated with the current time from + * the system. + */ +static void sntpClient_GetTime( SntpTimestamp_t * pCurrentTime ); + +/** + * @brief The demo implementation of the @ref SntpSetTime_t interface + * for correcting the system clock time based on the time received + * from the server response and the clock-offset value calculated by + * the coreSNTP library. + * + * @note This demo uses either the "slew" OR "step" methodology of system + * clock correction based on the use-case: + * 1. "Step" correction is used if: + * - System time is ahead of server time so that system time is immediately + * corrected instead of potentially receding back in time with a "slew" + * correction approach. + * OR + * - It is the first time synchronization for the system since boot-up. Using + * "step" approach immediately corrects the system if it is far away from the + * server time on device startup instead of slowly correcting over time with + * the "slew" approach. + * + * 2. The "slew" correction approach is used for all cases other than the above + * as they represent regular time synchronization during device runtime where + * the system time may have drifted behind the server time, and can be corrected + * gradually over the SNTP client's polling interval period. + * + * @note The above system clock correction algorithm is just one example of a correction + * approach. It can be modified to suit your application needs. Examples include: + * - Always using "slew" correction if the device is always within a small time offset from + * server and your application is sensitive to non-abrupt changes in time (that could occur + * with "step" approach) for use-cases like logging events in correct order + * - Always using a "step" approach for a simplicity if your application is not sensitive to + * abrupt changes/progress in time. + */ +static void sntpClient_SetTime( const SntpServerInfo_t * pTimeServer, + const SntpTimestamp_t * pServerTime, + int32_t clockOffsetSec, + SntpLeapSecondInfo_t leapSecondInfo ); + + +/*------------------------------------------------------------------------------*/ + +static uint32_t translateYearToUnixSeconds( uint16_t year ) +{ + configASSERT( year >= 1970 ); + + uint32_t numOfDaysSince1970 = ( year - 1970 ) * 365; + + /* Calculate the extra days in leap years (for February 29) over the time + * period from 1st Jan 1970 to 1st Jan of the passed year. + * By subtracting from the year 1969, the extra day in 1972 is covered. */ + numOfDaysSince1970 += ( ( year - 1969 ) / 4 ); + + return( numOfDaysSince1970 * 24 * 3600 ); +} + +void calculateCurrentTime( UTCTime_t * pBaseTime, + TickType_t lastSyncTickCount, + uint32_t slewRate, + UTCTime_t * pCurrentTime ) +{ + uint64_t msElapsedSinceLastSync = 0; + TickType_t ticksElapsedSinceLastSync = xTaskGetTickCount() - lastSyncTickCount; + + /* Calculate time elapsed since last synchronization according to the number + * of system ticks passed. */ + msElapsedSinceLastSync = ticksElapsedSinceLastSync * MILLISECONDS_PER_TICK; + + /* If slew rate is set, then apply the slew-based clock adjustment for the elapsed time. */ + if( slewRate > 0 ) + { + msElapsedSinceLastSync += ( uint64_t ) slewRate * msElapsedSinceLastSync; + } + + /* Set the current UTC time in the output parameter. */ + if( msElapsedSinceLastSync >= 1000 ) + { + pCurrentTime->secs = pBaseTime->secs + msElapsedSinceLastSync / 1000; + pCurrentTime->msecs = msElapsedSinceLastSync % 1000; + } + else + { + pCurrentTime->secs = pBaseTime->secs; + pCurrentTime->msecs = msElapsedSinceLastSync; + } +} + +/********************** DNS Resolution Interface *******************************/ +static bool resolveDns( const SntpServerInfo_t * pServerAddr, + uint32_t * pIpV4Addr ) +{ + uint32_t resolvedAddr = 0; + bool status = false; + + resolvedAddr = FreeRTOS_gethostbyname( pServerAddr->pServerName ); + + /* Set the output parameter if DNS look up succeeded. */ + if( resolvedAddr != 0 ) + { + /* DNS Look up succeeded. */ + status = true; + + *pIpV4Addr = resolvedAddr; + + #if defined( LIBRARY_LOG_LEVEL ) && ( LIBRARY_LOG_LEVEL != LOG_NONE ) + uint8_t stringAddr[ 16 ]; + FreeRTOS_inet_ntoa( resolvedAddr, stringAddr ); + LogInfo( ( "Resolved time server as %s", stringAddr ) ); + #endif + } + + return status; +} + +/********************** UDP Interface definition *******************************/ +int32_t UdpTransport_Send( NetworkContext_t * pNetworkContext, + uint32_t serverAddr, + uint16_t serverPort, + const void * pBuffer, + size_t bytesToSend ) +{ + struct freertos_sockaddr destinationAddress; + int32_t bytesSent; + + destinationAddress.sin_addr = serverAddr; + destinationAddress.sin_port = FreeRTOS_htons( serverPort ); + + /* Send the buffer with ulFlags set to 0, so the FREERTOS_ZERO_COPY bit + * is clear. */ + bytesSent = FreeRTOS_sendto( /* The socket being send to. */ + pNetworkContext->socket, + /* The data being sent. */ + pBuffer, + /* The length of the data being sent. */ + bytesToSend, + /* ulFlags with the FREERTOS_ZERO_COPY bit clear. */ + 0, + /* Where the data is being sent. */ + &destinationAddress, + /* Not used but should be set as shown. */ + sizeof( destinationAddress ) + ); + + return bytesSent; +} + +static int32_t UdpTransport_Recv( NetworkContext_t * pNetworkContext, + uint32_t serverAddr, + uint16_t serverPort, + void * pBuffer, + size_t bytesToRecv ) +{ + struct freertos_sockaddr sourceAddress; + int32_t bytesReceived; + socklen_t addressLength = sizeof( struct freertos_sockaddr ); + + /* Receive into the buffer with ulFlags set to 0, so the FREERTOS_ZERO_COPY bit + * is clear. */ + bytesReceived = FreeRTOS_recvfrom( /* The socket data is being received on. */ + pNetworkContext->socket, + + /* The buffer into which received data will be + * copied. */ + pBuffer, + + /* The length of the buffer into which data will be + * copied. */ + bytesToRecv, + /* ulFlags with the FREERTOS_ZERO_COPY bit clear. */ + 0, + /* Will get set to the source of the received data. */ + &sourceAddress, + /* Not used but should be set as shown. */ + &addressLength + ); + + /* If data is received from the network, discard the data if received from a different source than + * the server. */ + if( ( bytesReceived > 0 ) && ( ( sourceAddress.sin_addr != serverAddr ) || + ( FreeRTOS_ntohs( sourceAddress.sin_port ) != serverPort ) ) ) + { + bytesReceived = 0; + + #if defined( LIBRARY_LOG_LEVEL ) && ( LIBRARY_LOG_LEVEL != LOG_NONE ) + /* Convert the IP address of the sender's address to string for logging. */ + char stringAddr[ 16 ]; + FreeRTOS_inet_ntoa( sourceAddress.sin_addr, stringAddr ); + + /* Log about reception of packet from unexpected sender. */ + LogWarn( ( "Received UDP packet from unexpected source: Addr=%s Port=%u", + stringAddr, FreeRTOS_ntohs( sourceAddress.sin_port ) ) ); + #endif + } + + /* Translate the return code of timeout to the UDP transport interface expected + * code to indicate read retry. */ + else if( bytesReceived == -pdFREERTOS_ERRNO_EWOULDBLOCK ) + { + bytesReceived = 0; + } + + return bytesReceived; +} + + +/**************************** Time Interfaces ************************************************/ +static void sntpClient_GetTime( SntpTimestamp_t * pCurrentTime ) +{ + UTCTime_t currentTime; + uint64_t ntpSecs; + + /* Obtain mutex for accessing system clock variables */ + xSemaphoreTake( xMutex, portMAX_DELAY ); + + calculateCurrentTime( &systemClock.baseTime, + systemClock.lastSyncTickCount, + systemClock.slewRate, + ¤tTime ); + + /* Release mutex. */ + xSemaphoreGive( xMutex ); + + /* Convert UTC time from UNIX timescale to SNTP timestamp format. */ + ntpSecs = currentTime.secs + SNTP_TIME_AT_UNIX_EPOCH_SECS; + + /* Support case of SNTP timestamp rollover on 7 February 2036 when + * converting from UNIX time to SNTP timestamp. */ + if( ntpSecs > UINT32_MAX ) + { + /* Subtract an extra second as timestamp 0 represents the epoch for + * NTP era 1. */ + pCurrentTime->seconds = ntpSecs - UINT32_MAX - 1; + } + else + { + pCurrentTime->seconds = ntpSecs; + } + + pCurrentTime->fractions = MILLISECONDS_TO_SNTP_FRACTIONS( currentTime.msecs ); +} + +static void sntpClient_SetTime( const SntpServerInfo_t * pTimeServer, + const SntpTimestamp_t * pServerTime, + int32_t clockOffsetSec, + SntpLeapSecondInfo_t leapSecondInfo ) +{ + /* TODO - Handle leap second. */ + ( void ) leapSecondInfo; + + ( void ) pTimeServer; + + /* Obtain the mutext for accessing system clock variables. */ + xSemaphoreTake( xMutex, portMAX_DELAY ); + + /* Use "step" approach if: + * The system clock has drifted ahead of server time. + * OR + * This is the first time synchronization with NTP server since device boot-up. + */ + if( ( clockOffsetSec < 0 ) || ( systemClock.firstTimeSyncDone == false ) ) + { + SntpStatus_t status; + uint32_t unixSecs; + uint32_t unixMicroSecs; + + /* Convert server time from NTP timestamp to UNIX format. */ + status = Sntp_ConvertToUnixTime( pServerTime, + &unixSecs, + &unixMicroSecs ); + configASSERT( status == SntpSuccess ); + + /* Immediately correct the base time of the system clock as server time. */ + systemClock.baseTime.secs = unixSecs; + systemClock.baseTime.msecs = unixMicroSecs / 1000; + + /* Reset slew rate to zero as the time has been immediately corrected to server time. */ + systemClock.slewRate = 0; + + /* Store the tick count of the current time synchronization in the system clock. */ + systemClock.lastSyncTickCount = xTaskGetTickCount(); + + /* Set the system clock flag that indicates completion of the first time synchronization since device boot-up. */ + if( systemClock.firstTimeSyncDone == false ) + { + systemClock.firstTimeSyncDone = true; + } + } + + /* As the system clock is behind server time, we will use a "slew" approach to gradually + * correct system time over the poll interval period. */ + else + { + /* Update the base time based on the previous slew rate and the time period transpired + * since last time synchronization. */ + calculateCurrentTime( &systemClock.baseTime, + systemClock.lastSyncTickCount, + systemClock.slewRate, + &systemClock.baseTime ); + + /* Calculate the new slew rate as offset in seconds of adjustment per second. */ + systemClock.slewRate = clockOffsetSec / systemClock.pollPeriod; + + /* Store the tick count of the current time synchronization in the system clock. */ + systemClock.lastSyncTickCount = xTaskGetTickCount(); + } + + xSemaphoreGive( xMutex ); +} + +/*************************************************************************************/ + +void initializeSystemClock( void ) +{ + /* On boot-up initialize the system time as the first second in the configured year. */ + int64_t startupTimeInUnixSecs = translateYearToUnixSeconds( democonfigSYSTEM_START_YEAR ); + + systemClock.baseTime.secs = startupTimeInUnixSecs; + systemClock.baseTime.msecs = 0; + + LogInfo( ( "System time has been initialized to the year %u", democonfigSYSTEM_START_YEAR ) ); + printTime( &systemClock.baseTime ); + + /* Initialize semaphore for guarding access to system clock variables. */ + xMutex = xSemaphoreCreateMutexStatic( &xSemaphoreMutex ); + configASSERT( xMutex ); + + /* Clear the first time sync completed flag of the system clock object so that a "step" correction + * of system time is utilized for the first time synchronization from a time server. */ + systemClock.firstTimeSyncDone = false; +} + +/*-----------------------------------------------------------*/ + +static bool initializeSntpClient( SntpContext_t * pContext, + const char ** pTimeServers, + size_t numOfServers, + uint8_t * pContextBuffer, + size_t contextBufferSize, + NetworkContext_t * pUdpContext ) +{ + bool initStatus = false; + + /* Populate the list of time servers. */ + SntpServerInfo_t * pServers = pvPortMalloc( sizeof( SntpServerInfo_t ) * numOfServers ); + + if( pServers == NULL ) + { + LogError( ( "Unable to initialize SNTP client: Malloc failed for memory of configured time servers." ) ); + } + else + { + for( int8_t index = 0; index < numOfServers; index++ ) + { + pServers[ index ].pServerName = pTimeServers[ index ]; + pServers[ index ].port = SNTP_DEFAULT_SERVER_PORT; + } + + LogInfo( ( "Calculated poll interval: %lus", systemClock.pollPeriod ) ); + + /* Create a UDP socket for network I/O with server. */ + pUdpContext->socket = FreeRTOS_socket( FREERTOS_AF_INET, + FREERTOS_SOCK_DGRAM, + FREERTOS_IPPROTO_UDP ); + + /* Check the socket was created successfully. */ + /* TODO - Consider using random port assigned by FreeRTOS for better protection */ + /* against "off-path" attacker. */ + if( pUdpContext->socket == FREERTOS_INVALID_SOCKET ) + { + /* There was insufficient FreeRTOS heap memory available for the socket + * to be created. */ + LogError( ( "Failed to create UDP socket for SNTP client due to insufficient memory." ) ); + } + else + { + struct freertos_sockaddr bindAddress; + UdpTransportInterface_t udpTransportIntf; + + bindAddress.sin_port = FreeRTOS_htons( SNTP_DEFAULT_SERVER_PORT ); + + if( FreeRTOS_bind( pUdpContext->socket, &bindAddress, sizeof( bindAddress ) ) == 0 ) + { + /* The bind was successful. */ + LogDebug( ( "UDP socket has been bound to port %lu", SNTP_DEFAULT_SERVER_PORT ) ); + } + + /* Set the UDP transport interface object. */ + udpTransportIntf.pUserContext = pUdpContext; + udpTransportIntf.sendTo = UdpTransport_Send; + udpTransportIntf.recvFrom = UdpTransport_Recv; + + /* Initialize context. */ + Sntp_Init( pContext, + pServers, + numOfServers, + democonfigSERVER_RESPONSE_TIMEOUT_MS, + pContextBuffer, + contextBufferSize, + resolveDns, + sntpClient_GetTime, + sntpClient_SetTime, + &udpTransportIntf, + NULL ); + + initStatus = true; + } + } + + return initStatus; +} + +/*-----------------------------------------------------------*/ + +void sntpTask( void * pParameters ) +{ + SntpContext_t clientContext; + bool initStatus = false; + + /* Variable representing the SNTP client context. */ + static SntpContext_t context; + + /* Memory for the SNTP packet buffer in the SNTP context. */ + static uint8_t contextBuffer[ SNTP_CONTEXT_NETWORK_BUFFER_SIZE ]; + + /* Memory for the network context representing the UDP socket that will be + * passed to the SNTP client context. */ + static NetworkContext_t udpContext; + + /* Store the configured time servers in an array. */ + static const char * pTimeServers[] = { democonfigLIST_OF_TIME_SERVERS }; + const size_t numOfServers = sizeof( pTimeServers ) / sizeof( char * ); + + initStatus = initializeSntpClient( &clientContext, + pTimeServers, + numOfServers, + contextBuffer, + sizeof( contextBuffer ), + &udpContext ); + + if( initStatus == true ) + { + SntpStatus_t status; + + /* Calculate Poll interval of SNTP client based on desired accuracy and clock tolerance of the system. */ + status = Sntp_CalculatePollInterval( democonfigSYSTEM_CLOCK_TOLERANCE_PPM, + democonfigDESIRED_CLOCK_ACCURACY_MS, + &systemClock.pollPeriod ); + configASSERT( status == SntpSuccess ); + + LogInfo( ( "Initialized SNTP Client context. Starting the SNTP client loop for time synchronization every %lu seconds", + systemClock.pollPeriod ) ); + + /* SNTP Client loop of sending and receiving SNTP packets for time synchronization at poll intervals */ + while( 1 ) + { + /* TODO - Generate random number with corePKCS11. */ + status = Sntp_SendTimeRequest( &clientContext, 100 ); + configASSERT( status == SntpSuccess ); + + /* Wait till the server response is not received. */ + do + { + /* Attempt to receive server response each time for 200 ms. */ + status = Sntp_ReceiveTimeResponse( &clientContext, 200 ); + } while( status == SntpNoResponseReceived ); + + /* Wait for the poll interval period before the next iteration of time synchronization. */ + vTaskDelay( pdMS_TO_TICKS( systemClock.pollPeriod * 1000 ) ); + } + } + else + { + configASSERT( false ); + + /* Terminate the task as the SNTP client failed to be run. */ + LogError( ( "Failed to initialize SNTP client. Terminating SNTP client task.." ) ); + + vTaskDelete( NULL ); + } +} + +/*-----------------------------------------------------------*/ + +void systemGetWallClockTime( UTCTime_t * pTime ) +{ + TickType_t xTickCount = 0; + uint32_t ulTimeMs = 0UL; + + /* Obtain the mutext for accessing system clock variables. */ + xSemaphoreTake( xMutex, portMAX_DELAY ); + + /* Calculate the current RAM-based time using a mathematical formula using + * system clock state parameters and the time transpired since last synchronization. */ + calculateCurrentTime( &systemClock.baseTime, + systemClock.lastSyncTickCount, + systemClock.slewRate, + pTime ); + + xSemaphoreGive( xMutex ); +} + +/*-----------------------------------------------------------*/ diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/DemoTasks/SampleAppTask.c b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/DemoTasks/SampleAppTask.c new file mode 100755 index 0000000000..53cdb527f5 --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/DemoTasks/SampleAppTask.c @@ -0,0 +1,92 @@ +/* + * FreeRTOS V202104.00 + * Copyright (C) 2021 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. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * This file belongs to the demo for showing use of the coreSNTP library for synchronizing + * system time with internet time and maintaining correct wall-clock time. + * + * This file shows how an application task can query Coordinated Universal Time (UTC) from system, + * that is maintained and synchronized periodically in the SNTP client (daemon) task of the demo + * project. Refer to the the SNTPClientTask.c file in this project for the SNTP client task. + */ + +/* Standard includes. */ +#include +#include +#include +#include + +/* Kernel includes. */ +#include "FreeRTOS.h" +#include "task.h" + +/* Demo includes. */ +#include "common_demo_include.h" + +/*-----------------------------------------------------------*/ + +/** + * @brief The periodicity of the application task in query and logging system time. This is the time + * interval between consecutive system clock time queries in the sample application task. + */ +#define CLOCK_QUERY_TASK_DELAY_MS ( 1000 ) + +/*-----------------------------------------------------------*/ + +void printTime( const UTCTime_t * pUnixTime ) +{ + struct tm * currTime; + time_t time; + + /* Obtain the broken-down UTC representation of the current system time. */ + time = pUnixTime->secs; + currTime = gmtime( &time ); + + /* Log the time as both UNIX timestamp and Human Readable time. */ + LogInfo( ( "Time:\nUNIX=%lusecs %lums\nHuman Readable=%lu-%02lu-%02lu %02luh:%02lum:%02lus", + pUnixTime->secs, pUnixTime->msecs, + currTime->tm_year + 1900, currTime->tm_mon + 1, currTime->tm_mday, + currTime->tm_hour, currTime->tm_min, currTime->tm_sec ) ); +} + +/*************************************************************************************/ + +/* Sample application task that will query and log system time every second. */ +void sampleAppTask( void * pvParameters ) +{ + UTCTime_t systemTime; + + while( 1 ) + { + systemGetWallClockTime( &systemTime ); + + printTime( &systemTime ); + + vTaskDelay( pdMS_TO_TICKS( CLOCK_QUERY_TASK_DELAY_MS ) ); + } +} + +/*-----------------------------------------------------------*/ diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/FreeRTOSConfig.h b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/FreeRTOSConfig.h new file mode 100755 index 0000000000..9cb3f18563 --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/FreeRTOSConfig.h @@ -0,0 +1,203 @@ +/* + * FreeRTOS V202104.00 + * Copyright (C) 2020 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://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +/*----------------------------------------------------------- +* Application specific definitions. +* +* These definitions should be adjusted for your particular hardware and +* application requirements. +* +* THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE +* FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. +* http://www.freertos.org/a00110.html +* +* The bottom of this file contains some constants specific to running the UDP +* stack in this demo. Constants specific to FreeRTOS+TCP itself (rather than +* the demo) are contained in FreeRTOSIPConfig.h. +*----------------------------------------------------------*/ +#define configUSE_PREEMPTION 1 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 +#define configMAX_PRIORITIES ( 7 ) +#define configTICK_RATE_HZ ( 1000 ) /* In this non-real time simulated environment the tick frequency has to be at least a multiple of the Win32 tick frequency, and therefore very slow. */ +#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 60 ) /* In this simulated case, the stack only has to hold one small structure as the real stack is part of the Win32 thread. */ +#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 2048U * 1024U ) ) +#define configMAX_TASK_NAME_LEN ( 15 ) +#define configUSE_TRACE_FACILITY 0 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 1 +#define configUSE_CO_ROUTINES 0 +#define configUSE_MUTEXES 1 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 0 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configUSE_ALTERNATIVE_API 0 +#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 +#define configENABLE_BACKWARD_COMPATIBILITY 1 +#define configSUPPORT_STATIC_ALLOCATION 1 +#define configUSE_STATS_FORMATTING_FUNCTIONS 0 + +/* Hook function related definitions. */ +#define configUSE_TICK_HOOK 0 +#define configUSE_IDLE_HOOK 0 +#define configUSE_MALLOC_FAILED_HOOK 0 +#define configCHECK_FOR_STACK_OVERFLOW 0 /* Not applicable to the Win32 port. */ + +/* Software timer related definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) +#define configTIMER_QUEUE_LENGTH 5 +#define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE * 2 ) + +/* Event group related definitions. */ +#define configUSE_EVENT_GROUPS 1 + +/* Run time stats gathering configuration options. */ +#define configGENERATE_RUN_TIME_STATS 0 + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES ( 2 ) + +/* Set the following definitions to 1 to include the API function, or zero + * to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 0 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 1 +#define INCLUDE_xTaskGetSchedulerState 1 +#define INCLUDE_xTimerGetTimerTaskHandle 0 +#define INCLUDE_xTaskGetIdleTaskHandle 0 +#define INCLUDE_xQueueGetMutexHolder 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xEventGroupSetBitsFromISR 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_pcTaskGetTaskName 1 + +/* Assert call defined for debug builds. */ +#ifdef _DEBUG + extern void vAssertCalled( const char * pcFile, + uint32_t ulLine ); + #define configASSERT( x ) if( ( x ) == 0 ) vAssertCalled( __FILE__, __LINE__ ) +#endif /* _DEBUG */ + + + +/* Application specific definitions follow. **********************************/ + +/* Only used when running in the FreeRTOS Windows simulator. Defines the + * priority of the task used to simulate Ethernet interrupts. */ +#define configMAC_ISR_SIMULATOR_PRIORITY ( configMAX_PRIORITIES - 1 ) + +/* This demo creates a virtual network connection by accessing the raw Ethernet + * or WiFi data to and from a real network connection. Many computers have more + * than one real network port, and configNETWORK_INTERFACE_TO_USE is used to tell + * the demo which real port should be used to create the virtual port. The ports + * available are displayed on the console when the application is executed. For + * example, on my development laptop setting configNETWORK_INTERFACE_TO_USE to 4 + * results in the wired network being used, while setting + * configNETWORK_INTERFACE_TO_USE to 2 results in the wireless network being + * used. */ +#define configNETWORK_INTERFACE_TO_USE ( 2L ) + +/* The address to which logging is sent should UDP logging be enabled. */ +#define configUDP_LOGGING_ADDR0 192 +#define configUDP_LOGGING_ADDR1 168 +#define configUDP_LOGGING_ADDR2 0 +#define configUDP_LOGGING_ADDR3 11 + +/* Default MAC address configuration. The demo creates a virtual network + * connection that uses this MAC address by accessing the raw Ethernet/WiFi data + * to and from a real network connection on the host PC. See the + * configNETWORK_INTERFACE_TO_USE definition above for information on how to + * configure the real network connection to use. */ +#define configMAC_ADDR0 0x00 +#define configMAC_ADDR1 0x11 +#define configMAC_ADDR2 0x11 +#define configMAC_ADDR3 0x11 +#define configMAC_ADDR4 0x11 +#define configMAC_ADDR5 0x41 + +/* Default IP address configuration. Used in ipconfigUSE_DNS is set to 0, or + * ipconfigUSE_DNS is set to 1 but a DNS server cannot be contacted. */ +#define configIP_ADDR0 10 +#define configIP_ADDR1 10 +#define configIP_ADDR2 10 +#define configIP_ADDR3 200 + +/* Default gateway IP address configuration. Used in ipconfigUSE_DNS is set to + * 0, or ipconfigUSE_DNS is set to 1 but a DNS server cannot be contacted. */ +#define configGATEWAY_ADDR0 10 +#define configGATEWAY_ADDR1 10 +#define configGATEWAY_ADDR2 10 +#define configGATEWAY_ADDR3 1 + +/* Default DNS server configuration. OpenDNS addresses are 208.67.222.222 and + * 208.67.220.220. Used in ipconfigUSE_DNS is set to 0, or ipconfigUSE_DNS is set + * to 1 but a DNS server cannot be contacted.*/ +#define configDNS_SERVER_ADDR0 208 +#define configDNS_SERVER_ADDR1 67 +#define configDNS_SERVER_ADDR2 222 +#define configDNS_SERVER_ADDR3 222 + +/* Default netmask configuration. Used in ipconfigUSE_DNS is set to 0, or + * ipconfigUSE_DNS is set to 1 but a DNS server cannot be contacted. */ +#define configNET_MASK0 255 +#define configNET_MASK1 0 +#define configNET_MASK2 0 +#define configNET_MASK3 0 + +/* The UDP port to which print messages are sent. */ +#define configPRINT_PORT ( 15000 ) + + +#if ( defined( _MSC_VER ) && ( _MSC_VER <= 1600 ) && !defined( snprintf ) ) + /* Map to Windows names. */ + #define snprintf _snprintf + #define vsnprintf _vsnprintf +#endif + +/* Visual studio does not have an implementation of strcasecmp(). */ +#define strcasecmp _stricmp +#define strncasecmp _strnicmp +#define strcmpi _strcmpi + +/* Prototype for the function used to print out. In this case it prints to the + * console before the network is connected then a UDP port after the network has + * connected. */ +extern void vLoggingPrintf( const char * pcFormatString, + ... ); +#define configPRINTF( X ) vLoggingPrintf X + +#endif /* FREERTOS_CONFIG_H */ diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/FreeRTOSIPConfig.h b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/FreeRTOSIPConfig.h new file mode 100755 index 0000000000..47eb83cf67 --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/FreeRTOSIPConfig.h @@ -0,0 +1,311 @@ +/* + * FreeRTOS V202104.00 + * Copyright (C) 2020 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://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +/***************************************************************************** +* +* See the following URL for configuration information. +* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_IP_Configuration.html +* +*****************************************************************************/ + +#ifndef FREERTOS_IP_CONFIG_H +#define FREERTOS_IP_CONFIG_H + +/* Prototype for the function used to print out. In this case it prints to the + * console before the network is connected then a UDP port after the network has + * connected. */ +extern void vLoggingPrintf( const char * pcFormatString, + ... ); + +/* Set to 1 to print out debug messages. If ipconfigHAS_DEBUG_PRINTF is set to + * 1 then FreeRTOS_debug_printf should be defined to the function used to print + * out the debugging messages. */ +#define ipconfigHAS_DEBUG_PRINTF 0 +#if ( ipconfigHAS_DEBUG_PRINTF == 1 ) + #define FreeRTOS_debug_printf( X ) vLoggingPrintf X +#endif + +/* Set to 1 to print out non debugging messages, for example the output of the + * FreeRTOS_netstat() command, and ping replies. If ipconfigHAS_PRINTF is set to 1 + * then FreeRTOS_printf should be set to the function used to print out the + * messages. */ +#define ipconfigHAS_PRINTF 1 +#if ( ipconfigHAS_PRINTF == 1 ) + #define FreeRTOS_printf( X ) vLoggingPrintf X +#endif + +/* Define the byte order of the target MCU (the MCU FreeRTOS+TCP is executing + * on). Valid options are pdFREERTOS_BIG_ENDIAN and pdFREERTOS_LITTLE_ENDIAN. */ +#define ipconfigBYTE_ORDER pdFREERTOS_LITTLE_ENDIAN + +/* If the network card/driver includes checksum offloading (IP/TCP/UDP checksums) + * then set ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM to 1 to prevent the software + * stack repeating the checksum calculations. */ +#define ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM 1 + +/* Several API's will block until the result is known, or the action has been + * performed, for example FreeRTOS_send() and FreeRTOS_recv(). The timeouts can be + * set per socket, using setsockopt(). If not set, the times below will be + * used as defaults. */ +#define ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME ( 5000 ) +#define ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME ( 5000 ) + +/* Include support for LLMNR: Link-local Multicast Name Resolution + * (non-Microsoft) */ +#define ipconfigUSE_LLMNR ( 0 ) + +/* Include support for NBNS: NetBIOS Name Service (Microsoft) */ +#define ipconfigUSE_NBNS ( 0 ) + +/* Include support for DNS caching. For TCP, having a small DNS cache is very + * useful. When a cache is present, ipconfigDNS_REQUEST_ATTEMPTS can be kept low + * and also DNS may use small timeouts. If a DNS reply comes in after the DNS + * socket has been destroyed, the result will be stored into the cache. The next + * call to FreeRTOS_gethostbyname() will return immediately, without even creating + * a socket. */ +#define ipconfigUSE_DNS_CACHE ( 1 ) +#define ipconfigDNS_CACHE_NAME_LENGTH ( 32 ) +#define ipconfigDNS_CACHE_ENTRIES ( 4 ) +#define ipconfigDNS_REQUEST_ATTEMPTS ( 2 ) + +/* The IP stack executes it its own task (although any application task can make + * use of its services through the published sockets API). ipconfigUDP_TASK_PRIORITY + * sets the priority of the task that executes the IP stack. The priority is a + * standard FreeRTOS task priority so can take any value from 0 (the lowest + * priority) to (configMAX_PRIORITIES - 1) (the highest priority). + * configMAX_PRIORITIES is a standard FreeRTOS configuration parameter defined in + * FreeRTOSConfig.h, not FreeRTOSIPConfig.h. Consideration needs to be given as to + * the priority assigned to the task executing the IP stack relative to the + * priority assigned to tasks that use the IP stack. */ +#define ipconfigIP_TASK_PRIORITY ( configMAX_PRIORITIES - 2 ) + +/* The size, in words (not bytes), of the stack allocated to the FreeRTOS+TCP + * task. This setting is less important when the FreeRTOS Win32 simulator is used + * as the Win32 simulator only stores a fixed amount of information on the task + * stack. FreeRTOS includes optional stack overflow detection, see: + * http://www.freertos.org/Stacks-and-stack-overflow-checking.html */ +#define ipconfigIP_TASK_STACK_SIZE_WORDS ( configMINIMAL_STACK_SIZE * 5 ) + +/* ipconfigRAND32() is called by the IP stack to generate random numbers for + * things such as a DHCP transaction number or initial sequence number. Random + * number generation is performed via this macro to allow applications to use their + * own random number generation method. For example, it might be possible to + * generate a random number by sampling noise on an analogue input. */ +extern UBaseType_t uxRand(); +#define ipconfigRAND32() uxRand() + +/* If ipconfigUSE_NETWORK_EVENT_HOOK is set to 1 then FreeRTOS+TCP will call the + * network event hook at the appropriate times. If ipconfigUSE_NETWORK_EVENT_HOOK + * is not set to 1 then the network event hook will never be called. See + * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_UDP/API/vApplicationIPNetworkEventHook.shtml + */ +#define ipconfigUSE_NETWORK_EVENT_HOOK 1 + +/* Sockets have a send block time attribute. If FreeRTOS_sendto() is called but + * a network buffer cannot be obtained then the calling task is held in the Blocked + * state (so other tasks can continue to executed) until either a network buffer + * becomes available or the send block time expires. If the send block time expires + * then the send operation is aborted. The maximum allowable send block time is + * capped to the value set by ipconfigMAX_SEND_BLOCK_TIME_TICKS. Capping the + * maximum allowable send block time prevents prevents a deadlock occurring when + * all the network buffers are in use and the tasks that process (and subsequently + * free) the network buffers are themselves blocked waiting for a network buffer. + * ipconfigMAX_SEND_BLOCK_TIME_TICKS is specified in RTOS ticks. A time in + * milliseconds can be converted to a time in ticks by dividing the time in + * milliseconds by portTICK_PERIOD_MS. */ +#define ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS ( 5000 / portTICK_PERIOD_MS ) + +/* If ipconfigUSE_DHCP is 1 then FreeRTOS+TCP will attempt to retrieve an IP + * address, netmask, DNS server address and gateway address from a DHCP server. If + * ipconfigUSE_DHCP is 0 then FreeRTOS+TCP will use a static IP address. The + * stack will revert to using the static IP address even when ipconfigUSE_DHCP is + * set to 1 if a valid configuration cannot be obtained from a DHCP server for any + * reason. The static configuration used is that passed into the stack by the + * FreeRTOS_IPInit() function call. */ +#define ipconfigUSE_DHCP 1 + +/* When ipconfigUSE_DHCP is set to 1, DHCP requests will be sent out at + * increasing time intervals until either a reply is received from a DHCP server + * and accepted, or the interval between transmissions reaches + * ipconfigMAXIMUM_DISCOVER_TX_PERIOD. The IP stack will revert to using the + * static IP address passed as a parameter to FreeRTOS_IPInit() if the + * re-transmission time interval reaches ipconfigMAXIMUM_DISCOVER_TX_PERIOD without + * a DHCP reply being received. */ +#define ipconfigMAXIMUM_DISCOVER_TX_PERIOD ( 120000 / portTICK_PERIOD_MS ) + +/* The ARP cache is a table that maps IP addresses to MAC addresses. The IP + * stack can only send a UDP message to a remove IP address if it knowns the MAC + * address associated with the IP address, or the MAC address of the router used to + * contact the remote IP address. When a UDP message is received from a remote IP + * address the MAC address and IP address are added to the ARP cache. When a UDP + * message is sent to a remote IP address that does not already appear in the ARP + * cache then the UDP message is replaced by a ARP message that solicits the + * required MAC address information. ipconfigARP_CACHE_ENTRIES defines the maximum + * number of entries that can exist in the ARP table at any one time. */ +#define ipconfigARP_CACHE_ENTRIES 6 + +/* ARP requests that do not result in an ARP response will be re-transmitted a + * maximum of ipconfigMAX_ARP_RETRANSMISSIONS times before the ARP request is + * aborted. */ +#define ipconfigMAX_ARP_RETRANSMISSIONS ( 5 ) + +/* ipconfigMAX_ARP_AGE defines the maximum time between an entry in the ARP + * table being created or refreshed and the entry being removed because it is stale. + * New ARP requests are sent for ARP cache entries that are nearing their maximum + * age. ipconfigMAX_ARP_AGE is specified in tens of seconds, so a value of 150 is + * equal to 1500 seconds (or 25 minutes). */ +#define ipconfigMAX_ARP_AGE 150 + +/* Implementing FreeRTOS_inet_addr() necessitates the use of string handling + * routines, which are relatively large. To save code space the full + * FreeRTOS_inet_addr() implementation is made optional, and a smaller and faster + * alternative called FreeRTOS_inet_addr_quick() is provided. FreeRTOS_inet_addr() + * takes an IP in decimal dot format (for example, "192.168.0.1") as its parameter. + * FreeRTOS_inet_addr_quick() takes an IP address as four separate numerical octets + * (for example, 192, 168, 0, 1) as its parameters. If + * ipconfigINCLUDE_FULL_INET_ADDR is set to 1 then both FreeRTOS_inet_addr() and + * FreeRTOS_indet_addr_quick() are available. If ipconfigINCLUDE_FULL_INET_ADDR is + * not set to 1 then only FreeRTOS_indet_addr_quick() is available. */ +#define ipconfigINCLUDE_FULL_INET_ADDR 1 + +/* ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS defines the total number of network buffer that + * are available to the IP stack. The total number of network buffers is limited + * to ensure the total amount of RAM that can be consumed by the IP stack is capped + * to a pre-determinable value. */ +#define ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS 60 + +/* A FreeRTOS queue is used to send events from application tasks to the IP + * stack. ipconfigEVENT_QUEUE_LENGTH sets the maximum number of events that can + * be queued for processing at any one time. The event queue must be a minimum of + * 5 greater than the total number of network buffers. */ +#define ipconfigEVENT_QUEUE_LENGTH ( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS + 5 ) + +/* The address of a socket is the combination of its IP address and its port + * number. FreeRTOS_bind() is used to manually allocate a port number to a socket + * (to 'bind' the socket to a port), but manual binding is not normally necessary + * for client sockets (those sockets that initiate outgoing connections rather than + * wait for incoming connections on a known port number). If + * ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is set to 1 then calling + * FreeRTOS_sendto() on a socket that has not yet been bound will result in the IP + * stack automatically binding the socket to a port number from the range + * socketAUTO_PORT_ALLOCATION_START_NUMBER to 0xffff. If + * ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is set to 0 then calling FreeRTOS_sendto() + * on a socket that has not yet been bound will result in the send operation being + * aborted. */ +#define ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND 1 + +/* Defines the Time To Live (TTL) values used in outgoing UDP packets. */ +#define ipconfigUDP_TIME_TO_LIVE 128 +#define ipconfigTCP_TIME_TO_LIVE 128 /* also defined in FreeRTOSIPConfigDefaults.h */ + +/* USE_TCP: Use TCP and all its features */ +#define ipconfigUSE_TCP ( 1 ) + +/* Use the TCP socket wake context with a callback. */ +#define ipconfigSOCKET_HAS_USER_WAKE_CALLBACK_WITH_CONTEXT ( 1 ) + +/* USE_WIN: Let TCP use windowing mechanism. */ +#define ipconfigUSE_TCP_WIN ( 1 ) + +/* The MTU is the maximum number of bytes the payload of a network frame can + * contain. For normal Ethernet V2 frames the maximum MTU is 1500. Setting a + * lower value can save RAM, depending on the buffer management scheme used. If + * ipconfigCAN_FRAGMENT_OUTGOING_PACKETS is 1 then (ipconfigNETWORK_MTU - 28) must + * be divisible by 8. */ +#define ipconfigNETWORK_MTU 1200 + +/* Set ipconfigUSE_DNS to 1 to include a basic DNS client/resolver. DNS is used + * through the FreeRTOS_gethostbyname() API function. */ +#define ipconfigUSE_DNS 1 + +/* If ipconfigREPLY_TO_INCOMING_PINGS is set to 1 then the IP stack will + * generate replies to incoming ICMP echo (ping) requests. */ +#define ipconfigREPLY_TO_INCOMING_PINGS 1 + +/* If ipconfigSUPPORT_OUTGOING_PINGS is set to 1 then the + * FreeRTOS_SendPingRequest() API function is available. */ +#define ipconfigSUPPORT_OUTGOING_PINGS 0 + +/* If ipconfigSUPPORT_SELECT_FUNCTION is set to 1 then the FreeRTOS_select() + * (and associated) API function is available. */ +#define ipconfigSUPPORT_SELECT_FUNCTION 1 + +/* If ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES is set to 1 then Ethernet frames + * that are not in Ethernet II format will be dropped. This option is included for + * potential future IP stack developments. */ +#define ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES 1 + +/* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1 then it is the + * responsibility of the Ethernet interface to filter out packets that are of no + * interest. If the Ethernet interface does not implement this functionality, then + * set ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES to 0 to have the IP stack + * perform the filtering instead (it is much less efficient for the stack to do it + * because the packet will already have been passed into the stack). If the + * Ethernet driver does all the necessary filtering in hardware then software + * filtering can be removed by using a value other than 1 or 0. */ +#define ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES 1 + +/* The windows simulator cannot really simulate MAC interrupts, and needs to + * block occasionally to allow other tasks to run. */ +#define configWINDOWS_MAC_INTERRUPT_SIMULATOR_DELAY ( 20 / portTICK_PERIOD_MS ) + +/* Advanced only: in order to access 32-bit fields in the IP packets with + * 32-bit memory instructions, all packets will be stored 32-bit-aligned, plus 16-bits. + * This has to do with the contents of the IP-packets: all 32-bit fields are + * 32-bit-aligned, plus 16-bit(!) */ +#define ipconfigPACKET_FILLER_SIZE 2 + +/* Define the size of the pool of TCP window descriptors. On the average, each + * TCP socket will use up to 2 x 6 descriptors, meaning that it can have 2 x 6 + * outstanding packets (for Rx and Tx). When using up to 10 TP sockets + * simultaneously, one could define TCP_WIN_SEG_COUNT as 120. */ +#define ipconfigTCP_WIN_SEG_COUNT 240 + +/* Each TCP socket has a circular buffers for Rx and Tx, which have a fixed + * maximum size. Define the size of Rx buffer for TCP sockets. */ +#define ipconfigTCP_RX_BUFFER_LENGTH ( 1000 ) + +/* Define the size of Tx buffer for TCP sockets. */ +#define ipconfigTCP_TX_BUFFER_LENGTH ( 1000 ) + +/* When using call-back handlers, the driver may check if the handler points to + * real program memory (RAM or flash) or just has a random non-zero value. */ +#define ipconfigIS_VALID_PROG_ADDRESS( x ) ( ( x ) != NULL ) + +/* Include support for TCP hang protection. All sockets in a connecting or + * disconnecting stage will timeout after a period of non-activity. */ +#define ipconfigTCP_HANG_PROTECTION ( 1 ) +#define ipconfigTCP_HANG_PROTECTION_TIME ( 30 ) + +/* Include support for TCP keep-alive messages. */ +#define ipconfigTCP_KEEP_ALIVE ( 1 ) +#define ipconfigTCP_KEEP_ALIVE_INTERVAL ( 20 ) /* in seconds */ + +#define portINLINE __inline + +#endif /* FREERTOS_IP_CONFIG_H */ diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/WIN32.vcxproj b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/WIN32.vcxproj new file mode 100644 index 0000000000..602de1d0f7 --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/WIN32.vcxproj @@ -0,0 +1,207 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {C686325E-3261-42F7-AEB1-DDE5280E1CEB} + RTOSDemo + 10.0 + + + + Application + false + MultiByte + v142 + + + Application + false + MultiByte + v142 + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + .\Debug\ + .\Debug\ + true + .\Release\ + .\Release\ + false + AllRules.ruleset + + + + .\Debug/WIN32.tlb + + + + + Disabled + ..\..\..\Source\FreeRTOS-Plus-Trace\Include;..\..\..\FreeRTOS-Plus\Source\FreeRTOS-Plus-TCP\include;..\..\..\FreeRTOS-Plus\Source\FreeRTOS-Plus-TCP\portable\BufferManagement;..\..\..\FreeRTOS-Plus\Source\FreeRTOS-Plus-TCP\portable\Compiler\MSVC;..\..\..\FreeRTOS-Plus\Source\Utilities\logging;..\Common\WinPCap;..\..\..\FreeRTOS\Source\include;..\..\..\FreeRTOS\Source\portable\MSVC-MingW;..\..\Source\Application-Protocols\coreSNTP\source\include;.;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;_WIN32_WINNT=0x0500;WINVER=0x400;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDLL + .\Debug/WIN32.pch + .\Debug/ + .\Debug/ + .\Debug/ + Level4 + true + false + EditAndContinue + /wd4210 /wd4127 /wd4214 /wd4201 /wd4244 /wd4310 /wd4200 %(AdditionalOptions) + true + NotUsing + false + CompileAsC + + + _DEBUG;%(PreprocessorDefinitions) + 0x0c09 + + + .\Debug/RTOSDemo.exe + true + true + .\Debug/WIN32.pdb + Console + MachineX86 + wpcap.lib;%(AdditionalDependencies) + ..\Common\WinPCap + false + false + + + true + .\Debug/WIN32.bsc + + + + + .\Release/WIN32.tlb + + + + + MaxSpeed + OnlyExplicitInline + _WINSOCKAPI_;WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + MultiThreaded + true + .\Release/WIN32.pch + .\Release/ + .\Release/ + .\Release/ + Level3 + true + ..\Common\Utils;..\Common\ethernet\lwip-1.4.0\ports\win32\WinPCap;..\Common\ethernet\lwip-1.4.0\src\include\ipv4;..\Common\ethernet\lwip-1.4.0\src\include;..\..\Source\include;..\..\Source\portable\MSVC-MingW;..\Common\ethernet\lwip-1.4.0\ports\win32\include;..\Common\Include;.\lwIP_Apps;.;%(AdditionalIncludeDirectories) + + + NDEBUG;%(PreprocessorDefinitions) + 0x0c09 + + + .\Release/RTOSDemo.exe + true + .\Release/WIN32.pdb + Console + MachineX86 + ..\Common\ethernet\lwip-1.4.0\ports\win32\WinPCap + wpcap.lib;%(AdditionalDependencies) + + + true + .\Release/WIN32.bsc + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/WIN32.vcxproj.filters b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/WIN32.vcxproj.filters new file mode 100644 index 0000000000..1e7f6386e8 --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/WIN32.vcxproj.filters @@ -0,0 +1,247 @@ + + + + + {af3445a1-4908-4170-89ed-39345d90d30c} + + + {f32be356-4763-4cae-9020-974a2638cb08} + *.c + + + {88f409e6-d396-4ac5-94bd-7a99c914be46} + + + {e5ad4ec7-23dc-4295-8add-2acaee488f5a} + + + {d2dcd641-8d91-492b-852f-5563ffadaec6} + + + {8672fa26-b119-481f-8b8d-086419c01a3e} + + + {4570be11-ec96-4b55-ac58-24b50ada980a} + + + {5d93ed51-023a-41ad-9243-8d230165d34b} + + + {b71e974a-9f28-4815-972b-d930ba8a34d0} + + + {60717407-397f-4ea5-8492-3314acdd25f0} + + + {8a90222f-d723-4b4e-8e6e-c57afaf7fa92} + + + {2d17d5e6-ed70-4e42-9693-f7a63baf4948} + + + {6ad56e6d-c330-4830-8f4b-c75b05dfa866} + + + {84613aa2-91dc-4e1a-a3b3-823b6d7bf0e0} + + + {70524181-23e5-4dde-a3fb-6afc11d6df04} + + + {6e7ee4cd-b54c-4f67-9b70-8c1e9fe80b92} + + + {59d75faa-e4df-4d85-bf56-67e9cc801004} + + + {212f58ea-e09c-4778-9935-31b4e95538ee} + + + {2e22b7fe-a180-47a1-b459-6a3451c7a4ee} + + + {1407130d-da4c-4bcc-8ca0-4cf77f4cf97f} + + + + + FreeRTOS\Source\Portable + + + FreeRTOS\Source + + + FreeRTOS\Source + + + FreeRTOS\Source + + + FreeRTOS\Source + + + FreeRTOS+\FreeRTOS+TCP + + + FreeRTOS+\FreeRTOS+TCP + + + FreeRTOS+\FreeRTOS+TCP + + + FreeRTOS+\FreeRTOS+TCP + + + FreeRTOS+\FreeRTOS+TCP\portable + + + FreeRTOS+\FreeRTOS+TCP\portable + + + FreeRTOS+\FreeRTOS+TCP + + + FreeRTOS+\FreeRTOS+TCP + + + FreeRTOS+\FreeRTOS+TCP + + + FreeRTOS+\FreeRTOS+TCP + + + FreeRTOS\Source + + + FreeRTOS\Source\Portable + + + FreeRTOS+\FreeRTOS+TCP + + + FreeRTOS\Source + + + + + + DemoTasks + + + FreeRTOS+\FreeRTOS IoT Libraries\standard\coreSNTP + + + FreeRTOS+\FreeRTOS IoT Libraries\standard\coreSNTP + + + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS\Source\include + + + FreeRTOS\Source\include + + + FreeRTOS\Source\include + + + FreeRTOS\Source\include + + + FreeRTOS\Source\include + + + FreeRTOS\Source\include + + + FreeRTOS\Source\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS\Source\include + + + FreeRTOS\Source\include + + + FreeRTOS+\FreeRTOS IoT Libraries\standard\coreSNTP\include + + + FreeRTOS+\FreeRTOS IoT Libraries\standard\coreSNTP\include + + + FreeRTOS+\FreeRTOS+TCP\include + + + FreeRTOS+\FreeRTOS IoT Libraries\standard\coreSNTP\include + + + FreeRTOS+\FreeRTOS IoT Libraries\platform\backoff_algorithm\include + + + FreeRTOS+\FreeRTOS IoT Libraries\platform\logging + + + FreeRTOS+\FreeRTOS IoT Libraries\platform\logging + + + FreeRTOS+\FreeRTOS IoT Libraries\platform\logging + + + Config + + + Config + + + Config + + + Config + + + Config + + + \ No newline at end of file diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/common_demo_include.h b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/common_demo_include.h new file mode 100755 index 0000000000..cfcae950fc --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/common_demo_include.h @@ -0,0 +1,98 @@ +/* + * FreeRTOS V202104.00 + * Copyright (C) 2020 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://www.FreeRTOS.org + * http://aws.amazon.com/freertos + */ +#ifndef COMMON_DEMO_INCLUDE_H +#define COMMON_DEMO_INCLUDE_H + +#include "demo_config.h" + +/** + * @brief Utility macro to convert milliseconds to the fractions value of an SNTP timestamp. + * @note The fractions value MUST be less than 1000 as duration of seconds is not represented + * as fractions part of SNTP timestamp. + */ +#define MILLISECONDS_TO_SNTP_FRACTIONS( ms ) ( ms * 1000 * SNTP_FRACTION_VALUE_PER_MICROSECOND ) + +/** + * @brief Type representing system time in Coordinated Universal Time (UTC) + * zone as time since 1st January 1970 00h:00m:00s. + * + * @note This demo uses RAM-based mathematical model to represent UTC time + * in system. + */ +typedef struct UTCTime +{ + uint32_t secs; + uint32_t msecs; +} UTCTime_t; + +/** + * @brief Utility function to print the system time as both UNIX time (i.e. + * time since 1st January 1970 00h:00m:00s) and human-readable time (in the + * YYYY-MM-DD dd:mm:ss format). + * + * @param[in] pTime The system time to be printed. + */ +void printTime( const UTCTime_t * pTime ); + +/** + * @brief Initializes the system clock with the first second of the year (i.e. at midnight + * of 1st January) that is configured in the democonfigSYSTEM_START_YEAR config of + * demo_config.h file. + */ +void initializeSystemClock( void ); + +/** + * @brief The demo function for an application to query wall-clock + * time as Coordinated Universal Time (UTC) from the system. + * + * @note This demo showcases a RAM-based mathematical model for + * representing current UTC time in the system. + * + * @param[out] pTime This will be populated with the current time + * in the system as total time since 1st January 1900 00h:00m:00s. + */ +void systemGetWallClockTime( UTCTime_t * pTime ); + +/** + * @brief The task function for a sample application that queries + * system time periodically. + */ +void sampleAppTask( void * pvParameters ); + +/** + * @brief The task function that represents a daemon SNTP client task + * that is responsible for periodically synchronizing system time with + * time servers from the list of configured time servers in + * democonfigLIST_OF_TIME_SERVERS. + * + * @note The usage of the coreSNTP library API is encapsulated within + * this task. The rest of the FreeRTOS tasks/application does not need + * to be aware of the SNTP client as they can query time from the + * @ref systemGetWallClockTime() function. + */ +void sntpTask( void * parameters ); + + +#endif /* ifndef COMMON_DEMO_INCLUDE_H */ diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/core_sntp_config.h b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/core_sntp_config.h new file mode 100755 index 0000000000..40f9e15ecc --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/core_sntp_config.h @@ -0,0 +1,66 @@ +/* + * FreeRTOS V202104.00 + * Copyright (C) 2020 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://www.FreeRTOS.org + * http://aws.amazon.com/freertos + */ +#ifndef CORE_SNTP_CONFIG_H +#define CORE_SNTP_CONFIG_H + +/**************************************************/ +/******* DO NOT CHANGE the following order ********/ +/**************************************************/ + +/* Include logging header files and define logging macros in the following order: + * 1. Include the header file "logging_levels.h". + * 2. Define the LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL macros depending on + * the logging configuration for SNTP. + * 3. Include the header file "logging_stack.h", if logging is enabled for SNTP. + */ + +#include "logging_levels.h" + +/* Logging configuration for the SNTP library. */ +#ifndef LIBRARY_LOG_NAME + #define LIBRARY_LOG_NAME "SNTP" +#endif + +#ifndef LIBRARY_LOG_LEVEL + #define LIBRARY_LOG_LEVEL LOG_ERROR +#endif + +/* Prototype for the function used to print to console on Windows simulator + * of FreeRTOS. + * The function prints to the console before the network is connected; + * then a UDP port after the network has connected. */ +extern void vLoggingPrintf( const char * pcFormatString, + ... ); + +/* Map the SdkLog macro to the logging function to enable logging + * on Windows simulator. */ +#ifndef SdkLog + #define SdkLog( message ) vLoggingPrintf message +#endif + +#include "logging_stack.h" +/************ End of logging configuration ****************/ + +#endif /* ifndef CORE_SNTP_CONFIG_H */ diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/core_sntp_demo.sln b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/core_sntp_demo.sln new file mode 100644 index 0000000000..dcfc1fe098 --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/core_sntp_demo.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29215.179 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RTOSDemo", "WIN32.vcxproj", "{C686325E-3261-42F7-AEB1-DDE5280E1CEB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C686325E-3261-42F7-AEB1-DDE5280E1CEB}.Debug|Win32.ActiveCfg = Debug|Win32 + {C686325E-3261-42F7-AEB1-DDE5280E1CEB}.Debug|Win32.Build.0 = Debug|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {150F08BF-9D61-4CC2-8DBF-1335172A1EA4} + EndGlobalSection + GlobalSection(TestCaseManagementSettings) = postSolution + CategoryFile = FreeRTOS_Plus_TCP_Minimal.vsmdi + EndGlobalSection +EndGlobal diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/demo_config.h b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/demo_config.h new file mode 100755 index 0000000000..75fbd1418d --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/demo_config.h @@ -0,0 +1,128 @@ +/* + * FreeRTOS V202104.00 + * Copyright (C) 2020 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://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef DEMO_CONFIG_H +#define DEMO_CONFIG_H + +/**************************************************/ +/******* DO NOT CHANGE the following order ********/ +/**************************************************/ + +/* Include logging header files and define logging macros in the following order: + * 1. Include the header file "logging_levels.h". + * 2. Define the LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL macros depending on + * the logging configuration for DEMO. + * 3. Include the header file "logging_stack.h", if logging is enabled for DEMO. + */ + +#include "logging_levels.h" + +/* Logging configuration for the Demo. */ +#ifndef LIBRARY_LOG_NAME + #define LIBRARY_LOG_NAME "SNTPDemo" +#endif + +#ifndef LIBRARY_LOG_LEVEL + #define LIBRARY_LOG_LEVEL LOG_INFO +#endif + +/* Prototype for the function used to print to console on Windows simulator + * of FreeRTOS. + * The function prints to the console before the network is connected; + * then a UDP port after the network has connected. */ +extern void vLoggingPrintf( const char * pcFormatString, + ... ); + +/* Map the SdkLog macro to the logging function to enable logging + * on Windows simulator. */ +#ifndef SdkLog + #define SdkLog( message ) vLoggingPrintf message +#endif + +#include "logging_stack.h" + +/************ End of logging configuration ****************/ + +/** + * @brief The desired accuracy (in milliseconds) of system clock in relation with internet time. + * In other words, this is the maximum tolerance desired for clock drift in the system. + */ +#define democonfigDESIRED_CLOCK_ACCURACY_MS ( 1000 ) + +/** + * @brief The system clock tolerance (in parts per million) that represents the rate of clock + * drift of the system. The rate can be viewed as the system clock drift that occurs as milliseconds + * per second. + * + * @note In systems with a HW oscillator based clock, the frequency tolerance can be obtained from the + * hardware specification of the clock oscillator. + * @note This demo DOES NOT use a hardware clock oscillator as it runs on Windows Simulator. The configuration + * ONLY provides the user to view the impact of the settings for "Clock Tolerance" and "Desired + * Clock Accuracy" configurations on the calculated "SNTP polling period". + */ +#define democonfigSYSTEM_CLOCK_TOLERANCE_PPM ( 32000 ) + +/** + * @brief The set of time servers, in decreasing order of priority, for configuring the SNTP client. + * The servers SHOULD be listed as comma-separated list of strings. For example, the following + * can be a configuration used: + */ +#define democonfigLIST_OF_TIME_SERVERS "time.cloudflare.com", "pool.ntp.org" + +/** + * @brief The year to bake in the demo application for initializing the system clock with. + * The demo initializes the system clock time for the starting second of the 1st January of + * the configured year. So for example, with a configuration of year 2021, the demo will + * initialize the system clock time as 1st January 2021 00h:00m:00s. + * + * @note The coreSNTP library REQUIRES that the client system time is within ~68 years of internet + * time. Thus, for systems that do not have an Real-Time Clock module, this demo shows how + * a starting time can be baked in the device firmware to keep the starting time of the system + * close to actual time on the first boot-up of device. + * For such systems without Real-Time Clock module, all device boot ups from subsequent device resets + * or power cycles can continue to carry close to correct time by EITHER + * * (RECOMMENDED) Saving the most recent time in non-volatile memory + * OR + * * Using the same firmware baked-in starting time of device for every boot-up. + */ +#define democonfigSYSTEM_START_YEAR ( 2021 ) + +/** + * @brief The timeout (in milliseconds) for the time response to a time request made to a + * time server. + */ +#define democonfigSERVER_RESPONSE_TIMEOUT_MS ( 5000 ) + +/** + * @brief Set the stack size of the main demo task. + * + * In the Windows port, this stack only holds a structure. The actual + * stack is created by an operating system thread. + */ +#define democonfigDEMO_STACKSIZE configMINIMAL_STACK_SIZE + +#endif /* DEMO_CONFIG_H */ diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/main.c b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/main.c new file mode 100755 index 0000000000..7a8a666e05 --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/main.c @@ -0,0 +1,412 @@ +/* + * FreeRTOS V202104.00 + * Copyright (C) 2020 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. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/*** + * See https://www.FreeRTOS.org/coresntp for configuration and usage instructions, + ***/ + +/* Standard includes. */ +#include +#include + +/* Visual studio intrinsics used so the __debugbreak() function is available + * should an assert get hit. */ +#include + +/* FreeRTOS includes. */ +#include +#include "task.h" + +/* TCP/IP stack includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" + +/* Demo logging includes. */ +#include "logging.h" + +/* Demo Specific configs. */ +#include "demo_config.h" +#include "common_demo_include.h" + +/* + * Prototypes for the demos that can be started from this project. Note the + * SNTP demo is not actually started until the network is already, which is + * indicated by vApplicationIPNetworkEventHook() executing - hence + * prvStartSimpleSNTPDemo() is called from inside vApplicationIPNetworkEventHook(). + */ +static void vStartSntpDemo( void ); + +/* + * Just seeds the simple pseudo random number generator. + * + * !!! NOTE !!! + * This is not a secure method of generating random numbers and production + * devices should use a true random number generator (TRNG). + */ +static void prvSRand( UBaseType_t ulSeed ); + +/* + * Miscellaneous initialization including preparing the logging and seeding the + * random number generator. + */ +static void prvMiscInitialisation( void ); + +/* The default IP and MAC address used by the demo. The address configuration + * defined here will be used if ipconfigUSE_DHCP is 0, or if ipconfigUSE_DHCP is + * 1 but a DHCP server could not be contacted. See the online documentation for + * more information. */ +static const uint8_t ucIPAddress[ 4 ] = { configIP_ADDR0, configIP_ADDR1, configIP_ADDR2, configIP_ADDR3 }; +static const uint8_t ucNetMask[ 4 ] = { configNET_MASK0, configNET_MASK1, configNET_MASK2, configNET_MASK3 }; +static const uint8_t ucGatewayAddress[ 4 ] = { configGATEWAY_ADDR0, configGATEWAY_ADDR1, configGATEWAY_ADDR2, configGATEWAY_ADDR3 }; +static const uint8_t ucDNSServerAddress[ 4 ] = { configDNS_SERVER_ADDR0, configDNS_SERVER_ADDR1, configDNS_SERVER_ADDR2, configDNS_SERVER_ADDR3 }; + +/* Set the following constant to pdTRUE to log using the method indicated by the + * name of the constant, or pdFALSE to not log using the method indicated by the + * name of the constant. Options include to standard out (xLogToStdout), to a disk + * file (xLogToFile), and to a UDP port (xLogToUDP). If xLogToUDP is set to pdTRUE + * then UDP messages are sent to the IP address configured as the UDP logging server + * address (see the configUDP_LOGGING_ADDR0 definitions in FreeRTOSConfig.h) and + * the port number set by configPRINT_PORT in FreeRTOSConfig.h. */ +const BaseType_t xLogToStdout = pdTRUE, xLogToFile = pdFALSE, xLogToUDP = pdFALSE; + +/* Default MAC address configuration. The demo creates a virtual network + * connection that uses this MAC address by accessing the raw Ethernet data + * to and from a real network connection on the host PC. See the + * configNETWORK_INTERFACE_TO_USE definition for information on how to configure + * the real network connection to use. */ +const uint8_t ucMACAddress[ 6 ] = { configMAC_ADDR0, configMAC_ADDR1, configMAC_ADDR2, configMAC_ADDR3, configMAC_ADDR4, configMAC_ADDR5 }; + +/* Use by the pseudo random number generator. */ +static UBaseType_t ulNextRand; +/*-----------------------------------------------------------*/ + +int main( void ) +{ + /*** + * See https://www.FreeRTOS.org/coresntp for configuration and usage instructions. + * + ***/ + + /* Miscellaneous initialization including preparing the logging and seeding + * the random number generator. */ + prvMiscInitialisation(); + + /* Initialize the network interface. + * + ***NOTE*** Tasks that use the network are created in the network event hook + * when the network is connected and ready for use (see the implementation of + * vApplicationIPNetworkEventHook() below). The address values passed in here + * are used if ipconfigUSE_DHCP is set to 0, or if ipconfigUSE_DHCP is set to 1 + * but a DHCP server cannot be contacted. */ + FreeRTOS_IPInit( ucIPAddress, ucNetMask, ucGatewayAddress, ucDNSServerAddress, ucMACAddress ); + + /* Start the RTOS scheduler. */ + vTaskStartScheduler(); + + /* If all is well, the scheduler will now be running, and the following + * line will never be reached. If the following line does execute, then + * there was insufficient FreeRTOS heap memory available for the idle and/or + * timer tasks to be created. See the memory management section on the + * FreeRTOS web site for more details (this is standard text that is not + * really applicable to the Win32 simulator port). */ + for( ; ; ) + { + __debugbreak(); + } +} +/*-----------------------------------------------------------*/ + +/** + * @brief Entry point of the demo that creates 2 tasks: + * 1. One task represents the SNTP client that periodically synchronizes system time with + * time from time servers. + * 2. The other task represents a sample application time that queries the system time + * periodically and prints it in human readable form of the YYYY-MM-DD hh:mm:ss. + */ +void vStartSntpDemo( void ) +{ + initializeSystemClock(); + + /* Create the SNTP client task that is responsible for synchronizing system time with the time servers + * periodically. This is created as a high priority task to keep the SNTP client operation unhindered. */ + xTaskCreate( sntpTask, /* Function that implements the task. */ + "SntpClientTask", /* Text name for the task - only used for debugging. */ + democonfigDEMO_STACKSIZE, /* Size of stack (in words, not bytes) to allocate for the task. */ + NULL, /* Task parameter - not used in this case. */ + configMAX_PRIORITIES - 1, /* Task priority, must be between 0 and configMAX_PRIORITIES - 1. */ + NULL ); + + /* Create the task that represents an application needing wall-clock time. */ + xTaskCreate( sampleAppTask, /* Function that implements the task. */ + "SampleAppTask", /* Text name for the task - only used for debugging. */ + democonfigDEMO_STACKSIZE, /* Size of stack (in words, not bytes) to allocate for the task. */ + NULL, /* Task parameter - not used in this case. */ + tskIDLE_PRIORITY, /* Task priority, must be between 0 and configMAX_PRIORITIES - 1. */ + NULL ); /* Used to pass out a handle to the created task - not used in this case. */ +} + +/*-----------------------------------------------------------*/ + +/* Called by FreeRTOS+TCP when the network connects or disconnects. Disconnect + * events are only received if implemented in the MAC driver. */ +void vApplicationIPNetworkEventHook( eIPCallbackEvent_t eNetworkEvent ) +{ + uint32_t ulIPAddress, ulNetMask, ulGatewayAddress, ulDNSServerAddress; + char cBuffer[ 16 ]; + static BaseType_t xTasksAlreadyCreated = pdFALSE; + + /* If the network has just come up...*/ + if( eNetworkEvent == eNetworkUp ) + { + /* Create the tasks that use the IP stack if they have not already been + * created. */ + if( xTasksAlreadyCreated == pdFALSE ) + { + /* Demos that use the network are created after the network is + * up. */ + LogInfo( ( "---------STARTING DEMO---------\r\n" ) ); + vStartSntpDemo(); + xTasksAlreadyCreated = pdTRUE; + } + + /* Print out the network configuration, which may have come from a DHCP + * server. */ + FreeRTOS_GetAddressConfiguration( &ulIPAddress, &ulNetMask, &ulGatewayAddress, &ulDNSServerAddress ); + FreeRTOS_inet_ntoa( ulIPAddress, cBuffer ); + LogInfo( ( "\r\n\r\nIP Address: %s\r\n", cBuffer ) ); + + FreeRTOS_inet_ntoa( ulNetMask, cBuffer ); + LogInfo( ( "Subnet Mask: %s\r\n", cBuffer ) ); + + FreeRTOS_inet_ntoa( ulGatewayAddress, cBuffer ); + LogInfo( ( "Gateway Address: %s\r\n", cBuffer ) ); + + FreeRTOS_inet_ntoa( ulDNSServerAddress, cBuffer ); + LogInfo( ( "DNS Server Address: %s\r\n\r\n\r\n", cBuffer ) ); + } +} +/*-----------------------------------------------------------*/ + +void vAssertCalled( const char * pcFile, + uint32_t ulLine ) +{ + volatile uint32_t ulBlockVariable = 0UL; + volatile char * pcFileName = ( volatile char * ) pcFile; + volatile uint32_t ulLineNumber = ulLine; + + ( void ) pcFileName; + ( void ) ulLineNumber; + + printf( "vAssertCalled( %s, %u\n", pcFile, ulLine ); + + /* Setting ulBlockVariable to a non-zero value in the debugger will allow + * this function to be exited. */ + taskDISABLE_INTERRUPTS(); + { + while( ulBlockVariable == 0UL ) + { + __debugbreak(); + } + } + taskENABLE_INTERRUPTS(); +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxRand( void ) +{ + const uint32_t ulMultiplier = 0x015a4e35UL, ulIncrement = 1UL; + + /* + * Utility function to generate a pseudo random number. + * + * !!!NOTE!!! + * This is not a secure method of generating a random number. Production + * devices should use a True Random Number Generator (TRNG). + */ + ulNextRand = ( ulMultiplier * ulNextRand ) + ulIncrement; + return( ( int ) ( ulNextRand >> 16UL ) & 0x7fffUL ); +} +/*-----------------------------------------------------------*/ + +static void prvSRand( UBaseType_t ulSeed ) +{ + /* Utility function to seed the pseudo random number generator. */ + ulNextRand = ulSeed; +} +/*-----------------------------------------------------------*/ + +static void prvMiscInitialisation( void ) +{ + time_t xTimeNow; + uint32_t ulLoggingIPAddress; + + ulLoggingIPAddress = FreeRTOS_inet_addr_quick( configUDP_LOGGING_ADDR0, configUDP_LOGGING_ADDR1, configUDP_LOGGING_ADDR2, configUDP_LOGGING_ADDR3 ); + vLoggingInit( xLogToStdout, xLogToFile, xLogToUDP, ulLoggingIPAddress, configPRINT_PORT ); + + /* + * Seed random number generator. + * + * !!!NOTE!!! + * This is not a secure method of generating a random number. Production + * devices should use a True Random Number Generator (TRNG). + */ + time( &xTimeNow ); + LogDebug( ( "Seed for randomizer: %lu\n", xTimeNow ) ); + prvSRand( ( uint32_t ) xTimeNow ); + LogDebug( ( "Random numbers: %08X %08X %08X %08X\n", ipconfigRAND32(), ipconfigRAND32(), ipconfigRAND32(), ipconfigRAND32() ) ); +} +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_LLMNR != 0 ) || ( ipconfigUSE_NBNS != 0 ) || ( ipconfigDHCP_REGISTER_HOSTNAME == 1 ) + + const char * pcApplicationHostnameHook( void ) + { + /* Assign the name "FreeRTOS" to this network node. This function will + * be called during the DHCP: the machine will be registered with an IP + * address plus this name. */ + return mainHOST_NAME; + } + +#endif +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_LLMNR != 0 ) || ( ipconfigUSE_NBNS != 0 ) + + BaseType_t xApplicationDNSQueryHook( const char * pcName ) + { + BaseType_t xReturn; + + /* Determine if a name lookup is for this node. Two names are given + * to this node: that returned by pcApplicationHostnameHook() and that set + * by mainDEVICE_NICK_NAME. */ + if( _stricmp( pcName, pcApplicationHostnameHook() ) == 0 ) + { + xReturn = pdPASS; + } + else if( _stricmp( pcName, mainDEVICE_NICK_NAME ) == 0 ) + { + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + + return xReturn; + } + +#endif /* if ( ipconfigUSE_LLMNR != 0 ) || ( ipconfigUSE_NBNS != 0 ) */ +/*-----------------------------------------------------------*/ + +/* + * Callback that provides the inputs necessary to generate a randomized TCP + * Initial Sequence Number per RFC 6528. THIS IS ONLY A DUMMY IMPLEMENTATION + * THAT RETURNS A PSEUDO RANDOM NUMBER SO IS NOT INTENDED FOR USE IN PRODUCTION + * SYSTEMS. + */ +extern uint32_t ulApplicationGetNextSequenceNumber( uint32_t ulSourceAddress, + uint16_t usSourcePort, + uint32_t ulDestinationAddress, + uint16_t usDestinationPort ) +{ + ( void ) ulSourceAddress; + ( void ) usSourcePort; + ( void ) ulDestinationAddress; + ( void ) usDestinationPort; + + return uxRand(); +} +/*-----------------------------------------------------------*/ + +/* + * Set *pulNumber to a random number, and return pdTRUE. When the random number + * generator is broken, it shall return pdFALSE. + * The macros ipconfigRAND32() and configRAND32() are not in use + * anymore in FreeRTOS+TCP. + * + * THIS IS ONLY A DUMMY IMPLEMENTATION THAT RETURNS A PSEUDO RANDOM NUMBER SO IS + * NOT INTENDED FOR USE IN PRODUCTION SYSTEMS. + */ +BaseType_t xApplicationGetRandomNumber( uint32_t * pulNumber ) +{ + *pulNumber = uxRand(); + return pdTRUE; +} +/*-----------------------------------------------------------*/ + +/* configUSE_STATIC_ALLOCATION is set to 1, so the application must provide an + * implementation of vApplicationGetIdleTaskMemory() to provide the memory that is + * used by the Idle task. */ +void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, + StackType_t ** ppxIdleTaskStackBuffer, + uint32_t * pulIdleTaskStackSize ) +{ + /* If the buffers to be provided to the Idle task are declared inside this + * function then they must be declared static - otherwise they will be allocated on + * the stack and so not exists after this function exits. */ + static StaticTask_t xIdleTaskTCB; + static StackType_t uxIdleTaskStack[ configMINIMAL_STACK_SIZE ]; + + /* Pass out a pointer to the StaticTask_t structure in which the Idle task's + * state will be stored. */ + *ppxIdleTaskTCBBuffer = &xIdleTaskTCB; + + /* Pass out the array that will be used as the Idle task's stack. */ + *ppxIdleTaskStackBuffer = uxIdleTaskStack; + + /* Pass out the size of the array pointed to by *ppxIdleTaskStackBuffer. + * Note that, as the array is necessarily of type StackType_t, + * configMINIMAL_STACK_SIZE is specified in words, not bytes. */ + *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE; +} +/*-----------------------------------------------------------*/ + +/* configUSE_STATIC_ALLOCATION and configUSE_TIMERS are both set to 1, so the + * application must provide an implementation of vApplicationGetTimerTaskMemory() + * to provide the memory that is used by the Timer service task. */ +void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer, + StackType_t ** ppxTimerTaskStackBuffer, + uint32_t * pulTimerTaskStackSize ) +{ + /* If the buffers to be provided to the Timer task are declared inside this + * function then they must be declared static - otherwise they will be allocated on + * the stack and so not exists after this function exits. */ + static StaticTask_t xTimerTaskTCB; + static StackType_t uxTimerTaskStack[ configTIMER_TASK_STACK_DEPTH ]; + + /* Pass out a pointer to the StaticTask_t structure in which the Timer + * task's state will be stored. */ + *ppxTimerTaskTCBBuffer = &xTimerTaskTCB; + + /* Pass out the array that will be used as the Timer task's stack. */ + *ppxTimerTaskStackBuffer = uxTimerTaskStack; + + /* Pass out the size of the array pointed to by *ppxTimerTaskStackBuffer. + * Note that, as the array is necessarily of type StackType_t, + * configMINIMAL_STACK_SIZE is specified in words, not bytes. */ + *pulTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH; +} +/*-----------------------------------------------------------*/ diff --git a/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/readme.url b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/readme.url new file mode 100644 index 0000000000..44ba477139 --- /dev/null +++ b/FreeRTOS-Plus/Demo/coreSNTP_Windows_Simulator/readme.url @@ -0,0 +1,5 @@ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,11 +[InternetShortcut] +IDList= +URL=https://www.freertos.org/sntp/sntp-demo.html diff --git a/FreeRTOS-Plus/Source/Application-Protocols/coreSNTP b/FreeRTOS-Plus/Source/Application-Protocols/coreSNTP new file mode 160000 index 0000000000..cbf2696387 --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/coreSNTP @@ -0,0 +1 @@ +Subproject commit cbf2696387a91267427c30554140fd5cead2f3dd diff --git a/lexicon.txt b/lexicon.txt index 3e3a63f623..cb69f36f59 100644 --- a/lexicon.txt +++ b/lexicon.txt @@ -71,6 +71,7 @@ backoffalgorithm balternatesetting baltimore barry +basetime basetype bauddiv baudrate @@ -158,6 +159,10 @@ burtcmodeem busfault buttonisr bvic +bytesreceived +bytesreceived +bytessent +bytessent bytestorecv bytestosend bytestring @@ -365,6 +370,7 @@ copybrief corehttp coremqtt corepkcs +coresntp coretasks corextend correctl @@ -677,6 +683,7 @@ fcs fd fde fe +february fec ferr ff @@ -807,6 +814,7 @@ hetreg hfclk hfrco hfxo +hh hidef hifive hkdf @@ -955,6 +963,7 @@ iproduct iram irda iret +ireturned irom irq irqchannelpreemptionpriority @@ -980,6 +989,8 @@ itm itteratio itu ivr +jan +january javascript jefferson jitp @@ -1005,6 +1016,7 @@ kickstart knowns kx lapic +lastsynctickcount latestversion lathclr lathinv @@ -1308,6 +1320,7 @@ nullptr num numaker numberofitems +numofservers nvic nvs ocd @@ -1385,6 +1398,7 @@ pasv pathlen payloadlength pb +pbasetime pbclk pbuf pbuffer @@ -1439,6 +1453,7 @@ pcnewdir pcommandtorelease pcommandtosend pcontext +pcontextbuffer pcoverflowedtask pcpath pcpayload @@ -1465,6 +1480,7 @@ pctransmittedstring pctxbuffer pcurl pcurldata +pcurrenttime pcwritebuffer pd pdata @@ -1759,6 +1775,7 @@ prvsimplezerocopyudpclienttask prvsingletasktests prvskipnamefield prvstartsimplemqttdemo +prvstartsimplesntpdemo prvstartstoptracecommand prvstatcommand prvstatfscommand @@ -1810,6 +1827,9 @@ ptal ptcpsocket pth pthingname +ptime +ptimeserver +ptimeservers ptm ptopicfilter ptp @@ -1843,6 +1863,7 @@ pucstreambufferstoragearea pucstring puctxbuffer pucudppayloadbuffer +pudpcontext pul pulcount puldigestlen @@ -2050,6 +2071,7 @@ rng rnto ro robotronics +rollover rom rootca rootcasize @@ -2097,6 +2119,8 @@ safertos sam sama samd +sampleapp +sampleapptask santity sarecomtesttasksstillrunning saveall @@ -2141,7 +2165,9 @@ serinterrupt serput sersource sertx +serveraddr serverhost +serverport setbaudratevalue setfaketaskpriority setimagestate @@ -2177,6 +2203,7 @@ simultaniously singletasks sizeof sk +slewrate slibxr smc smclk @@ -2185,6 +2212,9 @@ smt snextcheckvariable sni snprintf +sntp +sntpclienttask +sntptask soc sockaddr socketauto @@ -2201,6 +2231,7 @@ sr sram src sren +ss sscanf ssi ssitask @@ -2268,6 +2299,7 @@ sysclk sysinit syst systemcoreclock +systemgetwallclocktime systeminit systeminithook systemirqhandler @@ -2625,6 +2657,7 @@ usthingnamelength ustopicfilterlength ustotallength utalised +utc utest util utilise @@ -3316,7 +3349,8 @@ xyieldpending xyieldrequired yrdkrl yrpbrl +yyyy yyyymmddhhmmss zc zer -zynq +zynq \ No newline at end of file diff --git a/manifest.yml b/manifest.yml index 5a7429a5f6..c12563cbc2 100644 --- a/manifest.yml +++ b/manifest.yml @@ -101,4 +101,11 @@ dependencies: url: "https://github.com/aws/ota-for-aws-iot-embedded-sdk" path: "FreeRTOS-Plus/Source/AWS/ota" + - name: "coreSNTP" + version: "v1.0.0" + repository: + type: "git" + url: "https://github.com/FreeRTOS/coreSNTP" + path: "FreeRTOS-Plus/Source/Application-Protocols/coreSNTP" + license: "MIT"