[修改] 增加freeRTOS

1. 版本FreeRTOSv202212.01,命名为kernel;
This commit is contained in:
2023-05-06 16:43:01 +00:00
commit a345df017b
20944 changed files with 11094377 additions and 0 deletions

8
kernel/.editorconfig Normal file
View File

@ -0,0 +1,8 @@
root = true
[*]
indent_style = space
indent_size = 4
[{Makefile,**.mk,Makefile.in}]
indent_style = tab

5
kernel/FreeRTOS+TCP.url Normal file
View File

@ -0,0 +1,5 @@
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
[InternetShortcut]
URL=http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/index.html
IDList=

1
kernel/FreeRTOS-Plus/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.vcxproj.user

View File

@ -0,0 +1,952 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/*
* Demo for showing how to use the Device Defender library's APIs. The Device
* Defender library provides macros and helper functions for assembling MQTT
* topics strings, and for determining whether an incoming MQTT message is
* related to Device Defender. The Device Defender library does not depend on
* any particular MQTT library, therefore the code for MQTT operations is
* placed in another file (mqtt_demo_helpers.c). This demo uses the coreMQTT
* library. If needed, mqtt_demo_helpers.c can be modified to replace coreMQTT
* with another MQTT library. This demo requires using the AWS IoT broker as
* Device Defender is an AWS service.
*
* This demo subscribes to the Device Defender topics. It then collects metrics
* for the open ports and sockets on the device using FreeRTOS+TCP. Additionally
* the stack high water mark and task IDs are collected for custom metrics.
* These metrics are used to generate a Device Defender report. The
* report is then published, and the demo waits for a response from the device
* defender service. Upon receiving an accepted response, the demo finishes.
* If the demo receives a rejected response or times out, the demo repeats up to
* a maximum of DEFENDER_MAX_DEMO_LOOP_COUNT times.
*
* This demo sets the report ID to xTaskGetTickCount(), which may collide if
* the device is reset. Reports for a Thing with a previously used report ID
* will be assumed to be duplicates and discarded by the Device Defender
* service. The report ID needs to be unique per report sent with a given
* Thing. We recommend using an increasing unique ID such as the current
* timestamp.
*/
/* Standard includes. */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
/* Kernel includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Demo config. */
#include "demo_config.h"
/* JSON Library. */
#include "core_json.h"
/* Device Defender Client Library. */
#include "defender.h"
/* MQTT operations. */
#include "mqtt_demo_helpers.h"
/* Metrics collector. */
#include "metrics_collector.h"
/* Report builder. */
#include "report_builder.h"
/**
* democonfigTHING_NAME is required. Throw compilation error if it is not defined.
*/
#ifndef democonfigTHING_NAME
#error "Please define democonfigTHING_NAME to the thing name registered with AWS IoT Core in demo_config.h."
#endif
/**
* @brief The length of #democonfigTHING_NAME.
*/
#define THING_NAME_LENGTH ( ( uint16_t ) ( sizeof( democonfigTHING_NAME ) - 1 ) )
/**
* @brief Number of seconds to wait for the response from AWS IoT Device
* Defender service.
*/
#define DEFENDER_RESPONSE_WAIT_SECONDS ( 2 )
/**
* @brief Name of the report ID field in the response from the AWS IoT Device
* Defender service.
*/
#define DEFENDER_RESPONSE_REPORT_ID_FIELD "reportId"
/**
* @brief The length of #DEFENDER_RESPONSE_REPORT_ID_FIELD.
*/
#define DEFENDER_RESPONSE_REPORT_ID_FIELD_LENGTH ( sizeof( DEFENDER_RESPONSE_REPORT_ID_FIELD ) - 1 )
/**
* @brief The maximum number of times to run the loop in this demo.
*
* @note The demo loop is attempted to re-run only if it fails in an iteration.
* Once the demo loop succeeds in an iteration, the demo exits successfully.
*/
#ifndef DEFENDER_MAX_DEMO_LOOP_COUNT
#define DEFENDER_MAX_DEMO_LOOP_COUNT ( 3 )
#endif
/**
* @brief Time in ticks to wait between retries of the demo loop if
* demo loop fails.
*/
#define DELAY_BETWEEN_DEMO_RETRY_ITERATIONS_TICKS ( pdMS_TO_TICKS( 5000U ) )
/**
* @brief Status values of the Device Defender report.
*/
typedef enum
{
ReportStatusNotReceived,
ReportStatusAccepted,
ReportStatusRejected
} ReportStatus_t;
/**
* @brief Each compilation unit that consumes the NetworkContext must define it.
* It should contain a single pointer to the type of your desired transport.
* When using multiple transports in the same compilation unit, define this pointer as void *.
*
* @note Transport stacks are defined in FreeRTOS-Plus/Source/Application-Protocols/network_transport.
*/
struct NetworkContext
{
TlsTransportParams_t * pParams;
};
/*-----------------------------------------------------------*/
/**
* @brief The MQTT context used for MQTT operation.
*/
static MQTTContext_t xMqttContext;
/**
* @brief The network context used for mbedTLS operation.
*/
static NetworkContext_t xNetworkContext;
/**
* @brief The parameters for the network context using mbedTLS operation.
*/
static TlsTransportParams_t xTlsTransportParams;
/**
* @brief Static buffer used to hold MQTT messages being sent and received.
*/
static uint8_t ucSharedBuffer[ democonfigNETWORK_BUFFER_SIZE ];
/**
* @brief Static buffer used to hold MQTT messages being sent and received.
*/
static MQTTFixedBuffer_t xBuffer =
{
ucSharedBuffer,
democonfigNETWORK_BUFFER_SIZE
};
/**
* @brief Network Stats.
*/
static NetworkStats_t xNetworkStats;
/**
* @brief Open TCP ports array.
*/
static uint16_t pusOpenTcpPorts[ democonfigOPEN_TCP_PORTS_ARRAY_SIZE ];
/**
* @brief Open UDP ports array.
*/
static uint16_t pusOpenUdpPorts[ democonfigOPEN_UDP_PORTS_ARRAY_SIZE ];
/**
* @brief Established connections array.
*/
static Connection_t pxEstablishedConnections[ democonfigESTABLISHED_CONNECTIONS_ARRAY_SIZE ];
/**
* @brief All the metrics sent in the Device Defender report.
*/
static ReportMetrics_t xDeviceMetrics;
/**
* @brief Report status.
*/
static ReportStatus_t xReportStatus;
/**
* @brief Buffer for generating the Device Defender report.
*/
static char pcDeviceMetricsJsonReport[ democonfigDEVICE_METRICS_REPORT_BUFFER_SIZE ];
/**
* @brief Report ID sent in the defender report.
*/
static uint32_t ulReportId = 0UL;
/*-----------------------------------------------------------*/
/**
* @brief Callback to receive the incoming publish messages from the MQTT broker.
*
* @param[in] pxMqttContext The MQTT context for the MQTT connection.
* @param[in] pxPacketInfo Pointer to publish info of the incoming publish.
* @param[in] pxDeserializedInfo Deserialized information from the incoming publish.
*/
static void prvPublishCallback( MQTTContext_t * pxMqttContext,
MQTTPacketInfo_t * pxPacketInfo,
MQTTDeserializedInfo_t * pxDeserializedInfo );
/**
* @brief Collect all the metrics to be sent in the Device Defender report.
*
* On success, caller is responsible for freeing xDeviceMetrics.pxTaskStatusArray.
*
* @return true if all the metrics are successfully collected;
* false otherwise.
*/
static bool prvCollectDeviceMetrics( void );
/**
* @brief Generate the Device Defender report.
*
* @param[out] pxOutReportLength Length of the Device Defender report.
*
* @return true if the report is generated successfully;
* false otherwise.
*/
static bool prvGenerateDeviceMetricsReport( size_t * pxOutReportLength );
/**
* @brief Subscribe to the Device Defender topics.
*
* @return true if the subscribe is successful;
* false otherwise.
*/
static bool prvSubscribeToDefenderTopics( void );
/**
* @brief Unsubscribe from the Device Defender topics.
*
* @return true if the unsubscribe is successful;
* false otherwise.
*/
static bool prvUnsubscribeFromDefenderTopics( void );
/**
* @brief Publish the generated Device Defender report.
*
* @param[in] xReportLength Length of the Device Defender report.
*
* @return true if the report is published successfully;
* false otherwise.
*/
static bool prvPublishDeviceMetricsReport( size_t xReportLength );
/**
* @brief Validate the response received from the AWS IoT Device Defender Service.
*
* This functions checks that a valid JSON is received and the report ID
* is same as was sent in the published report.
*
* @param[in] pcDefenderResponse The defender response to validate.
* @param[in] xDefenderResponseLength Length of the defender response.
*
* @return true if the response is valid;
* false otherwise.
*/
static bool prvValidateDefenderResponse( const char * pcDefenderResponse,
size_t xDefenderResponseLength );
/*-----------------------------------------------------------*/
static bool prvValidateDefenderResponse( const char * pcDefenderResponse,
size_t xDefenderResponseLength )
{
bool xStatus = false;
JSONStatus_t eJsonResult = JSONSuccess;
char * ucReportIdString = NULL;
size_t xReportIdStringLength;
uint32_t ulReportIdInResponse;
configASSERT( pcDefenderResponse != NULL );
/* Is the response a valid JSON? */
eJsonResult = JSON_Validate( pcDefenderResponse, xDefenderResponseLength );
if( eJsonResult != JSONSuccess )
{
LogError( ( "Invalid response from AWS IoT Device Defender Service: %.*s.",
( int ) xDefenderResponseLength,
pcDefenderResponse ) );
}
if( eJsonResult == JSONSuccess )
{
/* Search the ReportId key in the response. */
eJsonResult = JSON_Search( ( char * ) pcDefenderResponse,
xDefenderResponseLength,
DEFENDER_RESPONSE_REPORT_ID_FIELD,
DEFENDER_RESPONSE_REPORT_ID_FIELD_LENGTH,
&( ucReportIdString ),
&( xReportIdStringLength ) );
if( eJsonResult != JSONSuccess )
{
LogError( ( "%s key not found in the response from the"
"AWS IoT Device Defender Service: %.*s.",
DEFENDER_RESPONSE_REPORT_ID_FIELD,
( int ) xDefenderResponseLength,
pcDefenderResponse ) );
}
}
if( eJsonResult == JSONSuccess )
{
ulReportIdInResponse = ( uint32_t ) strtoul( ucReportIdString, NULL, 10 );
/* Is the report ID present in the response same as was sent in the
* published report? */
if( ulReportIdInResponse == ulReportId )
{
LogInfo( ( "A valid response with report ID %u received from the "
"AWS IoT Device Defender Service.", ulReportId ) );
xStatus = true;
}
else
{
LogError( ( "Unexpected %s found in the response from the AWS"
"IoT Device Defender Service. Expected: %u, Found: %u, "
"Complete Response: %.*s.",
DEFENDER_RESPONSE_REPORT_ID_FIELD,
ulReportId,
ulReportIdInResponse,
( int ) xDefenderResponseLength,
pcDefenderResponse ) );
}
}
return xStatus;
}
/*-----------------------------------------------------------*/
static void prvPublishCallback( MQTTContext_t * pxMqttContext,
MQTTPacketInfo_t * pxPacketInfo,
MQTTDeserializedInfo_t * pxDeserializedInfo )
{
DefenderStatus_t xStatus;
DefenderTopic_t xApi;
bool xValidationResult;
MQTTPublishInfo_t * pxPublishInfo;
configASSERT( pxMqttContext != NULL );
configASSERT( pxPacketInfo != NULL );
configASSERT( pxDeserializedInfo != NULL );
/* Suppress the unused parameter warning when asserts are disabled in
* build. */
( void ) pxMqttContext;
/* Handle an incoming publish. The lower 4 bits of the publish packet
* type is used for the dup, QoS, and retain flags. Hence masking
* out the lower bits to check if the packet is publish. */
if( ( pxPacketInfo->type & 0xF0U ) == MQTT_PACKET_TYPE_PUBLISH )
{
configASSERT( pxDeserializedInfo->pPublishInfo != NULL );
pxPublishInfo = pxDeserializedInfo->pPublishInfo;
/* Verify that the publish is for Device Defender, and if so get which
* defender API it is for */
xStatus = Defender_MatchTopic( pxPublishInfo->pTopicName,
pxPublishInfo->topicNameLength,
&( xApi ),
NULL,
NULL );
if( xStatus == DefenderSuccess )
{
if( xApi == DefenderJsonReportAccepted )
{
/* Check if the response is valid and is for the report we
* published. If so, report was accepted. */
xValidationResult = prvValidateDefenderResponse( pxPublishInfo->pPayload,
pxPublishInfo->payloadLength );
if( xValidationResult == true )
{
LogInfo( ( "The defender report was accepted by the service. Response: %.*s.",
( int ) pxPublishInfo->payloadLength,
( const char * ) pxPublishInfo->pPayload ) );
xReportStatus = ReportStatusAccepted;
}
}
else if( xApi == DefenderJsonReportRejected )
{
/* Check if the response is valid and is for the report we
* published. If so, report was rejected. */
xValidationResult = prvValidateDefenderResponse( pxPublishInfo->pPayload,
pxPublishInfo->payloadLength );
if( xValidationResult == true )
{
LogError( ( "The defender report was rejected by the service. Response: %.*s.",
( int ) pxPublishInfo->payloadLength,
( const char * ) pxPublishInfo->pPayload ) );
xReportStatus = ReportStatusRejected;
}
}
else
{
LogError( ( "Unexpected defender API : %d.", xApi ) );
}
}
else
{
LogError( ( "Unexpected publish message received. Topic: %.*s, Payload: %.*s.",
( int ) pxPublishInfo->topicNameLength,
( const char * ) pxPublishInfo->pTopicName,
( int ) pxPublishInfo->payloadLength,
( const char * ) ( pxPublishInfo->pPayload ) ) );
}
}
else
{
vHandleOtherIncomingPacket( pxPacketInfo, pxDeserializedInfo->packetIdentifier );
}
}
/*-----------------------------------------------------------*/
static bool prvCollectDeviceMetrics( void )
{
bool xStatus = false;
eMetricsCollectorStatus eStatus;
size_t uxNumOpenTcpPorts = 0UL;
size_t uxNumOpenUdpPorts = 0UL;
size_t uxNumEstablishedConnections = 0UL;
UBaseType_t uxTasksWritten = { 0 };
UBaseType_t uxNumTasksRunning;
TaskStatus_t pxTaskStatus = { 0 };
TaskStatus_t * pxTaskStatusArray = NULL;
/* Collect bytes and packets sent and received. */
eStatus = eGetNetworkStats( &( xNetworkStats ) );
if( eStatus != eMetricsCollectorSuccess )
{
LogError( ( "xGetNetworkStats failed. Status: %d.",
eStatus ) );
}
/* Collect a list of open TCP ports. */
if( eStatus == eMetricsCollectorSuccess )
{
eStatus = eGetOpenTcpPorts( &( pusOpenTcpPorts[ 0 ] ),
democonfigOPEN_TCP_PORTS_ARRAY_SIZE,
&( uxNumOpenTcpPorts ) );
if( eStatus != eMetricsCollectorSuccess )
{
LogError( ( "xGetOpenTcpPorts failed. Status: %d.",
eStatus ) );
}
}
/* Collect a list of open UDP ports. */
if( eStatus == eMetricsCollectorSuccess )
{
eStatus = eGetOpenUdpPorts( &( pusOpenUdpPorts[ 0 ] ),
democonfigOPEN_UDP_PORTS_ARRAY_SIZE,
&( uxNumOpenUdpPorts ) );
if( eStatus != eMetricsCollectorSuccess )
{
LogError( ( "xGetOpenUdpPorts failed. Status: %d.",
eStatus ) );
}
}
/* Collect a list of established connections. */
if( eStatus == eMetricsCollectorSuccess )
{
eStatus = eGetEstablishedConnections( &( pxEstablishedConnections[ 0 ] ),
democonfigESTABLISHED_CONNECTIONS_ARRAY_SIZE,
&( uxNumEstablishedConnections ) );
if( eStatus != eMetricsCollectorSuccess )
{
LogError( ( "GetEstablishedConnections failed. Status: %d.",
eStatus ) );
}
}
if( eStatus == eMetricsCollectorSuccess )
{
/* Get task count */
uxNumTasksRunning = uxTaskGetNumberOfTasks();
/* Allocate pxTaskStatusArray */
pxTaskStatusArray = pvPortMalloc( uxNumTasksRunning * sizeof( TaskStatus_t ) );
if( pxTaskStatusArray == NULL )
{
LogError( ( "Cannot allocate memory for pxTaskStatusArray: pvPortMalloc() failed." ) );
eStatus = eMetricsCollectorCollectionFailed;
}
}
/* Collect custom metrics. This demo sends this task's stack high water mark
* as a number type custom metric and the current task IDs as a list of
* numbers type custom metric. */
if( eStatus == eMetricsCollectorSuccess )
{
/* Get the current task's status information. The usStackHighWaterMark
* field of the task status will be included in the report as a "number"
* custom metric. */
vTaskGetInfo(
/* Query this task. */
NULL,
&pxTaskStatus,
/* Include the stack high water mark value. */
pdTRUE,
/* Don't include the task state in the TaskStatus_t structure. */
0 );
/* Get the task status information for all running tasks. The task IDs
* of each task is then extracted to include in the report as a "list of
* numbers" custom metric */
uxTasksWritten = uxTaskGetSystemState( pxTaskStatusArray, uxNumTasksRunning, NULL );
if( uxTasksWritten == 0 )
{
/* If 0 is returned, the buffer was too small. This line is reached
* when we hit the race condition where tasks have been added since
* we got the result of uxTaskGetNumberOfTasks() */
eStatus = eMetricsCollectorCollectionFailed;
LogError( ( "Failed to collect system state. uxTaskGetSystemState() failed due to insufficient buffer space.",
eStatus ) );
}
}
/* Populate device metrics. */
if( eStatus == eMetricsCollectorSuccess )
{
xStatus = true;
xDeviceMetrics.pxNetworkStats = &( xNetworkStats );
xDeviceMetrics.pusOpenTcpPortsArray = &( pusOpenTcpPorts[ 0 ] );
xDeviceMetrics.xOpenTcpPortsArrayLength = uxNumOpenTcpPorts;
xDeviceMetrics.pusOpenUdpPortsArray = &( pusOpenUdpPorts[ 0 ] );
xDeviceMetrics.xOpenUdpPortsArrayLength = uxNumOpenUdpPorts;
xDeviceMetrics.pxEstablishedConnectionsArray = &( pxEstablishedConnections[ 0 ] );
xDeviceMetrics.xEstablishedConnectionsArrayLength = uxNumEstablishedConnections;
xDeviceMetrics.ulStackHighWaterMark = pxTaskStatus.usStackHighWaterMark;
xDeviceMetrics.pxTaskStatusArray = pxTaskStatusArray;
xDeviceMetrics.xTaskStatusArrayLength = uxTasksWritten;
}
else
{
/* Free pxTaskStatusArray if we allocated it but did not add it to the
* xDeviceMetrics struct. */
if( pxTaskStatusArray != NULL )
{
vPortFree( pxTaskStatusArray );
}
}
return xStatus;
}
/*-----------------------------------------------------------*/
static bool prvGenerateDeviceMetricsReport( size_t * pxOutReportLength )
{
bool xStatus = false;
eReportBuilderStatus eReportBuilderStatus;
/* Generate the metrics report in the format expected by the AWS IoT Device
* Defender Service. */
eReportBuilderStatus = eGenerateJsonReport( &( pcDeviceMetricsJsonReport[ 0 ] ),
democonfigDEVICE_METRICS_REPORT_BUFFER_SIZE,
&( xDeviceMetrics ),
democonfigDEVICE_METRICS_REPORT_MAJOR_VERSION,
democonfigDEVICE_METRICS_REPORT_MINOR_VERSION,
ulReportId,
pxOutReportLength );
if( eReportBuilderStatus != eReportBuilderSuccess )
{
LogError( ( "GenerateJsonReport failed. Status: %d.",
eReportBuilderStatus ) );
}
else
{
LogDebug( ( "Generated Report: %.*s.",
*pxOutReportLength,
&( pcDeviceMetricsJsonReport[ 0 ] ) ) );
xStatus = true;
}
return xStatus;
}
/*-----------------------------------------------------------*/
static bool prvSubscribeToDefenderTopics( void )
{
bool xStatus = false;
/* Subscribe to defender topic for responses for accepted reports. */
xStatus = xSubscribeToTopic( &xMqttContext,
DEFENDER_API_JSON_ACCEPTED( democonfigTHING_NAME ),
DEFENDER_API_LENGTH_JSON_ACCEPTED( THING_NAME_LENGTH ) );
if( xStatus == false )
{
LogError( ( "Failed to subscribe to defender topic: %.*s.",
DEFENDER_API_LENGTH_JSON_ACCEPTED( THING_NAME_LENGTH ),
DEFENDER_API_JSON_ACCEPTED( democonfigTHING_NAME ) ) );
}
if( xStatus == true )
{
/* Subscribe to defender topic for responses for rejected reports. */
xStatus = xSubscribeToTopic( &xMqttContext,
DEFENDER_API_JSON_REJECTED( democonfigTHING_NAME ),
DEFENDER_API_LENGTH_JSON_REJECTED( THING_NAME_LENGTH ) );
if( xStatus == false )
{
LogError( ( "Failed to subscribe to defender topic: %.*s.",
DEFENDER_API_LENGTH_JSON_REJECTED( THING_NAME_LENGTH ),
DEFENDER_API_JSON_REJECTED( democonfigTHING_NAME ) ) );
}
}
return xStatus;
}
/*-----------------------------------------------------------*/
static bool prvUnsubscribeFromDefenderTopics( void )
{
bool xStatus = false;
/* Unsubscribe from defender accepted topic. */
xStatus = xUnsubscribeFromTopic( &xMqttContext,
DEFENDER_API_JSON_ACCEPTED( democonfigTHING_NAME ),
DEFENDER_API_LENGTH_JSON_ACCEPTED( THING_NAME_LENGTH ) );
if( xStatus == true )
{
/* Unsubscribe from defender rejected topic. */
xStatus = xUnsubscribeFromTopic( &xMqttContext,
DEFENDER_API_JSON_REJECTED( democonfigTHING_NAME ),
DEFENDER_API_LENGTH_JSON_REJECTED( THING_NAME_LENGTH ) );
}
return xStatus;
}
/*-----------------------------------------------------------*/
static bool prvPublishDeviceMetricsReport( size_t xReportLength )
{
return xPublishToTopic( &xMqttContext,
DEFENDER_API_JSON_PUBLISH( democonfigTHING_NAME ),
DEFENDER_API_LENGTH_JSON_PUBLISH( THING_NAME_LENGTH ),
&( pcDeviceMetricsJsonReport[ 0 ] ),
xReportLength );
}
/*-----------------------------------------------------------*/
void prvDefenderDemoTask( void * pvParameters )
{
bool xStatus = false;
BaseType_t xExitStatus = EXIT_FAILURE;
size_t uxReportLength = 0UL;
size_t uxIdx;
bool xMqttSessionEstablished = false;
UBaseType_t uxDemoRunCount = 0UL;
/* Remove compiler warnings about unused parameters. */
( void ) pvParameters;
/* Set the pParams member of the network context with desired transport. */
xNetworkContext.pParams = &xTlsTransportParams;
/* Start with report not received. */
xReportStatus = ReportStatusNotReceived;
/* This demo runs a single loop unless there are failures in the demo execution.
* In case of failures in the demo execution, demo loop will be retried for up to
* DEFENDER_MAX_DEMO_LOOP_COUNT times. */
do
{
LogInfo( ( "---------STARTING DEMO---------\r\n" ) );
if( xPlatformIsNetworkUp() == pdFALSE )
{
LogInfo( ( "Waiting for the network link up event..." ) );
while( xPlatformIsNetworkUp() == pdFALSE )
{
vTaskDelay( pdMS_TO_TICKS( 1000U ) );
}
}
/* Set a report ID to be used.
*
* !!!NOTE!!!
* This demo sets the report ID to xTaskGetTickCount(), which may collide
* if the device is reset. Reports for a Thing with a previously used
* report ID will be assumed to be duplicates and discarded by the Device
* Defender service. The report ID needs to be unique per report sent with
* a given Thing. We recommend using an increasing unique ID such as the
* current timestamp. */
ulReportId = ( uint32_t ) xTaskGetTickCount();
/****************************** Connect. ******************************/
/* Attempts to connect to the AWS IoT MQTT broker over TCP. If the
* connection fails, retries after a timeout. Timeout value will
* exponentially increase until maximum attempts are reached. */
LogInfo( ( "Establishing MQTT session..." ) );
xStatus = xEstablishMqttSession( &xMqttContext,
&xNetworkContext,
&xBuffer,
prvPublishCallback );
if( xStatus != true )
{
LogError( ( "Failed to establish MQTT session." ) );
}
else
{
xMqttSessionEstablished = true;
}
/******************** Subscribe to Defender topics. *******************/
/* Attempt to subscribe to the AWS IoT Device Defender topics.
* Since this demo is using JSON, in prvSubscribeToDefenderTopics() we
* subscribe to the topics to which accepted and rejected responses are
* received from after publishing a JSON report.
*
* This demo uses a constant #democonfigTHING_NAME known at compile time
* therefore we use macros to assemble defender topic strings.
* If the thing name is known at run time, then we could use the API
* #Defender_GetTopic instead.
*
* For example, for the JSON accepted responses topic:
*
* #define TOPIC_BUFFER_LENGTH ( 256U )
*
* // Every device should have a unique thing name registered with AWS IoT Core.
* // This example assumes that the device has a unique serial number which is
* // registered as the thing name with AWS IoT Core.
* const char * pThingName = GetDeviceSerialNumber();
* uint16_t thingNameLength = ( uint16_t )strlen( pThingname );
* char topicBuffer[ TOPIC_BUFFER_LENGTH ] = { 0 };
* uint16_t topicLength = 0;
* DefenderStatus_t status = DefenderSuccess;
*
* status = Defender_GetTopic( &( topicBuffer[ 0 ] ),
* TOPIC_BUFFER_LENGTH,
* pThingName,
* thingNameLength,
* DefenderJsonReportAccepted,
* &( topicLength ) );
*/
if( xStatus == true )
{
LogInfo( ( "Subscribing to defender topics..." ) );
xStatus = prvSubscribeToDefenderTopics();
if( xStatus != true )
{
LogError( ( "Failed to subscribe to defender topics." ) );
}
}
/*********************** Collect device metrics. **********************/
/* We then need to collect the metrics that will be sent to the AWS IoT
* Device Defender service. This demo uses the functions declared in
* in metrics_collector.h to collect network metrics. For this demo, the
* implementation of these functions are in metrics_collector.c and
* collects metrics using tcp_netstat utility for FreeRTOS+TCP. */
if( xStatus == true )
{
LogInfo( ( "Collecting device metrics..." ) );
xStatus = prvCollectDeviceMetrics();
if( xStatus != true )
{
LogError( ( "Failed to collect device metrics." ) );
}
}
/********************** Generate defender report. *********************/
/* The data needs to be incorporated into a JSON formatted report,
* which follows the format expected by the Device Defender service.
* This format is documented here:
* https://docs.aws.amazon.com/iot/latest/developerguide/detect-device-side-metrics.html
*/
if( xStatus == true )
{
LogInfo( ( "Generating Device Defender report..." ) );
xStatus = prvGenerateDeviceMetricsReport( &( uxReportLength ) );
/* Free the allocated array in xDeviceMetrics struct which is not
* used anymore after prvGenerateDeviceMetricsReport(). This code is
* only reached when prvCollectDeviceMetrics succeeded, so
* xDeviceMetrics.pxTaskStatusArray is a valid allocation that needs
* to be freed. */
vPortFree( xDeviceMetrics.pxTaskStatusArray );
if( xStatus != true )
{
LogError( ( "Failed to generate Device Defender report." ) );
}
}
/********************** Publish defender report. **********************/
/* The report is then published to the Device Defender service. This report
* is published to the MQTT topic for publishing JSON reports. As before,
* we use the defender library macros to create the topic string, though
* #Defender_GetTopic could be used if the Thing name is acquired at
* run time */
if( xStatus == true )
{
LogInfo( ( "Publishing Device Defender report..." ) );
xStatus = prvPublishDeviceMetricsReport( uxReportLength );
if( xStatus != true )
{
LogError( ( "Failed to publish Device Defender report." ) );
}
}
/* Wait for the response to our report. Response will be handled by the
* callback passed to xEstablishMqttSession() earlier.
* The callback will verify that the MQTT messages received are from the
* defender service's topic. Based on whether the response comes from
* the accepted or rejected topics, it updates xReportStatus. */
if( xStatus == true )
{
for( uxIdx = 0; uxIdx < DEFENDER_RESPONSE_WAIT_SECONDS; uxIdx++ )
{
( void ) xProcessLoop( &xMqttContext, 1000 );
/* xReportStatus is updated in the prvPublishCallback. */
if( xReportStatus != ReportStatusNotReceived )
{
break;
}
}
}
if( xReportStatus == ReportStatusNotReceived )
{
LogError( ( "Failed to receive response from AWS IoT Device Defender Service." ) );
xStatus = false;
}
/**************************** Disconnect. *****************************/
/* Unsubscribe and disconnect if MQTT session was established. Per the MQTT
* protocol spec, it is okay to send UNSUBSCRIBE even if no corresponding
* subscription exists on the broker. Therefore, it is okay to attempt
* unsubscribe even if one more subscribe failed earlier. */
if( xMqttSessionEstablished )
{
LogInfo( ( "Unsubscribing from defender topics..." ) );
xStatus = prvUnsubscribeFromDefenderTopics();
if( xStatus != true )
{
LogError( ( "Failed to unsubscribe from defender topics." ) );
}
LogInfo( ( "Closing MQTT session..." ) );
( void ) xDisconnectMqttSession( &xMqttContext,
&xNetworkContext );
}
if( ( xStatus == true ) && ( xReportStatus == ReportStatusAccepted ) )
{
xExitStatus = EXIT_SUCCESS;
}
/*********************** Retry in case of failure. ************************/
/* Increment the demo run count. */
uxDemoRunCount++;
if( xExitStatus == EXIT_SUCCESS )
{
LogInfo( ( "Demo iteration %lu is successful.", uxDemoRunCount ) );
}
/* Attempt to retry a failed iteration of demo for up to #DEFENDER_MAX_DEMO_LOOP_COUNT times. */
else if( uxDemoRunCount < DEFENDER_MAX_DEMO_LOOP_COUNT )
{
LogWarn( ( "Demo iteration %lu failed. Retrying...", uxDemoRunCount ) );
vTaskDelay( DELAY_BETWEEN_DEMO_RETRY_ITERATIONS_TICKS );
}
/* Failed all #DEFENDER_MAX_DEMO_LOOP_COUNT demo iterations. */
else
{
LogError( ( "All %d demo iterations failed.", DEFENDER_MAX_DEMO_LOOP_COUNT ) );
break;
}
} while( xExitStatus != EXIT_SUCCESS );
/****************************** Finish. ******************************/
if( xExitStatus == EXIT_SUCCESS )
{
LogInfo( ( "Demo completed successfully." ) );
}
else
{
LogError( ( "Demo failed." ) );
}
LogInfo( ( "-------DEMO FINISHED-------\r\n" ) );
/* Delete this task. */
LogInfo( ( "Deleting Defender Demo task." ) );
vTaskDelete( NULL );
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,198 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{6c548950-0bed-42ef-8039-95a2084a806d}</ProjectGuid>
<RootNamespace>DeviceDefenderDemo</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\AWS\device-defender\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\AWS\device-defender\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\AWS\device-defender\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="medtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\AWS\device-defender\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.c" />
<ClCompile Include="..\..\..\..\Source\AWS\device-defender\source\defender.c" />
<ClCompile Include="..\..\..\..\Source\coreJSON\source\core_json.c" />
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c" />
<ClCompile Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.c" />
<ClCompile Include="DemoTasks\DefenderDemoExample.c" />
<ClCompile Include="main.c" />
<ClCompile Include="metrics_collector.c" />
<ClCompile Include="report_builder.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.h" />
<ClInclude Include="..\..\..\..\Source\AWS\device-defender\source\include\defender.h" />
<ClInclude Include="..\..\..\..\Source\AWS\device-defender\source\include\defender_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\coreJSON\source\include\core_json.h" />
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h" />
<ClInclude Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.h" />
<ClInclude Include="core_mqtt_config.h" />
<ClInclude Include="defender_config.h" />
<ClInclude Include="demo_config.h" />
<ClInclude Include="metrics_collector.h" />
<ClInclude Include="report_builder.h" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj">
<Project>{c90e6cc5-818b-4c97-8876-0986d989387c}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj">
<Project>{72c209c4-49a4-4942-a201-44706c9d77ec}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj">
<Project>{be362ac0-b10b-4276-b84e-6304652ba228}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj">
<Project>{e1016f3e-94e9-4864-9fd8-1d7c1fefbfd7}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,171 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="Additional Network Transport Files">
<UniqueIdentifier>{dd51d59e-5364-4754-8bf8-9d28b504b06d}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries">
<UniqueIdentifier>{2860744a-0818-43ed-823e-814141580842}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT Device Defender">
<UniqueIdentifier>{f9d9acc8-facf-4594-848f-c86e8d4448ed}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT Device Defender\include">
<UniqueIdentifier>{c9e66dd3-1d31-4e7f-91f8-044acb1d500c}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT">
<UniqueIdentifier>{df5ee1fa-4f3a-47a2-b3f6-5b78ad7b8c90}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\include">
<UniqueIdentifier>{69eea975-6c9c-40bc-b0af-4fb5133106c1}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\interface">
<UniqueIdentifier>{432ee803-f901-47d9-94cc-5ca2f95211ea}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreJSON">
<UniqueIdentifier>{ad937432-b2b1-4c00-81ab-2f89f93fab5e}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreJSON\include">
<UniqueIdentifier>{aae732f5-763c-4654-907f-a3b8d3ac59b7}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm">
<UniqueIdentifier>{4a9d6aa8-5941-465f-9b9c-4ea26cd54f45}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm\include">
<UniqueIdentifier>{402f543a-4604-4007-a33e-88a612b1bccd}</UniqueIdentifier>
</Filter>
<Filter Include="Config">
<UniqueIdentifier>{2bc92365-ac9c-4c19-9f72-fb69e25d2b57}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport">
<UniqueIdentifier>{65d207cd-19f3-4660-9f1a-a8d91a5b4389}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include">
<UniqueIdentifier>{5f612844-a9d1-495d-9945-78b7502c17eb}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper">
<UniqueIdentifier>{8d8cb4b4-13f9-4ff1-9465-e1fc9f293fc8}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\include">
<UniqueIdentifier>{bc47cbaf-951c-4b67-8400-2e7d7efe5bf0}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports">
<UniqueIdentifier>{528452a5-23b0-41fe-b45e-0bb78c435d75}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports\freertos_plus_tcp">
<UniqueIdentifier>{a1785447-203d-46e5-aa81-d3e2c5c257be}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="DemoTasks\DefenderDemoExample.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="main.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="metrics_collector.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="report_builder.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\device-defender\source\defender.c">
<Filter>Additional Libraries\AWS IoT Device Defender</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c">
<Filter>Additional Libraries\Backoff Algorithm</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\coreJSON\source\core_json.c">
<Filter>Additional Libraries\coreJSON</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\ports\freertos_plus_tcp</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="metrics_collector.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="report_builder.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\device-defender\source\include\defender.h">
<Filter>Additional Libraries\AWS IoT Device Defender\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\device-defender\source\include\defender_config_defaults.h">
<Filter>Additional Libraries\AWS IoT Device Defender\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h">
<Filter>Additional Libraries\Backoff Algorithm\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h">
<Filter>Additional Libraries\coreMQTT\interface</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\coreJSON\source\include\core_json.h">
<Filter>Additional Libraries\coreJSON\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include</Filter>
</ClInclude>
<ClInclude Include="core_mqtt_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="defender_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="demo_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,96 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef CORE_MQTT_CONFIG_H
#define CORE_MQTT_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 MQTT.
* 3. Include the header file "logging_stack.h", if logging is enabled for MQTT.
*/
#include "logging_levels.h"
/* Logging configuration for the MQTT library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "MQTT"
#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 ****************/
/**
* @brief Determines the maximum number of MQTT PUBLISH messages, pending
* acknowledgement at a time, that are supported for incoming and outgoing
* direction of messages, separately.
*
* QoS 1 and 2 MQTT PUBLISHes require acknowledgement from the server before
* they can be completed. While they are awaiting the acknowledgement, the
* client must maintain information about their state. The value of this
* macro sets the limit on how many simultaneous PUBLISH states an MQTT
* context maintains, separately, for both incoming and outgoing direction of
* PUBLISHes.
*
* @note The MQTT context maintains separate state records for outgoing
* and incoming PUBLISHes, and thus, 2 * MQTT_STATE_ARRAY_MAX_COUNT amount
* of memory is statically allocated for the state records.
*/
#define MQTT_STATE_ARRAY_MAX_COUNT ( 10U )
/**
* @brief Number of milliseconds to wait for a ping response to a ping
* request as part of the keep-alive mechanism.
*
* If a ping response is not received before this timeout, then
* #MQTT_ProcessLoop will return #MQTTKeepAliveTimeout.
*/
#define MQTT_PINGRESP_TIMEOUT_MS ( 5000U )
#endif /* ifndef CORE_MQTT_CONFIG_H */

View File

@ -0,0 +1,95 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef DEFENDER_CONFIG_H_
#define DEFENDER_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.
* 3. Include the header file "logging_stack.h".
*/
#include "logging_levels.h"
/* Logging configuration for the Defender library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "Defender"
#endif
#ifndef LIBRARY_LOG_LEVEL
#define LIBRARY_LOG_LEVEL LOG_INFO
#endif
#include "logging_stack.h"
/************ End of logging configuration ****************/
/**
* AWS IoT Device Defender Service supports both long and short names for keys
* in the report sent by a device. For example,
*
* A device defender report using long key names:
* {
* "header": {
* "report_id": 1530304554,
* "version": "1.0"
* },
* "metrics": {
* "network_stats": {
* "bytes_in": 29358693495,
* "bytes_out": 26485035,
* "packets_in": 10013573555,
* "packets_out": 11382615
* }
* }
* }
*
* An equivalent report using short key names:
* {
* "hed": {
* "rid": 1530304554,
* "v": "1.0"
* },
* "met": {
* "ns": {
* "bi": 29358693495,
* "bo": 26485035,
* "pi": 10013573555,
* "po": 11382615
* }
* }
* }
*
* Set to 1 to enable use of long key names in the defender report.
*/
#define DEFENDER_USE_LONG_KEYS 0
#endif /* ifndef DEFENDER_CONFIG_H_ */

View File

@ -0,0 +1,79 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31205.134
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Device_Defender_Demo", "Device_Defender_Demo.vcxproj", "{6C548950-0BED-42EF-8039-95A2084A806D}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS+TCP", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj", "{C90E6CC5-818B-4C97-8876-0986D989387C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS-Kernel", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj", "{72C209C4-49A4-4942-A201-44706C9D77EC}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Logging", "..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj", "{BE362AC0-B10B-4276-B84E-6304652BA228}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MbedTLS", "..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj", "{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Statically Linked Libraries", "Statically Linked Libraries", "{DBCD753C-52CF-4671-B979-F19EF96D4303}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6C548950-0BED-42EF-8039-95A2084A806D}.Debug|x64.ActiveCfg = Debug|x64
{6C548950-0BED-42EF-8039-95A2084A806D}.Debug|x64.Build.0 = Debug|x64
{6C548950-0BED-42EF-8039-95A2084A806D}.Debug|x86.ActiveCfg = Debug|Win32
{6C548950-0BED-42EF-8039-95A2084A806D}.Debug|x86.Build.0 = Debug|Win32
{6C548950-0BED-42EF-8039-95A2084A806D}.Release|x64.ActiveCfg = Release|x64
{6C548950-0BED-42EF-8039-95A2084A806D}.Release|x64.Build.0 = Release|x64
{6C548950-0BED-42EF-8039-95A2084A806D}.Release|x86.ActiveCfg = Release|Win32
{6C548950-0BED-42EF-8039-95A2084A806D}.Release|x86.Build.0 = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.ActiveCfg = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.Build.0 = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x86.ActiveCfg = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x86.Build.0 = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.ActiveCfg = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.Build.0 = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x86.ActiveCfg = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x86.Build.0 = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.ActiveCfg = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.Build.0 = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x86.ActiveCfg = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x86.Build.0 = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.ActiveCfg = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.Build.0 = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x86.ActiveCfg = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x86.Build.0 = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.ActiveCfg = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.Build.0 = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x86.ActiveCfg = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x86.Build.0 = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.ActiveCfg = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.Build.0 = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x86.ActiveCfg = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x86.Build.0 = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.ActiveCfg = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.Build.0 = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x86.ActiveCfg = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x86.Build.0 = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.ActiveCfg = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.Build.0 = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x86.ActiveCfg = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C90E6CC5-818B-4C97-8876-0986D989387C} = {DBCD753C-52CF-4671-B979-F19EF96D4303}
{72C209C4-49A4-4942-A201-44706C9D77EC} = {DBCD753C-52CF-4671-B979-F19EF96D4303}
{BE362AC0-B10B-4276-B84E-6304652BA228} = {DBCD753C-52CF-4671-B979-F19EF96D4303}
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7} = {DBCD753C-52CF-4671-B979-F19EF96D4303}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E8237739-26DE-4179-84E1-70E13623A2ED}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,288 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef DEMO_CONFIG_H
#define DEMO_CONFIG_H
/* FreeRTOS config include. */
#include "FreeRTOSConfig.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 "DefenderDemo"
#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 Thing resource registered on your AWS IoT account to use in the demo.
* A Thing resource is required to communicate with the AWS IoT Device Shadow service.
*
* @note The Things associated with your AWS account can be found in the
* AWS IoT console under Manage/Things, or using the ListThings REST API (that can
* be called with the AWS CLI command line tool).
*
* #define democonfigTHING_NAME "...insert here..."
*/
#ifndef democonfigCLIENT_IDENTIFIER
/**
* @brief The MQTT client identifier used in this example. Each client identifier
* must be unique so edit as required to ensure no two clients connecting to the
* same broker use the same client identifier.
*
* @note Appending __TIME__ to the client id string will reduce the possibility of a
* client id collision in the broker. Note that the appended time is the compilation
* time. This client id can cause collision, if more than one instance of the same
* binary is used at the same time to connect to the broker.
*/
#define democonfigCLIENT_IDENTIFIER "testClient"__TIME__
#endif
/**
* @brief The AWS IoT broker endpoint to connect to in the demo.
*
* @note Your AWS IoT Core endpoint can be found in the AWS IoT console under
* Settings/Custom Endpoint, or using the DescribeEndpoint REST API (that can
* be called with AWS CLI command line tool).
*
* #define democonfigMQTT_BROKER_ENDPOINT "...insert here..."
*/
/**
* @brief The port to use for the demo.
*
* In general, port 8883 is for secured MQTT connections.
*
* @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol
* name. Using ALPN with this demo would require additional changes, including
* setting the `pAlpnProtos` member of the `NetworkCredentials_t` struct before
* forming the TLS connection. When using port 8883, ALPN is not required.
*
* #define democonfigMQTT_BROKER_PORT ( insert here. )
*/
/**
* @brief AWS root CA certificate.
*
* This certificate is used to identify the AWS IoT server and is publicly available.
* Refer to the link below.
* https://www.amazontrust.com/repository/AmazonRootCA1.pem
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigROOT_CA_PEM "...insert here..."
*/
/**
* @brief Client certificate.
*
* Please refer to the AWS documentation below for details
* regarding client authentication.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigCLIENT_CERTIFICATE_PEM "...insert here..."
*/
/**
* @brief Client's private key.
*
* Please refer to the AWS documentation below for details
* regarding client authentication.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
*
* @note This private key should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN RSA PRIVATE KEY-----\n"\
* "...base64 data...\n"\
* "-----END RSA PRIVATE KEY-----\n"
*
* #define democonfigCLIENT_PRIVATE_KEY_PEM "...insert here..."
*/
/**
* @brief The username value for authenticating client to the MQTT broker when
* username/password based client authentication is used.
*
* Please refer to the AWS IoT documentation below for
* details regarding client authentication with a username and password.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* #define democonfigCLIENT_USERNAME "...insert here..."
*/
/**
* @brief The password value for authenticating client to the MQTT broker when
* username/password based client authentication is used.
*
* Please refer to the AWS IoT documentation below for
* details regarding client authentication with a username and password.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* #define democonfigCLIENT_PASSWORD "...insert here..."
*/
/**
* @brief The name of the operating system that the application is running on.
* The current value is given as an example. Please update for your specific
* operating system.
*/
#define democonfigOS_NAME "FreeRTOS"
/**
* @brief The version of the operating system that the application is running
* on. The current value is given as an example. Please update for your specific
* operating system version.
*/
#define democonfigOS_VERSION tskKERNEL_VERSION_NUMBER
/**
* @brief The name of the hardware platform the application is running on. The
* current value is given as an example. Please update for your specific
* hardware platform.
*/
#define democonfigHARDWARE_PLATFORM_NAME "WinSim"
/**
* @brief The name of the MQTT library used and its version, following an "@"
* symbol.
*/
#include "core_mqtt.h" /* Include coreMQTT header for MQTT_LIBRARY_VERSION macro. */
#define democonfigMQTT_LIB "core-mqtt@"MQTT_LIBRARY_VERSION
/**
* @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
/**
* @brief Size of the network buffer for MQTT packets.
*/
#define democonfigNETWORK_BUFFER_SIZE ( 1024U )
/**
* @brief Size of the open TCP ports array.
*
* A maximum of these many open TCP ports will be sent in the device defender
* report.
*/
#define democonfigOPEN_TCP_PORTS_ARRAY_SIZE 10
/**
* @brief Size of the open UDP ports array.
*
* A maximum of these many open UDP ports will be sent in the device defender
* report.
*/
#define democonfigOPEN_UDP_PORTS_ARRAY_SIZE 10
/**
* @brief Size of the established connections array.
*
* A maximum of these many established connections will be sent in the device
* defender report.
*/
#define democonfigESTABLISHED_CONNECTIONS_ARRAY_SIZE 10
/**
* @brief Size of the task numbers array.
*
* This must be at least the number of tasks used.
*/
#define democonfigCUSTOM_METRICS_TASKS_ARRAY_SIZE 10
/**
* @brief Size of the buffer which contains the generated device defender report.
*
* If the generated report is larger than this, it is rejected.
*/
#define democonfigDEVICE_METRICS_REPORT_BUFFER_SIZE 1000
/**
* @brief Major version number of the device defender report.
*/
#define democonfigDEVICE_METRICS_REPORT_MAJOR_VERSION 1
/**
* @brief Minor version number of the device defender report.
*/
#define democonfigDEVICE_METRICS_REPORT_MINOR_VERSION 0
#endif /* DEMO_CONFIG_H */

View File

@ -0,0 +1,108 @@
/*
* FreeRTOS V202212.01
* 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/iot-device-defender for configuration and usage instructions.
***/
/* Standard includes. */
#include <stdio.h>
#include <time.h>
#include <stdint.h>
/* Visual studio intrinsics used so the __debugbreak() function is available
* should an assert get hit. */
#include <intrin.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#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"
/**
* @brief The task used to demonstrate the Defender API.
*
* This task collects metrics from the device using the functions in
* metrics_collector.h and uses them to build a defender report using functions
* in report_builder.h. Metrics include the number for bytes written and read
* over the network, open TCP and UDP ports, and open TCP sockets. The
* generated report is then published to the AWS IoT Device Defender service.
*
* @param[in] pvParameters Parameters as passed at the time of task creation.
* Not used in this example.
*/
void prvDefenderDemoTask( void * pvParameters );
extern void vPlatformInitIpStack( void );
/*-----------------------------------------------------------*/
int main( void )
{
vPlatformInitLogging();
/*
* This example uses a single application task, which shows that how to use
* Device Defender library to generate and validate AWS IoT Device Defender
* MQTT topics, and use the coreMQTT library to communicate with the AWS
* IoT Device Defender service.
*/
xTaskCreate( prvDefenderDemoTask, /* Function that implements the task. */
"DemoTask", /* 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. */
/* Initialize the FreeRTOS+TCP Stack */
vPlatformInitIpStack();
/* 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.
*/
for( ; ; )
{
configASSERT( pdFALSE );
}
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,270 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file metrics_collector.c
*
* @brief Functions used by the defender demo to collect metrics on the
* device's open ports and sockets. FreeRTOS+TCP tcp_netstat utility
* is used to collect this metrics.
*/
/* Standard includes. */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "FreeRTOS_IP.h"
/* Demo config. */
#include "demo_config.h"
/* Interface include. */
#include "metrics_collector.h"
/*-----------------------------------------------------------*/
eMetricsCollectorStatus eGetNetworkStats( NetworkStats_t * pxOutNetworkStats )
{
eMetricsCollectorStatus eStatus = eMetricsCollectorSuccess;
MetricsType_t xMetrics = { 0 };
BaseType_t xMetricsStatus = 0;
configASSERT( pxOutNetworkStats != NULL );
/* Start with everything as zero. */
memset( pxOutNetworkStats, 0, sizeof( NetworkStats_t ) );
/* Get metrics from FreeRTOS+TCP tcp_netstat utility. */
xMetricsStatus = vGetMetrics( &xMetrics );
if( xMetricsStatus != 0 )
{
LogError( ( "Failed to acquire metrics from FreeRTOS+TCP tcp_netstat utility. Status: %d.",
( int ) xMetricsStatus ) );
eStatus = eMetricsCollectorCollectionFailed;
}
/* Fill our response with values gotten from FreeRTOS+TCP. */
if( eStatus == eMetricsCollectorSuccess )
{
LogDebug( ( "Network stats read. Bytes received: %lu, packets received: %lu, "
"bytes sent: %lu, packets sent: %lu.",
( unsigned long ) xMetrics.xInput.uxByteCount,
( unsigned long ) xMetrics.xInput.uxPacketCount,
( unsigned long ) xMetrics.xOutput.uxByteCount,
( unsigned long ) xMetrics.xOutput.uxPacketCount ) );
pxOutNetworkStats->uxBytesReceived = xMetrics.xInput.uxByteCount;
pxOutNetworkStats->uxPacketsReceived = xMetrics.xInput.uxPacketCount;
pxOutNetworkStats->uxBytesSent = xMetrics.xOutput.uxByteCount;
pxOutNetworkStats->uxPacketsSent = xMetrics.xOutput.uxPacketCount;
}
return eStatus;
}
/*-----------------------------------------------------------*/
eMetricsCollectorStatus eGetOpenTcpPorts( uint16_t * pusOutTcpPortsArray,
size_t xTcpPortsArrayLength,
size_t * pxOutNumTcpOpenPorts )
{
eMetricsCollectorStatus eStatus = eMetricsCollectorSuccess;
MetricsType_t xMetrics = { 0 };
BaseType_t xMetricsStatus = 0;
size_t xCopyAmount = 0UL;
/* pusOutTcpPortsArray can be NULL. */
configASSERT( pxOutNumTcpOpenPorts != NULL );
/* Get metrics from FreeRTOS+TCP tcp_netstat utility. */
xMetricsStatus = vGetMetrics( &xMetrics );
if( xMetricsStatus != 0 )
{
LogError( ( "Failed to acquire metrics from FreeRTOS+TCP tcp_netstat utility. Status: %d.",
( int ) xMetricsStatus ) );
eStatus = eMetricsCollectorCollectionFailed;
}
if( eStatus == eMetricsCollectorSuccess )
{
/* Fill the output array with as many TCP ports as will fit in the
* given array. */
if( pusOutTcpPortsArray != NULL )
{
xCopyAmount = xMetrics.xTCPPortList.uxCount;
/* Limit the copied ports to what can fit in the output array. */
if( xTcpPortsArrayLength < xMetrics.xTCPPortList.uxCount )
{
LogWarn( ( "Ports returned truncated due to insufficient buffer size." ) );
xCopyAmount = xTcpPortsArrayLength;
}
memcpy( pusOutTcpPortsArray, &xMetrics.xTCPPortList.usTCPPortList, xCopyAmount * sizeof( uint16_t ) );
/* Return the number of elements copied to the array. */
*pxOutNumTcpOpenPorts = xCopyAmount;
}
else
{
/* Return the total number of open ports. */
*pxOutNumTcpOpenPorts = xMetrics.xTCPPortList.uxCount;
}
}
return eStatus;
}
/*-----------------------------------------------------------*/
eMetricsCollectorStatus eGetOpenUdpPorts( uint16_t * pusOutUdpPortsArray,
size_t xUdpPortsArrayLength,
size_t * pxOutNumUdpOpenPorts )
{
eMetricsCollectorStatus eStatus = eMetricsCollectorSuccess;
MetricsType_t xMetrics = { 0 };
BaseType_t xMetricsStatus = 0;
size_t xCopyAmount = 0UL;
/* pusOutUdpPortsArray can be NULL. */
configASSERT( pxOutNumUdpOpenPorts != NULL );
/* Get metrics from FreeRTOS+TCP tcp_netstat utility. */
xMetricsStatus = vGetMetrics( &xMetrics );
if( xMetricsStatus != 0 )
{
LogError( ( "Failed to acquire metrics from FreeRTOS+TCP tcp_netstat utility. Status: %d.",
( int ) xMetricsStatus ) );
eStatus = eMetricsCollectorCollectionFailed;
}
if( eStatus == eMetricsCollectorSuccess )
{
/* Fill the output array with as many UDP ports as will fit in the
* given array. */
if( pusOutUdpPortsArray != NULL )
{
xCopyAmount = xMetrics.xUDPPortList.uxCount;
/* Limit the copied ports to what can fit in the output array. */
if( xUdpPortsArrayLength < xMetrics.xUDPPortList.uxCount )
{
LogWarn( ( "Ports returned truncated due to insufficient buffer size." ) );
xCopyAmount = xUdpPortsArrayLength;
}
memcpy( pusOutUdpPortsArray, &xMetrics.xUDPPortList.usUDPPortList, xCopyAmount * sizeof( uint16_t ) );
/* Return the number of elements copied to the array. */
*pxOutNumUdpOpenPorts = xCopyAmount;
}
else
{
/* Return the total number of open ports. */
*pxOutNumUdpOpenPorts = xMetrics.xUDPPortList.uxCount;
}
}
return eStatus;
}
/*-----------------------------------------------------------*/
eMetricsCollectorStatus eGetEstablishedConnections( Connection_t * pxOutConnectionsArray,
size_t xConnectionsArrayLength,
size_t * pxOutNumEstablishedConnections )
{
eMetricsCollectorStatus eStatus = eMetricsCollectorSuccess;
MetricsType_t xMetrics = { 0 };
BaseType_t xMetricsStatus = 0;
size_t xCopyAmount = 0UL;
size_t uxIdx;
uint32_t ulLocalIp = 0UL;
/* pxOutConnectionsArray can be NULL. */
configASSERT( pxOutNumEstablishedConnections != NULL );
/* Get metrics from FreeRTOS+TCP tcp_netstat utility. */
xMetricsStatus = vGetMetrics( &xMetrics );
if( xMetricsStatus != 0 )
{
LogError( ( "Failed to acquire metrics from FreeRTOS+TCP tcp_netstat utility. Status: %d.",
( int ) xMetricsStatus ) );
eStatus = eMetricsCollectorCollectionFailed;
}
if( eStatus == eMetricsCollectorSuccess )
{
/* Fill the output array with as many TCP socket infos as will fit in
* the given array. */
if( pxOutConnectionsArray != NULL )
{
xCopyAmount = xMetrics.xTCPSocketList.uxCount;
/* Get local IP as the tcp_netstat utility does not give it. */
ulLocalIp = FreeRTOS_GetIPAddress();
/* Limit the outputted connections to what can fit in the output array. */
if( xConnectionsArrayLength < xMetrics.xTCPSocketList.uxCount )
{
LogWarn( ( "Ports returned truncated due to insufficient buffer size." ) );
xCopyAmount = xConnectionsArrayLength;
}
for( uxIdx = 0; uxIdx < xCopyAmount; uxIdx++ )
{
pxOutConnectionsArray[ uxIdx ].ulLocalIp = ulLocalIp;
pxOutConnectionsArray[ uxIdx ].usLocalPort =
xMetrics.xTCPSocketList.xTCPList[ uxIdx ].usLocalPort;
pxOutConnectionsArray[ uxIdx ].ulRemoteIp =
xMetrics.xTCPSocketList.xTCPList[ uxIdx ].ulRemoteIP;
pxOutConnectionsArray[ uxIdx ].usRemotePort =
xMetrics.xTCPSocketList.xTCPList[ uxIdx ].usRemotePort;
}
/* Return the number of elements copied to the array. */
*pxOutNumEstablishedConnections = xCopyAmount;
}
else
{
/* Return the total number of established connections. */
*pxOutNumEstablishedConnections = xMetrics.xTCPSocketList.uxCount;
}
}
return eStatus;
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,149 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file metrics_collector.h
*
* @brief Functions used by the defender demo to collect metrics on the
* device's open ports and sockets.
*/
#ifndef METRICS_COLLECTOR_H_
#define METRICS_COLLECTOR_H_
#include <stdint.h>
/**
* @brief Return codes from metrics collector APIs.
*/
typedef enum
{
eMetricsCollectorSuccess = 0,
eMetricsCollectorBadParameter,
eMetricsCollectorCollectionFailed
} eMetricsCollectorStatus;
/**
* @brief Represents network stats.
*/
typedef struct NetworkStats
{
size_t uxBytesReceived; /**< Number of bytes received. */
size_t uxBytesSent; /**< Number of bytes sent. */
size_t uxPacketsReceived; /**< Number of packets (ethernet frames) received. */
size_t uxPacketsSent; /**< Number of packets (ethernet frames) sent. */
} NetworkStats_t;
/**
* @brief Represents a network connection.
*/
typedef struct Connection
{
uint32_t ulLocalIp;
uint32_t ulRemoteIp;
uint16_t usLocalPort;
uint16_t usRemotePort;
} Connection_t;
/**
* @brief Get network stats.
*
* This function returns the network stats.
*
* @param[out] pxOutNetworkStats The network stats.
*
* @return #eMetricsCollectorSuccess if the network stats are successfully obtained;
* #eMetricsCollectorBadParameter if invalid parameters are passed;
* #eMetricsCollectorCollectionFailed if the collection methods failed.
*/
eMetricsCollectorStatus eGetNetworkStats( NetworkStats_t * pxOutNetworkStats );
/**
* @brief Get a list of the open TCP ports.
*
* This function finds the open TCP ports. It can be called with
* @p pusOutTcpPortsArray NULL to get the number of the open TCP ports.
*
* @param[out] pusOutTcpPortsArray The array to write the open TCP ports into. This
* can be NULL, if only the number of open ports is needed.
* @param[in] xTcpPortsArrayLength Length of the pusOutTcpPortsArray, if it is not
* NULL.
* @param[out] pxOutNumTcpOpenPorts Number of open TCP ports if @p
* pusOutTcpPortsArray NULL, else number of TCP ports written.
*
* @return #eMetricsCollectorSuccess if open TCP ports are successfully obtained;
* #eMetricsCollectorBadParameter if invalid parameters are passed;
* #eMetricsCollectorCollectionFailed if the collection methods failed.
*/
eMetricsCollectorStatus eGetOpenTcpPorts( uint16_t * pusOutTcpPortsArray,
size_t xTcpPortsArrayLength,
size_t * pxOutNumTcpOpenPorts );
/**
* @brief Get a list of the open UDP ports.
*
* This function finds the open UDP ports. It can be called with
* @p pusOutUdpPortsArray NULL to get the number of the open UDP ports.
*
* @param[out] pusOutUdpPortsArray The array to write the open UDP ports into. Can
* be NULL, if only number of open ports is needed.
* @param[in] xUdpPortsArrayLength Length of the pusOutUdpPortsArray, if it is not
* NULL.
* @param[out] pxOutNumUdpOpenPorts Number of open UDP ports if @p
* pusOutUdpPortsArray NULL, else number of UDP ports written.
*
* @return #eMetricsCollectorSuccess if open UDP ports are successfully obtained;
* #eMetricsCollectorBadParameter if invalid parameters are passed;
* #eMetricsCollectorCollectionFailed if the collection methods failed.
*/
eMetricsCollectorStatus eGetOpenUdpPorts( uint16_t * pusOutUdpPortsArray,
size_t xUdpPortsArrayLength,
size_t * pxOutNumUdpOpenPorts );
/**
* @brief Get a list of established connections.
*
* This function finds the established TCP connections.
* It can be called with @p pxOutConnectionsArray NULL to get the number of
* established connections.
*
* @param[out] pxOutConnectionsArray The array to write the established connections
* into. This can be NULL, if only the number of established connections is
* needed.
* @param[in] xConnectionsArrayLength Length of the pxOutConnectionsArray, if it
* is not NULL.
* @param[out] pxOutNumEstablishedConnections Number of established connections if @p
* pxOutNumEstablishedConnections NULL, else number of established connections written.
*
* @return #eMetricsCollectorSuccess if established connections are successfully obtained;
* #eMetricsCollectorBadParameter if invalid parameters are passed;
* #eMetricsCollectorCollectionFailed if the collection methods failed.
*/
eMetricsCollectorStatus eGetEstablishedConnections( Connection_t * pxOutConnectionsArray,
size_t xConnectionsArrayLength,
size_t * pxOutNumEstablishedConnections );
#endif /* ifndef METRICS_COLLECTOR_H_ */

View File

@ -0,0 +1,623 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/* Standard includes. */
#include <stdio.h>
#include <string.h>
#include <stdint.h>
/* Kernel includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Demo config. */
#include "demo_config.h"
/* Device Defender Client Library. */
#include "defender.h"
/* Interface include. */
#include "report_builder.h"
/* Helper macro to check if snprintf was successful. */
#define reportbuilderSNPRINTF_SUCCESS( retVal, bufLen ) ( ( retVal > 0 ) && ( ( uint32_t ) retVal < bufLen ) )
/*-----------------------------------------------------------*/
/**
* @brief Write ports array to the given buffer in the format expected by the
* AWS IoT Device Defender Service.
*
* This function writes an array of the following format:
* [
* {
* "port":44207
* },
* {
* "port":53
* }
* ]
*
* @param[in] pcBuffer The buffer to write the ports array.
* @param[in] xBufferLength The length of the buffer.
* @param[in] pusOpenPortsArray The array containing the open ports.
* @param[in] xOpenPortsArrayLength Length of the pusOpenPortsArray array.
* @param[out] pxOutCharsWritten Number of characters written to the buffer.
*
* @return #ReportBuilderSuccess if the array is successfully written;
* #ReportBuilderBufferTooSmall if the buffer cannot hold the full array.
*/
static eReportBuilderStatus prvWritePortsArray( char * pcBuffer,
size_t xBufferLength,
const uint16_t * pusOpenPortsArray,
size_t xOpenPortsArrayLength,
size_t * pxOutCharsWritten );
/**
* @brief Write established connections array to the given buffer in the format
* expected by the AWS IoT Device Defender Service.
*
* This function write array of the following format:
* [
* {
* "local_port":44207,
* "remote_addr":"127.0.0.1:45148"
* },
* {
* "local_port":22,
* "remote_addr":"24.16.237.194:63552"
* }
* ]
*
* @param[in] pcBuffer The buffer to write the connections array.
* @param[in] xBufferLength The length of the buffer.
* @param[in] pxConnectionsArray The array containing the established connections.
* @param[in] xConnectionsArrayLength Length of the pxConnectionsArray array.
* @param[out] pxOutCharsWritten Number of characters written to the buffer.
*
* @return #ReportBuilderSuccess if the array is successfully written;
* #ReportBuilderBufferTooSmall if the buffer cannot hold the full array.
*/
static eReportBuilderStatus prvWriteConnectionsArray( char * pcBuffer,
size_t xBufferLength,
const Connection_t * pxConnectionsArray,
size_t xConnectionsArrayLength,
size_t * pxOutCharsWritten );
/**
* @brief Write task ID array to the given buffer as a JSON array.
*
* @param[in] pcBuffer The buffer to write the array of task IDs.
* @param[in] xBufferLength The length of the buffer.
* @param[in] pxTaskStatusArray The array containing the task statuses.
* @param[in] xTaskStatusArrayLength Length of the pxTaskStatusArray array.
* @param[out] pxOutCharsWritten Number of characters written to the buffer.
*
* @return #ReportBuilderSuccess if the array is successfully written;
* #ReportBuilderBufferTooSmall if the buffer cannot hold the full array.
*/
static eReportBuilderStatus prvWriteTaskIdArray( char * pcBuffer,
size_t xBufferLength,
const TaskStatus_t * pxTaskStatusArray,
size_t xTaskStatusArrayLength,
size_t * pxOutCharsWritten );
/*-----------------------------------------------------------*/
static eReportBuilderStatus prvWritePortsArray( char * pcBuffer,
size_t xBufferLength,
const uint16_t * pusOpenPortsArray,
size_t xOpenPortsArrayLength,
size_t * pxOutCharsWritten )
{
char * pcCurrentWritePos = pcBuffer;
size_t uxIdx;
size_t xRemainingBufferLength = xBufferLength;
int32_t lCharactersWritten;
eReportBuilderStatus eStatus = eReportBuilderSuccess;
configASSERT( pcBuffer != NULL );
configASSERT( pusOpenPortsArray != NULL );
configASSERT( pxOutCharsWritten != NULL );
/* Write the JSON array open marker. */
if( xRemainingBufferLength > 1 )
{
*pcCurrentWritePos = '[';
xRemainingBufferLength -= 1;
pcCurrentWritePos += 1;
}
else
{
eStatus = eReportBuilderBufferTooSmall;
}
/* Write the array elements. */
for( uxIdx = 0U; ( ( uxIdx < xOpenPortsArrayLength ) && ( eStatus == eReportBuilderSuccess ) ); uxIdx++ )
{
lCharactersWritten = snprintf( pcCurrentWritePos,
xRemainingBufferLength,
"{"
"\"" DEFENDER_REPORT_PORT_KEY "\":%u"
"},",
( unsigned int ) pusOpenPortsArray[ uxIdx ] );
if( !reportbuilderSNPRINTF_SUCCESS( lCharactersWritten, xRemainingBufferLength ) )
{
eStatus = eReportBuilderBufferTooSmall;
}
else
{
xRemainingBufferLength -= ( uint32_t ) lCharactersWritten;
pcCurrentWritePos += lCharactersWritten;
}
}
if( eStatus == eReportBuilderSuccess )
{
/* Discard the last comma. */
if( xOpenPortsArrayLength > 0 )
{
pcCurrentWritePos -= 1;
xRemainingBufferLength += 1;
}
/* Write the JSON array close marker. */
if( xRemainingBufferLength > 1 )
{
*pcCurrentWritePos = ']';
xRemainingBufferLength -= 1;
pcCurrentWritePos += 1;
*pxOutCharsWritten = xBufferLength - xRemainingBufferLength;
}
else
{
eStatus = eReportBuilderBufferTooSmall;
}
}
return eStatus;
}
/*-----------------------------------------------------------*/
static eReportBuilderStatus prvWriteConnectionsArray( char * pcBuffer,
size_t xBufferLength,
const Connection_t * pxConnectionsArray,
size_t xConnectionsArrayLength,
size_t * pxOutCharsWritten )
{
char * pcCurrentWritePos = pcBuffer;
size_t uxIdx;
size_t xRemainingBufferLength = xBufferLength;
int32_t lCharactersWritten;
eReportBuilderStatus eStatus = eReportBuilderSuccess;
const Connection_t * pxConn;
configASSERT( pcBuffer != NULL );
configASSERT( pxConnectionsArray != NULL );
configASSERT( pxOutCharsWritten != NULL );
/* Write the JSON array open marker. */
if( xRemainingBufferLength > 1 )
{
*pcCurrentWritePos = '[';
xRemainingBufferLength -= 1;
pcCurrentWritePos += 1;
}
else
{
eStatus = eReportBuilderBufferTooSmall;
}
/* Write the array elements. */
for( uxIdx = 0; ( ( uxIdx < xConnectionsArrayLength ) && ( eStatus == eReportBuilderSuccess ) ); uxIdx++ )
{
pxConn = &( pxConnectionsArray[ uxIdx ] );
lCharactersWritten = snprintf( pcCurrentWritePos,
xRemainingBufferLength,
"{"
"\""DEFENDER_REPORT_LOCAL_PORT_KEY"\": %u,"
"\""DEFENDER_REPORT_REMOTE_ADDR_KEY"\": \"%u.%u.%u.%u:%u\""
"},",
( unsigned int ) pxConn->usLocalPort,
( unsigned int ) ( pxConn->ulRemoteIp >> 24 ) & 0xFF,
( unsigned int ) ( pxConn->ulRemoteIp >> 16 ) & 0xFF,
( unsigned int ) ( pxConn->ulRemoteIp >> 8 ) & 0xFF,
( unsigned int ) ( pxConn->ulRemoteIp ) & 0xFF,
( unsigned int ) pxConn->usRemotePort );
if( !reportbuilderSNPRINTF_SUCCESS( lCharactersWritten, xRemainingBufferLength ) )
{
eStatus = eReportBuilderBufferTooSmall;
}
else
{
xRemainingBufferLength -= lCharactersWritten;
pcCurrentWritePos += lCharactersWritten;
}
}
if( eStatus == eReportBuilderSuccess )
{
/* Discard the last comma. */
if( xConnectionsArrayLength > 0 )
{
pcCurrentWritePos -= 1;
xRemainingBufferLength += 1;
}
/* Write the JSON array close marker. */
if( xRemainingBufferLength > 1 )
{
*pcCurrentWritePos = ']';
xRemainingBufferLength -= 1;
pcCurrentWritePos += 1;
*pxOutCharsWritten = xBufferLength - xRemainingBufferLength;
}
else
{
eStatus = eReportBuilderBufferTooSmall;
}
}
return eStatus;
}
/*-----------------------------------------------------------*/
static eReportBuilderStatus prvWriteTaskIdArray( char * pcBuffer,
size_t xBufferLength,
const TaskStatus_t * pxTaskStatusArray,
size_t xTaskStatusArrayLength,
size_t * pxOutCharsWritten )
{
char * pcCurrentWritePos = pcBuffer;
size_t uxIdx;
size_t xRemainingBufferLength = xBufferLength;
int32_t lCharactersWritten;
eReportBuilderStatus eStatus = eReportBuilderSuccess;
configASSERT( pcBuffer != NULL );
configASSERT( pxTaskStatusArray != NULL );
configASSERT( pxOutCharsWritten != NULL );
/* Write the JSON array open marker. */
if( xRemainingBufferLength > 1 )
{
*pcCurrentWritePos = '[';
xRemainingBufferLength -= 1;
pcCurrentWritePos += 1;
}
else
{
eStatus = eReportBuilderBufferTooSmall;
}
/* Write the array elements. */
for( uxIdx = 0; ( ( uxIdx < xTaskStatusArrayLength ) && ( eStatus == eReportBuilderSuccess ) ); uxIdx++ )
{
lCharactersWritten = snprintf( pcCurrentWritePos,
xRemainingBufferLength,
"%u,",
( unsigned int ) pxTaskStatusArray[ uxIdx ].xTaskNumber );
if( !reportbuilderSNPRINTF_SUCCESS( lCharactersWritten, xRemainingBufferLength ) )
{
eStatus = eReportBuilderBufferTooSmall;
}
else
{
xRemainingBufferLength -= ( uint32_t ) lCharactersWritten;
pcCurrentWritePos += lCharactersWritten;
}
}
if( eStatus == eReportBuilderSuccess )
{
/* Discard the last comma. */
if( xTaskStatusArrayLength > 0 )
{
pcCurrentWritePos -= 1;
xRemainingBufferLength += 1;
}
/* Write the JSON array close marker. */
if( xRemainingBufferLength > 1 )
{
*pcCurrentWritePos = ']';
xRemainingBufferLength -= 1;
pcCurrentWritePos += 1;
*pxOutCharsWritten = xBufferLength - xRemainingBufferLength;
}
else
{
eStatus = eReportBuilderBufferTooSmall;
}
}
return eStatus;
}
/*-----------------------------------------------------------*/
eReportBuilderStatus eGenerateJsonReport( char * pcBuffer,
size_t xBufferLength,
const ReportMetrics_t * pxMetrics,
uint32_t ulMajorReportVersion,
uint32_t ulMinorReportVersion,
uint32_t ulReportId,
size_t * pxOutReportLength )
{
char * pcCurrentWritePos = pcBuffer;
size_t xRemainingBufferLength = xBufferLength;
size_t bufferWritten;
eReportBuilderStatus eStatus = eReportBuilderSuccess;
int32_t lCharactersWritten;
configASSERT( pcBuffer != NULL );
configASSERT( pxMetrics != NULL );
configASSERT( pxOutReportLength != NULL );
configASSERT( xBufferLength != 0 );
if( ( pcBuffer == NULL ) ||
( xBufferLength == 0 ) ||
( pxMetrics == NULL ) ||
( pxOutReportLength == NULL ) )
{
LogError( ( "Invalid parameters. pcBuffer: %p, xBufferLength: %u"
" pMetrics: %p, pOutReprotLength: %p.",
pcBuffer,
xBufferLength,
pxMetrics,
pxOutReportLength ) );
eStatus = eReportBuilderBadParameter;
}
/* Write part1. */
if( eStatus == eReportBuilderSuccess )
{
lCharactersWritten = snprintf( pcCurrentWritePos,
xRemainingBufferLength,
"{"
"\""DEFENDER_REPORT_HEADER_KEY"\": {"
"\""DEFENDER_REPORT_ID_KEY"\": %u,"
"\""DEFENDER_REPORT_VERSION_KEY"\": \"%u.%u\""
"},"
"\""DEFENDER_REPORT_METRICS_KEY"\": {"
"\""DEFENDER_REPORT_TCP_LISTENING_PORTS_KEY"\": {"
"\""DEFENDER_REPORT_PORTS_KEY"\": ",
( unsigned int ) ulReportId,
( unsigned int ) ulMajorReportVersion,
( unsigned int ) ulMinorReportVersion );
if( !reportbuilderSNPRINTF_SUCCESS( lCharactersWritten, xRemainingBufferLength ) )
{
LogError( ( "Failed to write part 1." ) );
eStatus = eReportBuilderBufferTooSmall;
}
else
{
xRemainingBufferLength -= lCharactersWritten;
pcCurrentWritePos += lCharactersWritten;
}
}
/* Write TCP ports array. */
if( eStatus == eReportBuilderSuccess )
{
eStatus = prvWritePortsArray( pcCurrentWritePos,
xRemainingBufferLength,
pxMetrics->pusOpenTcpPortsArray,
pxMetrics->xOpenTcpPortsArrayLength,
&( bufferWritten ) );
if( eStatus == eReportBuilderSuccess )
{
pcCurrentWritePos += bufferWritten;
xRemainingBufferLength -= bufferWritten;
}
else
{
LogError( ( "Failed to write TCP ports array." ) );
}
}
/* Write part2. */
if( eStatus == eReportBuilderSuccess )
{
lCharactersWritten = snprintf( pcCurrentWritePos,
xRemainingBufferLength,
","
"\""DEFENDER_REPORT_TOTAL_KEY"\": %u"
"},"
"\""DEFENDER_REPORT_UDP_LISTENING_PORTS_KEY"\": {"
"\""DEFENDER_REPORT_PORTS_KEY"\": ",
( unsigned int ) pxMetrics->xOpenTcpPortsArrayLength );
if( !reportbuilderSNPRINTF_SUCCESS( lCharactersWritten, xRemainingBufferLength ) )
{
LogError( ( "Failed to write part 2." ) );
eStatus = eReportBuilderBufferTooSmall;
}
else
{
xRemainingBufferLength -= lCharactersWritten;
pcCurrentWritePos += lCharactersWritten;
}
}
/* Write UDP ports array. */
if( eStatus == eReportBuilderSuccess )
{
eStatus = prvWritePortsArray( pcCurrentWritePos,
xRemainingBufferLength,
pxMetrics->pusOpenUdpPortsArray,
pxMetrics->xOpenUdpPortsArrayLength,
&( bufferWritten ) );
if( eStatus == eReportBuilderSuccess )
{
pcCurrentWritePos += bufferWritten;
xRemainingBufferLength -= bufferWritten;
}
else
{
LogError( ( "Failed to write UDP ports array." ) );
}
}
/* Write part3. */
if( eStatus == eReportBuilderSuccess )
{
lCharactersWritten = snprintf( pcCurrentWritePos,
xRemainingBufferLength,
","
"\""DEFENDER_REPORT_TOTAL_KEY"\": %u"
"},"
"\""DEFENDER_REPORT_NETWORK_STATS_KEY"\": {"
"\""DEFENDER_REPORT_BYTES_IN_KEY"\": %u,"
"\""DEFENDER_REPORT_BYTES_OUT_KEY"\": %u,"
"\""DEFENDER_REPORT_PKTS_IN_KEY"\": %u,"
"\""DEFENDER_REPORT_PKTS_OUT_KEY"\": %u"
"},"
"\""DEFENDER_REPORT_TCP_CONNECTIONS_KEY"\": {"
"\""DEFENDER_REPORT_ESTABLISHED_CONNECTIONS_KEY"\": {"
"\""DEFENDER_REPORT_CONNECTIONS_KEY"\": ",
( unsigned int ) pxMetrics->xOpenUdpPortsArrayLength,
( unsigned int ) pxMetrics->pxNetworkStats->uxBytesReceived,
( unsigned int ) pxMetrics->pxNetworkStats->uxBytesSent,
( unsigned int ) pxMetrics->pxNetworkStats->uxPacketsReceived,
( unsigned int ) pxMetrics->pxNetworkStats->uxPacketsSent );
if( !reportbuilderSNPRINTF_SUCCESS( lCharactersWritten, xRemainingBufferLength ) )
{
LogError( ( "Failed to write part 3." ) );
eStatus = eReportBuilderBufferTooSmall;
}
else
{
xRemainingBufferLength -= lCharactersWritten;
pcCurrentWritePos += lCharactersWritten;
}
}
/* Write connections array. */
if( eStatus == eReportBuilderSuccess )
{
eStatus = prvWriteConnectionsArray( pcCurrentWritePos,
xRemainingBufferLength,
pxMetrics->pxEstablishedConnectionsArray,
pxMetrics->xEstablishedConnectionsArrayLength,
&( bufferWritten ) );
if( eStatus == eReportBuilderSuccess )
{
pcCurrentWritePos += bufferWritten;
xRemainingBufferLength -= bufferWritten;
}
else
{
LogError( ( "Failed to write established connections array." ) );
}
}
/* Write part4. */
if( eStatus == eReportBuilderSuccess )
{
lCharactersWritten = snprintf( pcCurrentWritePos,
xRemainingBufferLength,
","
"\""DEFENDER_REPORT_TOTAL_KEY"\": %u"
"}"
"}"
"},"
"\""DEFENDER_REPORT_CUSTOM_METRICS_KEY"\": {"
"\"stack_high_water_mark\": ["
"{"
"\""DEFENDER_REPORT_NUMBER_KEY"\": %u"
"}"
"],"
"\"task_numbers\": ["
"{"
"\""DEFENDER_REPORT_NUMBER_LIST_KEY"\": ",
( unsigned int ) pxMetrics->xEstablishedConnectionsArrayLength,
( unsigned int ) pxMetrics->ulStackHighWaterMark );
if( !reportbuilderSNPRINTF_SUCCESS( lCharactersWritten, xRemainingBufferLength ) )
{
LogError( ( "Failed to write part 4." ) );
eStatus = eReportBuilderBufferTooSmall;
}
else
{
xRemainingBufferLength -= lCharactersWritten;
pcCurrentWritePos += lCharactersWritten;
}
}
/* Write task ids array. */
if( eStatus == eReportBuilderSuccess )
{
eStatus = prvWriteTaskIdArray( pcCurrentWritePos,
xRemainingBufferLength,
pxMetrics->pxTaskStatusArray,
pxMetrics->xTaskStatusArrayLength,
&( bufferWritten ) );
if( eStatus == eReportBuilderSuccess )
{
pcCurrentWritePos += bufferWritten;
xRemainingBufferLength -= bufferWritten;
}
else
{
LogError( ( "Failed to write task ID array." ) );
}
}
/* Write part5. */
if( eStatus == eReportBuilderSuccess )
{
lCharactersWritten = snprintf( pcCurrentWritePos,
xRemainingBufferLength,
"}"
"]"
"}"
"}" );
if( !reportbuilderSNPRINTF_SUCCESS( lCharactersWritten, xRemainingBufferLength ) )
{
LogError( ( "Failed to write part 5." ) );
eStatus = eReportBuilderBufferTooSmall;
}
else
{
xRemainingBufferLength -= lCharactersWritten;
pcCurrentWritePos += lCharactersWritten;
*pxOutReportLength = xBufferLength - xRemainingBufferLength;
}
}
return eStatus;
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,91 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef REPORT_BUILDER_H_
#define REPORT_BUILDER_H_
/* Metrics collector. */
#include "metrics_collector.h"
/**
* @brief Return codes from report builder APIs.
*/
typedef enum
{
eReportBuilderSuccess = 0,
eReportBuilderBadParameter,
eReportBuilderBufferTooSmall
} eReportBuilderStatus;
/**
* @brief Represents metrics to be included in the report, including custom metrics.
*
* This demo demonstrates the use of the stack high water mark and list of
* running task ids as custom metrics sent to AWS IoT Device Defender service.
*
* For more information on custom metrics, refer to the following AWS document:
* https://docs.aws.amazon.com/iot/latest/developerguide/dd-detect-custom-metrics.html
*/
typedef struct ReportMetrics
{
NetworkStats_t * pxNetworkStats;
uint16_t * pusOpenTcpPortsArray;
size_t xOpenTcpPortsArrayLength;
uint16_t * pusOpenUdpPortsArray;
size_t xOpenUdpPortsArrayLength;
Connection_t * pxEstablishedConnectionsArray;
size_t xEstablishedConnectionsArrayLength;
/* Custom metrics */
uint32_t ulStackHighWaterMark;
TaskStatus_t * pxTaskStatusArray;
size_t xTaskStatusArrayLength;
} ReportMetrics_t;
/**
* @brief Generate a report in the format expected by the AWS IoT Device Defender
* Service.
*
* @param[in] pcBuffer The buffer to write the report into.
* @param[in] xBufferLength The length of the buffer.
* @param[in] pxMetrics Metrics to write in the generated report.
* @param[in] ulMajorReportVersion Major version of the report.
* @param[in] ulMinorReportVersion Minor version of the report.
* @param[in] ulReportId Value to be used as the ulReportId in the generated report.
* @param[out] pxOutReprotLength The length of the generated report.
*
* @return #ReportBuilderSuccess if the report is successfully generated;
* #ReportBuilderBadParameter if invalid parameters are passed;
* #ReportBuilderBufferTooSmall if the buffer cannot hold the full report.
*/
eReportBuilderStatus eGenerateJsonReport( char * pcBuffer,
size_t xBufferLength,
const ReportMetrics_t * pxMetrics,
uint32_t ulMajorReportVersion,
uint32_t ulMinorReportVersion,
uint32_t ulReportId,
size_t * pxOutReportLength );
#endif /* ifndef REPORT_BUILDER_H_ */

View File

@ -0,0 +1,95 @@
/*
* FreeRTOS V202212.01
* 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/coremqtt for configuration and usage instructions.
***/
/* Standard includes. */
#include <stdio.h>
#include <time.h>
/* Visual studio intrinsics used so the __debugbreak() function is available
* should an assert get hit. */
#include <intrin.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#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"
/*-----------------------------------------------------------*/
extern void prvShadowDemoTask( void * pvParameters );
extern void vPlatformInitIpStack( void );
/*-----------------------------------------------------------*/
int main( void )
{
vPlatformInitLogging();
/* This example uses a single application task, which shows that how to
* use Device Shadow library to generate and validate AWS IoT Device Shadow
* MQTT topics, and use the coreMQTT library to communicate with the AWS IoT
* Device Shadow service.
*/
xTaskCreate( prvShadowDemoTask, /* Function that implements the task. */
"DemoTask", /* 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. */
/* Initialize the FreeRTOS+TCP Stack */
vPlatformInitIpStack();
/* 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.
*/
for( ; ; )
{
configASSERT( pdFALSE );
}
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,753 @@
/*
* Copyright 2001, 2002 Georges Menie (www.menie.org)
* stdarg version contributed by Christian Ettinger
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Changes for the FreeRTOS ports:
*
* - The dot in "%-8.8s"
* - The specifiers 'l' (long) and 'L' (long long)
* - The specifier 'u' for unsigned
* - Dot notation for IP addresses:
* sprintf("IP = %xip\n", 0xC0A80164);
* will produce "IP = 192.168.1.100\n"
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "FreeRTOS.h"
#define PAD_RIGHT 1
#define PAD_ZERO 2
/*
* Return 1 for readable, 2 for writeable, 3 for both.
* Function must be provided by the application.
*/
extern BaseType_t xApplicationMemoryPermissions( uint32_t aAddress );
extern void vOutputChar( const char cChar,
const TickType_t xTicksToWait );
static const TickType_t xTicksToWait = pdMS_TO_TICKS( 20 );
struct xPrintFlags
{
int base;
int width;
int printLimit;
unsigned
pad : 8,
letBase : 8,
isSigned : 1,
isNumber : 1,
long32 : 1,
long64 : 1;
};
struct SStringBuf
{
char * str;
const char * orgStr;
const char * nulPos;
int curLen;
struct xPrintFlags flags;
};
static void strbuf_init( struct SStringBuf * apStr,
char * apBuf,
const char * apMaxStr )
{
apStr->str = apBuf;
apStr->orgStr = apBuf;
apStr->nulPos = apMaxStr - 1;
apStr->curLen = 0;
memset( &apStr->flags, '\0', sizeof( apStr->flags ) );
}
/*-----------------------------------------------------------*/
static BaseType_t strbuf_printchar( struct SStringBuf * apStr,
int c )
{
if( apStr->str == NULL )
{
vOutputChar( ( char ) c, xTicksToWait );
apStr->curLen++;
return pdTRUE;
}
if( apStr->str < apStr->nulPos )
{
*( apStr->str++ ) = c;
apStr->curLen++;
return pdTRUE;
}
if( apStr->str == apStr->nulPos )
{
*( apStr->str++ ) = '\0';
}
return pdFALSE;
}
/*-----------------------------------------------------------*/
static portINLINE BaseType_t strbuf_printchar_inline( struct SStringBuf * apStr,
int c )
{
if( apStr->str == NULL )
{
vOutputChar( ( char ) c, xTicksToWait );
if( c == 0 )
{
return pdFALSE;
}
apStr->curLen++;
return pdTRUE;
}
if( apStr->str < apStr->nulPos )
{
*( apStr->str++ ) = c;
if( c == 0 )
{
return pdFALSE;
}
apStr->curLen++;
return pdTRUE;
}
if( apStr->str == apStr->nulPos )
{
*( apStr->str++ ) = '\0';
}
return pdFALSE;
}
/*-----------------------------------------------------------*/
static portINLINE int i2hex( int aCh )
{
int iResult;
if( aCh < 10 )
{
iResult = '0' + aCh;
}
else
{
iResult = 'A' + aCh - 10;
}
return iResult;
}
/*-----------------------------------------------------------*/
static BaseType_t prints( struct SStringBuf * apBuf,
const char * apString )
{
register int padchar = ' ';
int i, len;
if( xApplicationMemoryPermissions( ( uint32_t ) apString ) == 0 )
{
/* The user has probably made a mistake with the parameter
* for '%s', the memory is not readbale. */
apString = "INV_MEM";
}
if( apBuf->flags.width > 0 )
{
register int len = 0;
register const char * ptr;
for( ptr = apString; *ptr; ++ptr )
{
++len;
}
if( len >= apBuf->flags.width )
{
apBuf->flags.width = 0;
}
else
{
apBuf->flags.width -= len;
}
if( apBuf->flags.pad & PAD_ZERO )
{
padchar = '0';
}
}
if( ( apBuf->flags.pad & PAD_RIGHT ) == 0 )
{
for( ; apBuf->flags.width > 0; --apBuf->flags.width )
{
if( strbuf_printchar( apBuf, padchar ) == 0 )
{
return pdFALSE;
}
}
}
if( ( apBuf->flags.isNumber == pdTRUE ) && ( apBuf->flags.pad == pdTRUE ) )
{
/* The string to print represents an integer number.
* In this case, printLimit is the min number of digits to print
* If the length of the number to print is less than the min nb of i
* digits to display, we add 0 before printing the number
*/
len = strlen( apString );
if( len < apBuf->flags.printLimit )
{
i = apBuf->flags.printLimit - len;
for( ; i; i-- )
{
if( strbuf_printchar( apBuf, '0' ) == 0 )
{
return pdFALSE;
}
}
}
}
/* The string to print is not the result of a number conversion to ascii.
* For a string, printLimit is the max number of characters to display
*/
for( ; apBuf->flags.printLimit && *apString; ++apString, --apBuf->flags.printLimit )
{
if( !strbuf_printchar( apBuf, *apString ) )
{
return pdFALSE;
}
}
for( ; apBuf->flags.width > 0; --apBuf->flags.width )
{
if( !strbuf_printchar( apBuf, padchar ) )
{
return pdFALSE;
}
}
return pdTRUE;
}
/*-----------------------------------------------------------*/
/* the following should be enough for 32 bit int */
#define PRINT_BUF_LEN 12 /* to print 4294967296 */
#if SPRINTF_LONG_LONG
#warning 64-bit libraries will be included as well
static BaseType_t printll( struct SStringBuf * apBuf,
long long i )
{
char print_buf[ 2 * PRINT_BUF_LEN ];
register char * s;
register int t, neg = 0;
register unsigned long long u = i;
lldiv_t lldiv_result;
/* typedef struct
* {
* long long int quot; // quotient
* long long int rem; // remainder
* } lldiv_t;
*/
apBuf->flags.isNumber = pdTRUE; /* Parameter for prints */
if( i == 0LL )
{
print_buf[ 0 ] = '0';
print_buf[ 1 ] = '\0';
return prints( apBuf, print_buf );
}
if( ( apBuf->flags.isSigned == pdTRUE ) && ( apBuf->flags.base == 10 ) && ( i < 0LL ) )
{
neg = 1;
u = -i;
}
s = print_buf + sizeof( print_buf ) - 1;
*s = '\0';
/* 18446744073709551616 */
while( u != 0 )
{
lldiv_result = lldiv( u, ( unsigned long long ) apBuf->flags.base );
t = lldiv_result.rem;
if( t >= 10 )
{
t += apBuf->flags.letBase - '0' - 10;
}
*( --s ) = t + '0';
u = lldiv_result.quot;
}
if( neg != 0 )
{
if( ( apBuf->flags.width != 0 ) && ( apBuf->flags.pad & PAD_ZERO ) )
{
if( !strbuf_printchar( apBuf, '-' ) )
{
return pdFALSE;
}
--apBuf->flags.width;
}
else
{
*( --s ) = '-';
}
}
return prints( apBuf, s );
}
#endif /* SPRINTF_LONG_LONG */
/*-----------------------------------------------------------*/
static BaseType_t printi( struct SStringBuf * apBuf,
int i )
{
char print_buf[ PRINT_BUF_LEN ];
register char * s;
register int t, neg = 0;
register unsigned int u = i;
register unsigned base = apBuf->flags.base;
apBuf->flags.isNumber = pdTRUE; /* Parameter for prints */
if( i == 0 )
{
print_buf[ 0 ] = '0';
print_buf[ 1 ] = '\0';
return prints( apBuf, print_buf );
}
if( ( apBuf->flags.isSigned == pdTRUE ) && ( base == 10 ) && ( i < 0 ) )
{
neg = 1;
u = -i;
}
s = print_buf + sizeof( print_buf ) - 1;
*s = '\0';
switch( base )
{
case 16:
while( u != 0 )
{
t = u & 0xF;
if( t >= 10 )
{
t += apBuf->flags.letBase - '0' - 10;
}
*( --s ) = t + '0';
u >>= 4;
}
break;
case 8:
case 10:
/* GCC compiles very efficient */
while( u )
{
t = u % base;
*( --s ) = t + '0';
u /= base;
}
break;
/*
* // The generic case, not yet in use
* default:
* while( u )
* {
* t = u % base;
* if( t >= 10)
* {
* t += apBuf->flags.letBase - '0' - 10;
* }
*( --s ) = t + '0';
* u /= base;
* }
* break;
*/
}
if( neg != 0 )
{
if( apBuf->flags.width && ( apBuf->flags.pad & PAD_ZERO ) )
{
if( strbuf_printchar( apBuf, '-' ) == 0 )
{
return pdFALSE;
}
--apBuf->flags.width;
}
else
{
*( --s ) = '-';
}
}
return prints( apBuf, s );
}
/*-----------------------------------------------------------*/
static BaseType_t printIp( struct SStringBuf * apBuf,
unsigned i )
{
char print_buf[ 16 ];
sprintf( print_buf, "%u.%u.%u.%u",
i >> 24,
( i >> 16 ) & 0xff,
( i >> 8 ) & 0xff,
i & 0xff );
apBuf->flags.isNumber = pdTRUE; /* Parameter for prints */
prints( apBuf, print_buf );
return pdTRUE;
}
/*-----------------------------------------------------------*/
static void tiny_print( struct SStringBuf * apBuf,
const char * format,
va_list args )
{
char scr[ 2 ];
for( ; ; )
{
int ch = *( format++ );
if( ch != '%' )
{
do
{
/* Put the most like flow in a small loop */
if( strbuf_printchar_inline( apBuf, ch ) == 0 )
{
return;
}
ch = *( format++ );
} while( ch != '%' );
}
ch = *( format++ );
/* Now ch has character after '%', format pointing to next */
if( ch == '\0' )
{
break;
}
if( ch == '%' )
{
if( strbuf_printchar( apBuf, ch ) == 0 )
{
return;
}
continue;
}
memset( &apBuf->flags, '\0', sizeof( apBuf->flags ) );
if( ch == '-' )
{
ch = *( format++ );
apBuf->flags.pad = PAD_RIGHT;
}
while( ch == '0' )
{
ch = *( format++ );
apBuf->flags.pad |= PAD_ZERO;
}
if( ch == '*' )
{
ch = *( format++ );
apBuf->flags.width = va_arg( args, int );
}
else
{
while( ch >= '0' && ch <= '9' )
{
apBuf->flags.width *= 10;
apBuf->flags.width += ch - '0';
ch = *( format++ );
}
}
if( ch == '.' )
{
ch = *( format++ );
if( ch == '*' )
{
apBuf->flags.printLimit = va_arg( args, int );
ch = *( format++ );
}
else
{
while( ch >= '0' && ch <= '9' )
{
apBuf->flags.printLimit *= 10;
apBuf->flags.printLimit += ch - '0';
ch = *( format++ );
}
}
}
if( apBuf->flags.printLimit == 0 )
{
apBuf->flags.printLimit--; /* -1: make it unlimited */
}
if( ch == 's' )
{
register char * s = ( char * ) va_arg( args, int );
if( prints( apBuf, s ? s : "(null)" ) == 0 )
{
break;
}
continue;
}
if( ch == 'c' )
{
/* char are converted to int then pushed on the stack */
scr[ 0 ] = ( char ) va_arg( args, int );
if( strbuf_printchar( apBuf, scr[ 0 ] ) == 0 )
{
return;
}
continue;
}
if( ch == 'l' )
{
ch = *( format++ );
apBuf->flags.long32 = 1;
/* Makes not difference as u32 == long */
}
if( ch == 'L' )
{
ch = *( format++ );
apBuf->flags.long64 = 1;
/* Does make a difference */
}
apBuf->flags.base = 10;
apBuf->flags.letBase = 'a';
if( ( ch == 'd' ) || ( ch == 'u' ) )
{
apBuf->flags.isSigned = ( ch == 'd' );
#if SPRINTF_LONG_LONG
if( apBuf->flags.long64 != pdFALSE )
{
if( printll( apBuf, va_arg( args, long long ) ) == 0 )
{
break;
}
}
else
#endif /* SPRINTF_LONG_LONG */
if( printi( apBuf, va_arg( args, int ) ) == 0 )
{
break;
}
continue;
}
apBuf->flags.base = 16; /* From here all hexadecimal */
if( ( ch == 'x' ) && ( format[ 0 ] == 'i' ) && ( format[ 1 ] == 'p' ) )
{
format += 2; /* eat the "xi" of "xip" */
/* Will use base 10 again */
if( printIp( apBuf, va_arg( args, int ) ) == 0 )
{
break;
}
continue;
}
if( ( ch == 'x' ) || ( ch == 'X' ) || ( ch == 'p' ) || ( ch == 'o' ) )
{
if( ch == 'X' )
{
apBuf->flags.letBase = 'A';
}
else if( ch == 'o' )
{
apBuf->flags.base = 8;
}
#if SPRINTF_LONG_LONG
if( apBuf->flags.long64 != pdFALSE )
{
if( printll( apBuf, va_arg( args, long long ) ) == 0 )
{
break;
}
}
else
#endif /* SPRINTF_LONG_LONG */
if( printi( apBuf, va_arg( args, int ) ) == 0 )
{
break;
}
continue;
}
}
strbuf_printchar( apBuf, '\0' );
}
/*-----------------------------------------------------------*/
int vsnprintf( char * apBuf,
size_t aMaxLen,
const char * apFmt,
va_list args )
{
struct SStringBuf strBuf;
strbuf_init( &strBuf, apBuf, ( const char * ) apBuf + aMaxLen );
tiny_print( &strBuf, apFmt, args );
return strBuf.curLen;
}
/*-----------------------------------------------------------*/
int snprintf( char * apBuf,
size_t aMaxLen,
const char * apFmt,
... )
{
va_list args;
va_start( args, apFmt );
struct SStringBuf strBuf;
strbuf_init( &strBuf, apBuf, ( const char * ) apBuf + aMaxLen );
tiny_print( &strBuf, apFmt, args );
va_end( args );
return strBuf.curLen;
}
/*-----------------------------------------------------------*/
int sprintf( char * apBuf,
const char * apFmt,
... )
{
va_list args;
va_start( args, apFmt );
struct SStringBuf strBuf;
strbuf_init( &strBuf, apBuf, ( const char * ) apBuf + 1024 );
tiny_print( &strBuf, apFmt, args );
va_end( args );
return strBuf.curLen;
}
/*-----------------------------------------------------------*/
int vsprintf( char * apBuf,
const char * apFmt,
va_list args )
{
struct SStringBuf strBuf;
strbuf_init( &strBuf, apBuf, ( const char * ) apBuf + 1024 );
tiny_print( &strBuf, apFmt, args );
return strBuf.curLen;
}
/*-----------------------------------------------------------*/
const char * mkSize( unsigned long long aSize,
char * apBuf,
int aLen )
{
static char retString[ 33 ];
size_t gb, mb, kb, sb;
if( apBuf == NULL )
{
apBuf = retString;
aLen = sizeof( retString );
}
gb = aSize / ( 1024 * 1024 * 1024 );
aSize -= gb * ( 1024 * 1024 * 1024 );
mb = aSize / ( 1024 * 1024 );
aSize -= mb * ( 1024 * 1024 );
kb = aSize / ( 1024 );
aSize -= kb * ( 1024 );
sb = aSize;
if( gb )
{
snprintf( apBuf, aLen, "%u.%02u GB", ( unsigned ) gb, ( unsigned ) ( ( 100 * mb ) / 1024ul ) );
}
else if( mb )
{
snprintf( apBuf, aLen, "%u.%02u MB", ( unsigned ) mb, ( unsigned ) ( ( 100 * kb ) / 1024ul ) );
}
else if( kb != 0ul )
{
snprintf( apBuf, aLen, "%u.%02u KB", ( unsigned ) kb, ( unsigned ) ( ( 100 * sb ) / 1024ul ) );
}
else
{
snprintf( apBuf, aLen, "%u bytes", ( unsigned ) sb );
}
return apBuf;
}

View File

@ -0,0 +1,194 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{717f029b-ade9-433a-9c05-3136171beaef}</ProjectGuid>
<RootNamespace>DeviceShadowDemo</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\device-shadow\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\device-shadow\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\device-shadow\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\device-shadow\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.h" />
<ClInclude Include="..\..\..\..\Source\AWS\device-shadow\source\include\shadow.h" />
<ClInclude Include="..\..\..\..\Source\AWS\device-shadow\source\include\shadow_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\coreJSON\source\include\core_json.h" />
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h" />
<ClInclude Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.h" />
<ClInclude Include="core_mqtt_config.h" />
<ClInclude Include="demo_config.h" />
<ClInclude Include="shadow_config.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.c" />
<ClCompile Include="..\..\..\..\Source\AWS\device-shadow\source\shadow.c" />
<ClCompile Include="..\..\..\..\Source\coreJSON\source\core_json.c" />
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c" />
<ClCompile Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.c" />
<ClCompile Include="..\Common\main.c" />
<ClCompile Include="DemoTasks\ShadowDemoMainExample.c" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj">
<Project>{c90e6cc5-818b-4c97-8876-0986d989387c}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj">
<Project>{72c209c4-49a4-4942-a201-44706c9d77ec}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj">
<Project>{be362ac0-b10b-4276-b84e-6304652ba228}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj">
<Project>{e1016f3e-94e9-4864-9fd8-1d7c1fefbfd7}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,159 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="Additional Libraries">
<UniqueIdentifier>{a3c730a6-e260-4aa8-9ac2-34e7b58239aa}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT Device Shadow">
<UniqueIdentifier>{3162edd4-992f-40be-b044-3f4069fde765}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm">
<UniqueIdentifier>{2d81cf16-57de-4819-90e6-1a7aa43e1ca7}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT">
<UniqueIdentifier>{88ec2b7c-46b1-4922-a846-17df01fcc563}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreJSON">
<UniqueIdentifier>{561e7533-6144-46a2-8d3c-cfae00f253cc}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files">
<UniqueIdentifier>{5bce4131-4166-4cf0-a174-9501b84a59d1}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT Device Shadow\include">
<UniqueIdentifier>{c90b8caf-7b86-4667-a408-616c9de28018}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm\include">
<UniqueIdentifier>{ee35951a-05c0-47e4-89b5-0b03d6df4c31}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\include">
<UniqueIdentifier>{0059dfb9-954b-4be9-a039-33bd0d6e59d8}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\interface">
<UniqueIdentifier>{5b02b44f-c821-4ccf-8653-d4ee6317fab1}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreJSON\include">
<UniqueIdentifier>{8d194642-3f5f-4ad2-aae2-c1822303b0d3}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper">
<UniqueIdentifier>{a54febab-66c8-49c4-8f14-66b98f5507ad}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport">
<UniqueIdentifier>{3f9ffdaf-339e-4ec0-8191-dc24bc8cfa78}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include">
<UniqueIdentifier>{9ef7993e-bc65-4a5d-8004-f7c59786ba20}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\include">
<UniqueIdentifier>{c31d06d1-374f-46ab-b93f-f9a6e7411114}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports">
<UniqueIdentifier>{cf1a86db-4855-4457-9da6-8fa329e4e85e}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports\freertos_plus_tcp">
<UniqueIdentifier>{dc36bf1d-c1a0-49a3-ae7f-e5030fcacf3b}</UniqueIdentifier>
</Filter>
<Filter Include="Config">
<UniqueIdentifier>{bff12cfa-4535-4d9d-8177-c40bf4fd3fb9}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\..\Source\AWS\device-shadow\source\include\shadow.h">
<Filter>Additional Libraries\AWS IoT Device Shadow\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\device-shadow\source\include\shadow_config_defaults.h">
<Filter>Additional Libraries\AWS IoT Device Shadow\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h">
<Filter>Additional Libraries\Backoff Algorithm\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h">
<Filter>Additional Libraries\coreMQTT\interface</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\coreJSON\source\include\core_json.h">
<Filter>Additional Libraries\coreJSON\include</Filter>
</ClInclude>
<ClInclude Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include</Filter>
</ClInclude>
<ClInclude Include="core_mqtt_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="demo_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="shadow_config.h">
<Filter>Config</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="DemoTasks\ShadowDemoMainExample.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Common\main.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\device-shadow\source\shadow.c">
<Filter>Additional Libraries\AWS IoT Device Shadow</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c">
<Filter>Additional Libraries\Backoff Algorithm</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\coreJSON\source\core_json.c">
<Filter>Additional Libraries\coreJSON</Filter>
</ClCompile>
<ClCompile Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\ports\freertos_plus_tcp</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,6 @@
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,11
[InternetShortcut]
IDList=
URL=https://www.freertos.org/iot-device-shadow/index.html

View File

@ -0,0 +1,78 @@
/*
* FreeRTOS V202212.01
* 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://aws.amazon.com/freertos
*/
#ifndef CORE_MQTT_CONFIG_H
#define CORE_MQTT_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 MQTT.
* 3. Include the header file "logging_stack.h", if logging is enabled for MQTT.
*/
#include "logging_levels.h"
/* Logging configuration for the MQTT library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "MQTT"
#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 ****************/
/**
* @brief The maximum number of MQTT PUBLISH messages that may be pending
* acknowledgement at any time.
*
* QoS 1 and 2 MQTT PUBLISHes require acknowledgment from the server before
* they can be completed. While they are awaiting the acknowledgment, the
* client must maintain information about their state. The value of this
* macro sets the limit on how many simultaneous PUBLISH states an MQTT
* context maintains.
*/
#define MQTT_STATE_ARRAY_MAX_COUNT 10U
#endif /* ifndef CORE_MQTT_CONFIG_H */

View File

@ -0,0 +1,248 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef DEMO_CONFIG_H
#define DEMO_CONFIG_H
/* FreeRTOS config include. */
#include "FreeRTOSConfig.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 "ShadowDemo"
#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 Thing resource registered on your AWS IoT account to use in the demo.
* A Thing resource is required to communicate with the AWS IoT Device Shadow service.
*
* @note The Things associated with your AWS account can be found in the
* AWS IoT console under Manage/Things, or using the ListThings REST API (that can
* be called with the AWS CLI command line tool).
*
* #define democonfigTHING_NAME "...insert here..."
*/
#ifndef democonfigCLIENT_IDENTIFIER
/**
* @brief The MQTT client identifier used in this example. Each client identifier
* must be unique so edit as required to ensure no two clients connecting to the
* same broker use the same client identifier.
*
* @note Appending __TIME__ to the client id string will reduce the possibility of a
* client id collision in the broker. Note that the appended time is the compilation
* time. This client id can cause collision, if more than one instance of the same
* binary is used at the same time to connect to the broker.
*/
#define democonfigCLIENT_IDENTIFIER "testClient"__TIME__
#endif
/**
* @brief The AWS IoT broker endpoint to connect to in the demo.
*
* @note Your AWS IoT Core endpoint can be found in the AWS IoT console under
* Settings/Custom Endpoint, or using the DescribeEndpoint REST API (that can
* be called with AWS CLI command line tool).
*
* #define democonfigMQTT_BROKER_ENDPOINT "...insert here..."
*/
/**
* @brief The port to use for the demo.
*
* In general, port 8883 is for secured MQTT connections.
*
* @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol
* name. Using ALPN with this demo would require additional changes, including
* setting the `pAlpnProtos` member of the `NetworkCredentials_t` struct before
* forming the TLS connection. When using port 8883, ALPN is not required.
*
* #define democonfigMQTT_BROKER_PORT ( insert here. )
*/
/**
* @brief AWS root CA certificate.
*
* This certificate is used to identify the AWS IoT server and is publicly available.
* Refer to the link below.
* https://www.amazontrust.com/repository/AmazonRootCA1.pem
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigROOT_CA_PEM "...insert here..."
*/
/**
* @brief Client certificate.
*
* Please refer to the AWS documentation below for details
* regarding client authentication.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigCLIENT_CERTIFICATE_PEM "...insert here..."
*/
/**
* @brief Client's private key.
*
* Please refer to the AWS documentation below for details
* regarding clientauthentication.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
*
* @note This private key should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN RSA PRIVATE KEY-----\n"\
* "...base64 data...\n"\
* "-----END RSA PRIVATE KEY-----\n"
*
* #define democonfigCLIENT_PRIVATE_KEY_PEM "...insert here..."
*/
/**
* @brief The username value for authenticating client to the MQTT broker when
* username/password based client authentication is used.
*
* Please refer to the AWS IoT documentation below for
* details regarding client authentication with a username and password.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* #define democonfigCLIENT_USERNAME "...insert here..."
*/
/**
* @brief The password value for authenticating client to the MQTT broker when
* username/password based client authentication is used.
*
* Please refer to the AWS IoT documentation below for
* details regarding client authentication with a username and password.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* #define democonfigCLIENT_PASSWORD "...insert here..."
*/
/**
* @brief The name of the operating system that the application is running on.
* The current value is given as an example. Please update for your specific
* operating system.
*/
#define democonfigOS_NAME "FreeRTOS"
/**
* @brief The version of the operating system that the application is running
* on. The current value is given as an example. Please update for your specific
* operating system version.
*/
#define democonfigOS_VERSION tskKERNEL_VERSION_NUMBER
/**
* @brief The name of the hardware platform the application is running on. The
* current value is given as an example. Please update for your specific
* hardware platform.
*/
#define democonfigHARDWARE_PLATFORM_NAME "WinSim"
/**
* @brief The name of the MQTT library used and its version, following an "@"
* symbol.
*/
#include "core_mqtt.h" /* Include coreMQTT header for MQTT_LIBRARY_VERSION macro. */
#define democonfigMQTT_LIB "core-mqtt@"MQTT_LIBRARY_VERSION
/**
* @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
/**
* @brief Size of the network buffer for MQTT packets.
*/
#define democonfigNETWORK_BUFFER_SIZE ( 1024U )
/**
* @brief Predefined shadow name.
*
* Defaults to unnamed "Classic" shadow. Change to a custom string to use a named shadow.
*/
#ifndef democonfigSHADOW_NAME
#define democonfigSHADOW_NAME SHADOW_NAME_CLASSIC
#endif
#endif /* DEMO_CONFIG_H */

View File

@ -0,0 +1,64 @@
/*
* AWS IoT Device SDK for Embedded C V202009.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.
*/
#ifndef SHADOW_CONFIG_H
#define SHADOW_CONFIG_H
/**************************************************/
/******* DO NOT CHANGE the following order ********/
/**************************************************/
/* Logging related header files are required to be included in the following order:
* 1. Include the header file "logging_levels.h".
* 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL.
* 3. Include the header file "logging_stack.h".
*/
/* Include header that defines log levels. */
#include "logging_levels.h"
/* Configure name and log level for the Shadow library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "SHADOW"
#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 ****************/
#endif /* ifndef SHADOW_CONFIG_H */

View File

@ -0,0 +1,79 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31205.134
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Device_Shadow_Demo", "Device_Shadow_Demo.vcxproj", "{717F029B-ADE9-433A-9C05-3136171BEAEF}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS+TCP", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj", "{C90E6CC5-818B-4C97-8876-0986D989387C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS-Kernel", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj", "{72C209C4-49A4-4942-A201-44706C9D77EC}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Logging", "..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj", "{BE362AC0-B10B-4276-B84E-6304652BA228}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MbedTLS", "..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj", "{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Statically Linked Libraries", "Statically Linked Libraries", "{DD2D75A0-EA94-448B-A552-4A68E8336436}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{717F029B-ADE9-433A-9C05-3136171BEAEF}.Debug|x64.ActiveCfg = Debug|x64
{717F029B-ADE9-433A-9C05-3136171BEAEF}.Debug|x64.Build.0 = Debug|x64
{717F029B-ADE9-433A-9C05-3136171BEAEF}.Debug|x86.ActiveCfg = Debug|Win32
{717F029B-ADE9-433A-9C05-3136171BEAEF}.Debug|x86.Build.0 = Debug|Win32
{717F029B-ADE9-433A-9C05-3136171BEAEF}.Release|x64.ActiveCfg = Release|x64
{717F029B-ADE9-433A-9C05-3136171BEAEF}.Release|x64.Build.0 = Release|x64
{717F029B-ADE9-433A-9C05-3136171BEAEF}.Release|x86.ActiveCfg = Release|Win32
{717F029B-ADE9-433A-9C05-3136171BEAEF}.Release|x86.Build.0 = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.ActiveCfg = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.Build.0 = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x86.ActiveCfg = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x86.Build.0 = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.ActiveCfg = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.Build.0 = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x86.ActiveCfg = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x86.Build.0 = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.ActiveCfg = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.Build.0 = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x86.ActiveCfg = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x86.Build.0 = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.ActiveCfg = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.Build.0 = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x86.ActiveCfg = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x86.Build.0 = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.ActiveCfg = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.Build.0 = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x86.ActiveCfg = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x86.Build.0 = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.ActiveCfg = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.Build.0 = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x86.ActiveCfg = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x86.Build.0 = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.ActiveCfg = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.Build.0 = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x86.ActiveCfg = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x86.Build.0 = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.ActiveCfg = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.Build.0 = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x86.ActiveCfg = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C90E6CC5-818B-4C97-8876-0986D989387C} = {DD2D75A0-EA94-448B-A552-4A68E8336436}
{72C209C4-49A4-4942-A201-44706C9D77EC} = {DD2D75A0-EA94-448B-A552-4A68E8336436}
{BE362AC0-B10B-4276-B84E-6304652BA228} = {DD2D75A0-EA94-448B-A552-4A68E8336436}
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7} = {DD2D75A0-EA94-448B-A552-4A68E8336436}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {03924B69-9775-47B9-9704-9108BBFF7D30}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,183 @@
{
"Resources": {
"FPDemoRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"RoleName": "CF_FleetProvisioningDemoRole",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "iot.amazonaws.com"
}
}
]
},
"ManagedPolicyArns": [
"arn:aws:iam::aws:policy/service-role/AWSIoTThingsRegistration"
]
}
},
"FPDemoThingPolicy": {
"Type": "AWS::IoT::Policy",
"Properties": {
"PolicyName": "CF_FleetProvisioningDemoThingPolicy",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:Connect",
"Resource": {
"Fn::Join": [
":",
[
"arn:aws:iot",
{
"Ref": "AWS::Region"
},
{
"Ref": "AWS::AccountId"
},
"*"
]
]
}
}
]
}
}
},
"FPDemoTemplate": {
"Type": "AWS::IoT::ProvisioningTemplate",
"Properties": {
"TemplateName": "CF_FleetProvisioningDemoTemplate",
"Enabled": "true",
"ProvisioningRoleArn": {
"Fn::Join": [
"",
[
"arn:aws:iam::",
{
"Ref": "AWS::AccountId"
},
":role/",
{
"Ref": "FPDemoRole"
}
]
]
},
"TemplateBody": "{ \"Parameters\": { \"SerialNumber\": { \"Type\": \"String\" }, \"AWS::IoT::Certificate::Id\": { \"Type\": \"String\" } }, \"Resources\": { \"certificate\": { \"Properties\": { \"CertificateId\": { \"Ref\": \"AWS::IoT::Certificate::Id\" }, \"Status\": \"Active\" }, \"Type\": \"AWS::IoT::Certificate\" }, \"policy\": { \"Properties\": { \"PolicyName\": \"CF_FleetProvisioningDemoThingPolicy\" }, \"Type\": \"AWS::IoT::Policy\" }, \"thing\": { \"OverrideSettings\": { \"AttributePayload\": \"MERGE\", \"ThingGroups\": \"DO_NOTHING\" }, \"Properties\": { \"AttributePayload\": {}, \"ThingGroups\": [], \"ThingName\": { \"Fn::Join\": [ \"\", [ \"fp_demo_\", { \"Ref\": \"SerialNumber\" } ] ] } }, \"Type\": \"AWS::IoT::Thing\" } }, \"DeviceConfiguration\": { \"Foo\": \"Bar\" } }"
}
},
"FPDemoClaimPolicy": {
"Type": "AWS::IoT::Policy",
"Properties": {
"PolicyName": "CF_FleetProvisioningDemoClaimPolicy",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"iot:Publish",
"iot:Receive"
],
"Resource": [
{
"Fn::Join": [
"",
[
"arn:aws:iot:",
{
"Ref": "AWS::Region"
},
":",
{
"Ref": "AWS::AccountId"
},
":topic/$aws/certificates/create-from-csr/*"
]
]
},
{
"Fn::Join": [
"",
[
"arn:aws:iot:",
{
"Ref": "AWS::Region"
},
":",
{
"Ref": "AWS::AccountId"
},
":topic/$aws/provisioning-templates/",
{
"Ref": "FPDemoTemplate"
},
"/provision/*"
]
]
}
]
},
{
"Effect": "Allow",
"Action": "iot:Subscribe",
"Resource": [
{
"Fn::Join": [
"",
[
"arn:aws:iot:",
{
"Ref": "AWS::Region"
},
":",
{
"Ref": "AWS::AccountId"
},
":topicfilter/$aws/certificates/create-from-csr/*"
]
]
},
{
"Fn::Join": [
"",
[
"arn:aws:iot:",
{
"Ref": "AWS::Region"
},
":",
{
"Ref": "AWS::AccountId"
},
":topicfilter/$aws/provisioning-templates/",
{
"Ref": "FPDemoTemplate"
},
"/provision/*"
]
]
}
]
}
]
}
}
}
}
}

View File

@ -0,0 +1,68 @@
#!/usr/bin/env python
import os
import argparse
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
KEY_OUT_NAME = f"{os.getcwd()}\\corePKCS11_Claim_Key.dat"
CERT_OUT_NAME = f"{os.getcwd()}\\corePKCS11_Claim_Certificate.dat"
script_file_dir_abs_path = os.path.abspath(os.path.dirname(__file__))
def convert_pem_to_der(cert_pem, key_pem):
# Convert certificate from PEM to DER
key = serialization.load_pem_private_key(
bytes(key_pem, "utf-8"), None, default_backend())
key_der = key.private_bytes(
serialization.Encoding.DER,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption(),
)
with open(f"{KEY_OUT_NAME}", "wb") as key_out:
key_out.write(key_der)
print(
f"Successfully converted key PEM to DER. Output file named: {KEY_OUT_NAME}"
)
cert = x509.load_pem_x509_certificate(
bytes(cert_pem, "utf-8"), default_backend())
with open(f"{CERT_OUT_NAME}", "wb") as cert_out:
cert_out.write(cert.public_bytes(serialization.Encoding.DER))
print(
f"Successfully converted certificate PEM to DER. Output file named: {CERT_OUT_NAME}"
)
def main(args):
with open(args.cert_file, "r") as cert:
cert_pem = cert.read()
with open(args.key_file, "r") as key:
key_pem = key.read()
convert_pem_to_der(cert_pem, key_pem)
if __name__ == "__main__":
arg_parser = argparse.ArgumentParser(
description="This script converts passed in PEM format certificates and keys into the binary DER format."
)
arg_parser.add_argument(
"-c",
"--cert_file",
type=str,
help="Specify the name of the generated certificate file.",
required=True,
)
arg_parser.add_argument(
"-k",
"--key_file",
type=str,
help="Specify the name of the generated key file.",
required=True,
)
args = arg_parser.parse_args()
main(args)

View File

@ -0,0 +1,174 @@
#!/usr/bin/env python
import os
import boto3
import botocore
import argparse
KEY_OUT_NAME = f"{os.getcwd()}\\corePKCS11_Claim_Key.dat"
CERT_OUT_NAME = f"{os.getcwd()}\\corePKCS11_Claim_Certificate.dat"
THING_PRIVATE_KEY_NAME = f"{os.getcwd()}\\corePKCS11_Key.dat"
THING_PUBLIC_KEY_NAME = f"{os.getcwd()}\\corePKCS11_PubKey.dat"
THING_CERT_NAME = f"{os.getcwd()}\\corePKCS11_Certificate.dat"
RESOURCE_STACK_NAME = "FPDemoStack"
cf = boto3.client("cloudformation")
iot = boto3.client("iot")
# Convert a CloudFormation arn into a link to the resource
def convert_cf_arn_to_link(arn):
region = arn.split(":")[3]
return f"https://{region}.console.aws.amazon.com/cloudformation/home?region={region}#/stacks/stackinfo?stackId={arn}"
# Get the CloudFormation stack if it exists - "STACK_NOT_FOUND" otherwise
def get_stack():
try:
response = cf.describe_stacks(StackName=RESOURCE_STACK_NAME)
return response["Stacks"][0]
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "ValidationError":
return "STACK_NOT_FOUND"
raise
# Delete a Thing after clearing it of all certificates
def delete_thing(thing_name):
paginator = iot.get_paginator("list_thing_principals")
list_certificates_iterator = paginator.paginate(
thingName=thing_name
)
for response in list_certificates_iterator:
for certificate_arn in response["principals"]:
iot.detach_thing_principal(
thingName=thing_name,
principal=certificate_arn
)
iot.delete_thing(thingName=thing_name)
# Delete a certificate and all Things attached to it
def delete_certificate_and_things(certificate_arn, policy_name):
paginator = iot.get_paginator("list_principal_things")
list_things_iterator = paginator.paginate(
principal=certificate_arn
)
for response in list_things_iterator:
for thing_name in response["things"]:
delete_thing(thing_name)
iot.detach_policy(
policyName=policy_name,
target=certificate_arn
)
certificate_id = certificate_arn.split("/")[-1]
iot.update_certificate(
certificateId=certificate_id,
newStatus="INACTIVE"
)
iot.delete_certificate(certificateId=certificate_id)
# Delete all resources (including provisioned Things)
def delete_resources():
stack_response = get_stack()
if stack_response == "STACK_NOT_FOUND":
print("Nothing to delete - no Fleet Provisioning resources were found.")
return
# Find all certificates with "CF_FleetProvisioningDemoThingPolicy" attached
print("Deleting certificates and things...")
paginator = iot.get_paginator("list_targets_for_policy")
list_targets_things_iterator = paginator.paginate(
policyName="CF_FleetProvisioningDemoThingPolicy"
)
# Delete all certificates and Things created by this demo
for response in list_targets_things_iterator:
for certificate_arn in response["targets"]:
delete_certificate_and_things(
certificate_arn,
"CF_FleetProvisioningDemoThingPolicy"
)
# Find all certificates with "CF_FleetProvisioningDemoClaimPolicy" attached
paginator = iot.get_paginator("list_targets_for_policy")
list_targets_claim_iterator = paginator.paginate(
policyName="CF_FleetProvisioningDemoClaimPolicy"
)
# Delete all Fleet Provisioning Claim certificates
for response in list_targets_claim_iterator:
for certificate_arn in response["targets"]:
delete_certificate_and_things(
certificate_arn,
"CF_FleetProvisioningDemoClaimPolicy"
)
print("Done.")
print("Fleet Provisioning resource stack deletion started. View the stack in the CloudFormation console here:")
print(convert_cf_arn_to_link(stack_response["StackId"]))
delete_response = cf.delete_stack(
StackName=RESOURCE_STACK_NAME
)
print("Waiting...")
try:
create_waiter = cf.get_waiter("stack_delete_complete")
create_waiter.wait(StackName=RESOURCE_STACK_NAME)
print("Successfully deleted the resources stack.")
except botocore.exceptions.WaiterError as err:
print("Error: Stack deletion failed. Check the CloudFormation link for more information.")
raise
print("All Fleet Provisioning demo resources have been cleaned up.")
# Delete the files created by the demo and reset demo_config.h
def reset_files():
script_file_dir_abs_path = os.path.abspath(os.path.dirname(__file__))
# Remove Claim credentials
if os.path.exists(f"{KEY_OUT_NAME}"):
os.remove(f"{KEY_OUT_NAME}")
if os.path.exists(f"{CERT_OUT_NAME}"):
os.remove(f"{CERT_OUT_NAME}")
# Remove demo-generated Thing credentials
if os.path.exists(f"{THING_PRIVATE_KEY_NAME}"):
os.remove(f"{THING_PRIVATE_KEY_NAME}")
if os.path.exists(f"{THING_PUBLIC_KEY_NAME}"):
os.remove(f"{THING_PUBLIC_KEY_NAME}")
if os.path.exists(f"{THING_CERT_NAME}"):
os.remove(f"{THING_CERT_NAME}")
# Reset demo_config.h
template_file = open(f"{script_file_dir_abs_path}/demo_config_empty.templ", 'r')
file_text = template_file.read()
header_file = open(f"{script_file_dir_abs_path}/../demo_config.h", "w")
header_file.write(file_text)
header_file.close()
template_file.close()
print("Credentials removed and demo_config.h reset.")
# Get arguments
def get_args():
parser = argparse.ArgumentParser(description="Fleet Provisioning Demo setup script.")
parser.add_argument("--force", action="store_true", help="Used to skip the user prompt before executing.")
args = parser.parse_args()
return args
# Parse arguments and execute appropriate functions
def main():
# Check arguments and go appropriately
args = get_args();
print("\nThis script will delete ALL Things, credentials, and resources which were created by demo_setup.py and the Fleet Provisioning demo.")
print("It may take several minutes for all of the resources to be deleted.")
if args.force or input("Are you sure you want to do this? (y/n) ") == "y":
print()
reset_files()
delete_resources()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,238 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#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 "FLEET_PROVISIONING_DEMO"
#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 unique ID used by the demo to differentiate instances.
*
*!!! Please note a #defined constant is used for convenience of demonstration
*!!! only. Production devices can use something unique to the device that can
*!!! be read by software, such as a production serial number, instead of a
*!!! hard coded constant.
*/
#define democonfigFP_DEMO_ID "FPDemoID"__TIME__
/**
* @brief The MQTT client identifier used in this example. Each client identifier
* must be unique so edit as required to ensure no two clients connecting to the
* same broker use the same client identifier.
*
* @note Appending __TIME__ to the client id string will reduce the possibility of a
* client id collision in the broker. Note that the appended time is the compilation
* time. This client id can cause collision, if more than one instance of the same
* binary is used at the same time to connect to the broker.
*/
#ifndef democonfigCLIENT_IDENTIFIER
#define democonfigCLIENT_IDENTIFIER "client"democonfigFP_DEMO_ID
#endif
/**
* @brief Details of the MQTT broker to connect to.
*
* This is the Claim's Rest API Endpoint for AWS IoT.
*
* @note Your AWS IoT Core endpoint can be found in the AWS IoT console under
* Settings/Custom Endpoint, or using the describe-endpoint API.
*
* #define democonfigMQTT_BROKER_ENDPOINT "...insert here..."
*/
#define democonfigMQTT_BROKER_ENDPOINT <IOTEndpoint>
/**
* @brief AWS IoT MQTT broker port number.
*
* In general, port 8883 is for secured MQTT connections.
*
* @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol
* name. When using port 8883, ALPN is not required.
*/
#define democonfigMQTT_BROKER_PORT ( 8883 )
/**
* @brief Server's root CA certificate.
*
* For AWS IoT MQTT broker, this certificate is used to identify the AWS IoT
* server and is publicly available. Refer to the AWS documentation available
* in the link below.
* https://docs.aws.amazon.com/iot/latest/developerguide/server-authentication.html#server-authentication-certs
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigROOT_CA_PEM "...insert here..."
*/
#define democonfigROOT_CA_PEM "-----BEGIN CERTIFICATE-----\n" \
"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \
"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \
"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \
"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \
"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \
"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \
"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \
"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \
"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \
"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \
"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \
"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \
"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \
"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \
"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \
"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \
"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \
"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \
"-----END CERTIFICATE-----\n"
/**
* @brief Name of the provisioning template to use for the RegisterThing
* portion of the Fleet Provisioning workflow.
*
* For information about provisioning templates, see the following AWS documentation:
* https://docs.aws.amazon.com/iot/latest/developerguide/provision-template.html#fleet-provision-template
*
* The example template used for this demo is available in the
* example_demo_template.json file in the DemoSetup directory. In the example,
* replace <provisioned-thing-policy> with the policy provisioned devices
* should have. The demo template uses Fn::Join to construct the Thing name by
* concatenating fp_demo_ and the serial number sent by the demo.
*
* @note The provisioning template MUST be created in AWS IoT before running the
* demo.
*
* @note If you followed the manual setup steps on https://freertos.org/iot-fleet-provisioning/demo.html,
* the provisioning template name is "FleetProvisioningDemoTemplate".
* However, if you used CloudFormation to set up the demo, the template name is "CF_FleetProvisioningDemoTemplate"
*
* #define democonfigPROVISIONING_TEMPLATE_NAME "...insert here..."
*/
#define democonfigPROVISIONING_TEMPLATE_NAME "CF_FleetProvisioningDemoTemplate"
/**
* @brief Subject name to use when creating the certificate signing request (CSR)
* for provisioning the demo client with using the Fleet Provisioning
* CreateCertificateFromCsr APIs.
*
* This is passed to MbedTLS; see https://tls.mbed.org/api/x509__csr_8h.html#a954eae166b125cea2115b7db8c896e90
*/
#ifndef democonfigCSR_SUBJECT_NAME
#define democonfigCSR_SUBJECT_NAME "CN="democonfigFP_DEMO_ID
#endif
/**
* @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.
*
* @note This demo runs on WinSim and the minimal stack size is functional.
* However, if you are porting components of this demo to other platforms,
* the stack size may need to be increased to accommodate the size of the
* buffers used when generating new keys and certificates.
*
*/
#define democonfigDEMO_STACKSIZE configMINIMAL_STACK_SIZE
/**
* @brief Size of the network buffer for MQTT packets. Must be large enough to
* hold the GetCertificateFromCsr response, which, among other things, includes
* a PEM encoded certificate.
*/
#define democonfigNETWORK_BUFFER_SIZE ( 2048U )
/**
* @brief The name of the operating system that the application is running on.
* The current value is given as an example. Please update for your specific
* operating system.
*/
#define democonfigOS_NAME "FreeRTOS"
/**
* @brief The version of the operating system that the application is running
* on. The current value is given as an example. Please update for your specific
* operating system version.
*/
#define democonfigOS_VERSION tskKERNEL_VERSION_NUMBER
/**
* @brief The name of the hardware platform the application is running on. The
* current value is given as an example. Please update for your specific
* hardware platform.
*/
#define democonfigHARDWARE_PLATFORM_NAME "WinSim"
/**
* @brief The name of the MQTT library used and its version, following an "@"
* symbol.
*/
#include "core_mqtt.h" /* Include coreMQTT header for MQTT_LIBRARY_VERSION macro. */
#define democonfigMQTT_LIB "core-mqtt@"MQTT_LIBRARY_VERSION
#endif /* DEMO_CONFIG_H */

View File

@ -0,0 +1,215 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#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 "FLEET_PROVISIONING_DEMO"
#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 unique ID used by the demo to differentiate instances.
*
*!!! Please note a #defined constant is used for convenience of demonstration
*!!! only. Production devices can use something unique to the device that can
*!!! be read by software, such as a production serial number, instead of a
*!!! hard coded constant.
*/
#define democonfigFP_DEMO_ID "FPDemoID"__TIME__
/**
* @brief The MQTT client identifier used in this example. Each client identifier
* must be unique so edit as required to ensure no two clients connecting to the
* same broker use the same client identifier.
*
* @note Appending __TIME__ to the client id string will reduce the possibility of a
* client id collision in the broker. Note that the appended time is the compilation
* time. This client id can cause collision, if more than one instance of the same
* binary is used at the same time to connect to the broker.
*/
#ifndef democonfigCLIENT_IDENTIFIER
#define democonfigCLIENT_IDENTIFIER "client"democonfigFP_DEMO_ID
#endif
/**
* @brief Details of the MQTT broker to connect to.
*
* This is the Claim's Rest API Endpoint for AWS IoT.
*
* @note Your AWS IoT Core endpoint can be found in the AWS IoT console under
* Settings/Custom Endpoint, or using the describe-endpoint API.
*
* #define democonfigMQTT_BROKER_ENDPOINT "...insert here..."
*/
/**
* @brief AWS IoT MQTT broker port number.
*
* In general, port 8883 is for secured MQTT connections.
*
* @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol
* name. When using port 8883, ALPN is not required.
*/
#define democonfigMQTT_BROKER_PORT ( 8883 )
/**
* @brief Server's root CA certificate.
*
* For AWS IoT MQTT broker, this certificate is used to identify the AWS IoT
* server and is publicly available. Refer to the AWS documentation available
* in the link below.
* https://docs.aws.amazon.com/iot/latest/developerguide/server-authentication.html#server-authentication-certs
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigROOT_CA_PEM "...insert here..."
*/
/**
* @brief Name of the provisioning template to use for the RegisterThing
* portion of the Fleet Provisioning workflow.
*
* For information about provisioning templates, see the following AWS documentation:
* https://docs.aws.amazon.com/iot/latest/developerguide/provision-template.html#fleet-provision-template
*
* The example template used for this demo is available in the
* example_demo_template.json file in the DemoSetup directory. In the example,
* replace <provisioned-thing-policy> with the policy provisioned devices
* should have. The demo template uses Fn::Join to construct the Thing name by
* concatenating fp_demo_ and the serial number sent by the demo.
*
* @note The provisioning template MUST be created in AWS IoT before running the
* demo.
*
* @note If you followed the manual setup steps on https://freertos.org/iot-fleet-provisioning/demo.html,
* the provisioning template name is "FleetProvisioningDemoTemplate".
* However, if you used CloudFormation to set up the demo, the template name is "CF_FleetProvisioningDemoTemplate"
*
* #define democonfigPROVISIONING_TEMPLATE_NAME "...insert here..."
*/
/**
* @brief Subject name to use when creating the certificate signing request (CSR)
* for provisioning the demo client with using the Fleet Provisioning
* CreateCertificateFromCsr APIs.
*
* This is passed to MbedTLS; see https://tls.mbed.org/api/x509__csr_8h.html#a954eae166b125cea2115b7db8c896e90
*/
#ifndef democonfigCSR_SUBJECT_NAME
#define democonfigCSR_SUBJECT_NAME "CN="democonfigFP_DEMO_ID
#endif
/**
* @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.
*
* @note This demo runs on WinSim and the minimal stack size is functional.
* However, if you are porting components of this demo to other platforms,
* the stack size may need to be increased to accommodate the size of the
* buffers used when generating new keys and certificates.
*
*/
#define democonfigDEMO_STACKSIZE configMINIMAL_STACK_SIZE
/**
* @brief Size of the network buffer for MQTT packets. Must be large enough to
* hold the GetCertificateFromCsr response, which, among other things, includes
* a PEM encoded certificate.
*/
#define democonfigNETWORK_BUFFER_SIZE ( 2048U )
/**
* @brief The name of the operating system that the application is running on.
* The current value is given as an example. Please update for your specific
* operating system.
*/
#define democonfigOS_NAME "FreeRTOS"
/**
* @brief The version of the operating system that the application is running
* on. The current value is given as an example. Please update for your specific
* operating system version.
*/
#define democonfigOS_VERSION tskKERNEL_VERSION_NUMBER
/**
* @brief The name of the hardware platform the application is running on. The
* current value is given as an example. Please update for your specific
* hardware platform.
*/
#define democonfigHARDWARE_PLATFORM_NAME "WinSim"
/**
* @brief The name of the MQTT library used and its version, following an "@"
* symbol.
*/
#include "core_mqtt.h" /* Include coreMQTT header for MQTT_LIBRARY_VERSION macro. */
#define democonfigMQTT_LIB "core-mqtt@"MQTT_LIBRARY_VERSION
#endif /* DEMO_CONFIG_H */

View File

@ -0,0 +1,132 @@
#!/usr/bin/env python
import os
import argparse
import boto3
import botocore
from convert_credentials_to_der import convert_pem_to_der
KEY_OUT_NAME = f"{os.getcwd()}\\corePKCS11_Claim_Key.dat"
CERT_OUT_NAME = f"{os.getcwd()}\\corePKCS11_Claim_Certificate.dat"
RESOURCE_STACK_NAME = "FPDemoStack"
script_file_dir_abs_path = os.path.abspath(os.path.dirname(__file__))
cf = boto3.client("cloudformation")
iot = boto3.client("iot")
# Convert a CloudFormation arn into a link to the resource
def convert_cf_arn_to_link(arn):
region = arn.split(":")[3]
return f"https://{region}.console.aws.amazon.com/cloudformation/home?region={region}#/stacks/stackinfo?stackId={arn}"
# Get the CloudFormation stack if it exists - "STACK_NOT_FOUND" otherwise
def get_stack():
try:
paginator = cf.get_paginator("describe_stacks")
response_iterator = paginator.paginate(StackName=RESOURCE_STACK_NAME)
for response in response_iterator:
return response["Stacks"][0]
response = cf.describe_stacks(StackName=RESOURCE_STACK_NAME)
return response["Stacks"][0]
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "ValidationError":
return "STACK_NOT_FOUND"
raise
# Create the required resources from the CloudFormation template
def create_resources():
stack_response = get_stack()
if stack_response != "STACK_NOT_FOUND":
print("Fleet Provisioning resource stack already exists with status: " +
stack_response["StackStatus"])
print()
if stack_response["StackStatus"] != "CREATE_COMPLETE":
raise Exception("Fleet Provisioning resource stack failed to create successfully. You may need to delete the stack and retry."
+ "\nView the stack in the CloudFormation console here:\n" + convert_cf_arn_to_link(stack_response["StackId"]))
else:
# Read the cloudformation template file contained in the same directory
cf_template_file = open(f"{script_file_dir_abs_path}/cloudformation_template.json", "r")
cf_template = cf_template_file.read()
cf_template_file.close()
create_response = cf.create_stack(
StackName=RESOURCE_STACK_NAME,
TemplateBody=cf_template,
Capabilities=["CAPABILITY_NAMED_IAM"],
OnFailure="ROLLBACK"
)
print("Stack creation started. View the stack in the CloudFormation console here:")
print(convert_cf_arn_to_link(create_response["StackId"]))
print("Waiting...")
try:
create_waiter = cf.get_waiter("stack_create_complete")
create_waiter.wait(StackName=RESOURCE_STACK_NAME)
print("Successfully created the resources stack.")
except botocore.exceptions.WaiterError as err:
print(
"Error: Stack creation failed. You may need to delete_all and try again.")
raise
# Generate IoT credentials in DER format and save them in the demo directory
def create_credentials():
# Verify that the stack exists (create_resources has been ran before somewhere)
stack_response = get_stack()
if stack_response == "STACK_NOT_FOUND":
raise Exception(
f"CloudFormation stack \"{RESOURCE_STACK_NAME}\" not found.")
elif stack_response["StackStatus"] != "CREATE_COMPLETE":
print("Error: Stack was not successfully created. View the stack in the CloudFormation console here:")
stack_link = convert_cf_arn_to_link(stack_response["StackId"])
raise Exception(
"Stack was not successfully created. View the stack in the CloudFormation console here:\n" + stack_link)
else:
credentials = iot.create_keys_and_certificate(setAsActive=True)
iot.attach_policy(policyName="CF_FleetProvisioningDemoClaimPolicy",
target=credentials["certificateArn"])
convert_pem_to_der(
credentials["certificatePem"], credentials["keyPair"]["PrivateKey"])
# Set the necessary fields in demo_config.h
def update_demo_config():
endpoint = iot.describe_endpoint(endpointType='iot:Data-ATS')
template_file = open(f"{script_file_dir_abs_path}/demo_config.templ", 'r')
file_text = template_file.read()
file_text = file_text.replace(
"<IOTEndpoint>", "\"" + endpoint["endpointAddress"] + "\"")
header_file = open(f"{script_file_dir_abs_path}/../demo_config.h", "w")
header_file.write(file_text)
header_file.close()
template_file.close()
print("Successfully updated demo_config.h")
# Get arguments
def get_args():
parser = argparse.ArgumentParser(description="Fleet Provisioning Demo setup script.")
parser.add_argument("--force", action="store_true", help="Used to skip the user prompt before executing.")
args = parser.parse_args()
return args
# Parse arguments and execute appropriate functions
def main():
# Check arguments and go appropriately
args = get_args();
print("\nThis script will set up the AWS resources required for the Fleet Provisioning demo.")
print("It may take several minutes for the resources to be provisioned.")
if args.force or input("Are you sure you want to do this? (y/n) ") == "y":
print()
create_resources()
create_credentials()
update_demo_config()
print("\nFleet Provisioning demo setup complete. Ensure that all generated files (key, certificate, demo_config.h) are in the same folder as \"fleet_provisioning_demo.sln\".")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,31 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"iot:Publish",
"iot:Receive"
],
"Resource": [
"arn:aws:iot:<aws-region>:<aws-account-id>:topic/$aws/certificates/create-from-csr/*",
"arn:aws:iot:<aws-region>:<aws-account-id>:topic/$aws/provisioning-templates/FleetProvisioningDemoTemplate/provision/*"
]
},
{
"Effect": "Allow",
"Action": "iot:Subscribe",
"Resource": [
"arn:aws:iot:<aws-region>:<aws-account-id>:topicfilter/$aws/certificates/create-from-csr/*",
"arn:aws:iot:<aws-region>:<aws-account-id>:topicfilter/$aws/provisioning-templates/FleetProvisioningDemoTemplate/provision/*"
]
}
]
}

View File

@ -0,0 +1,54 @@
{
"Parameters": {
"SerialNumber": {
"Type": "String"
},
"AWS::IoT::Certificate::Id": {
"Type": "String"
}
},
"Resources": {
"certificate": {
"Properties": {
"CertificateId": {
"Ref": "AWS::IoT::Certificate::Id"
},
"Status": "Active"
},
"Type": "AWS::IoT::Certificate"
},
"policy": {
"Properties": {
"PolicyName": "FleetProvisioningDemoThingPolicy"
},
"Type": "AWS::IoT::Policy"
},
"thing": {
"OverrideSettings": {
"AttributePayload": "MERGE",
"ThingGroups": "DO_NOTHING",
"ThingTypeName": "REPLACE"
},
"Properties": {
"AttributePayload": {},
"ThingGroups": [],
"ThingName": {
"Fn::Join": [
"",
[
"fp_demo_",
{
"Ref": "SerialNumber"
}
]
]
},
"ThingTypeName": "fp_demo_things"
},
"Type": "AWS::IoT::Thing"
}
},
"DeviceConfiguration": {
"Foo": "Bar"
}
}

View File

@ -0,0 +1,10 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:Connect",
"Resource": "arn:aws:iot:<aws-region>:<aws-account-id>:*"
}
]
}

View File

@ -0,0 +1,857 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/*
* Demo for showing use of the Fleet Provisioning library to use the Fleet
* Provisioning feature of AWS IoT Core for provisioning devices with
* credentials. This demo shows how a device can be provisioned with AWS IoT
* Core using the Certificate Signing Request workflow of the Fleet
* Provisioning feature.
*
* The Fleet Provisioning library provides macros and helper functions for
* assembling MQTT topics strings, and for determining whether an incoming MQTT
* message is related to the Fleet Provisioning API of AWS IoT Core. The Fleet
* Provisioning library does not depend on any particular MQTT library,
* therefore the functionality for MQTT operations is placed in another file
* (mqtt_operations.c). This demo uses the coreMQTT library. If needed,
* mqtt_operations.c can be modified to replace coreMQTT with another MQTT
* library. This demo requires using the AWS IoT Core broker as Fleet
* Provisioning is an AWS IoT Core feature.
*
* This demo provisions a device certificate using the provisioning by claim
* workflow with a Certificate Signing Request (CSR). The demo connects to AWS
* IoT Core using provided claim credentials (whose certificate needs to be
* registered with IoT Core before running this demo), subscribes to the
* CreateCertificateFromCsr topics, and obtains a certificate. It then
* subscribes to the RegisterThing topics and activates the certificate and
* obtains a Thing using the provisioning template. Finally, it reconnects to
* AWS IoT Core using the new credentials.
*/
/* Standard includes. */
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
/* Kernel includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Demo Config */
#include "demo_config.h"
/* mbedTLS include for configuring threading functions */
#include "mbedtls/threading.h"
#include "threading_alt.h"
/* TinyCBOR library for CBOR encoding and decoding operations. */
#include "cbor.h"
/* corePKCS11 includes. */
#include "core_pkcs11.h"
#include "core_pkcs11_config.h"
/* AWS IoT Fleet Provisioning Library. */
#include "fleet_provisioning.h"
/* Demo includes. */
#include "mqtt_pkcs11_demo_helpers.h"
#include "pkcs11_operations.h"
#include "tinycbor_serializer.h"
/**
* These configurations are required. Throw compilation error if it is not
* defined.
*/
#ifndef democonfigPROVISIONING_TEMPLATE_NAME
#error "Please define democonfigPROVISIONING_TEMPLATE_NAME to the template name registered with AWS IoT Core in demo_config.h."
#endif
#ifndef democonfigROOT_CA_PEM
#error "Please define Root CA certificate of the MQTT broker(democonfigROOT_CA_PEM) in demo_config.h."
#endif
/**
* @brief The length of #democonfigPROVISIONING_TEMPLATE_NAME.
*/
#define fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ( ( uint16_t ) ( sizeof( democonfigPROVISIONING_TEMPLATE_NAME ) - 1 ) )
/**
* @brief The length of #democonfigFP_DEMO_ID.
*/
#define fpdemoFP_DEMO_ID_LENGTH ( ( uint16_t ) ( sizeof( democonfigFP_DEMO_ID ) - 1 ) )
/**
* @brief Size of AWS IoT Thing name buffer.
*
* See https://docs.aws.amazon.com/iot/latest/apireference/API_CreateThing.html#iot-CreateThing-request-thingName
*/
#define fpdemoMAX_THING_NAME_LENGTH 128
/**
* @brief The maximum number of times to run the loop in this demo.
*
* @note The demo loop is attempted to re-run only if it fails in an iteration.
* Once the demo loop succeeds in an iteration, the demo exits successfully.
*/
#ifndef fpdemoMAX_DEMO_LOOP_COUNT
#define fpdemoMAX_DEMO_LOOP_COUNT ( 3 )
#endif
/**
* @brief Time in seconds to wait between retries of the demo loop if
* demo loop fails.
*/
#define fpdemoDELAY_BETWEEN_DEMO_RETRY_ITERATIONS_SECONDS ( 5 )
/**
* @brief Size of buffer in which to hold the certificate signing request (CSR).
*/
#define fpdemoCSR_BUFFER_LENGTH 2048
/**
* @brief Size of buffer in which to hold the certificate.
*/
#define fpdemoCERT_BUFFER_LENGTH 2048
/**
* @brief Size of buffer in which to hold the certificate id.
*
* See https://docs.aws.amazon.com/iot/latest/apireference/API_Certificate.html#iot-Type-Certificate-certificateId
*/
#define fpdemoCERT_ID_BUFFER_LENGTH 64
/**
* @brief Size of buffer in which to hold the certificate ownership token.
*/
#define fpdemoOWNERSHIP_TOKEN_BUFFER_LENGTH 512
/**
* @brief Milliseconds per second.
*/
#define fpdemoMILLISECONDS_PER_SECOND ( 1000U )
/**
* @brief Milliseconds per FreeRTOS tick.
*/
#define fpdemoMILLISECONDS_PER_TICK ( fpdemoMILLISECONDS_PER_SECOND / configTICK_RATE_HZ )
/**
* @brief Status values of the Fleet Provisioning response.
*/
typedef enum
{
ResponseNotReceived,
ResponseAccepted,
ResponseRejected
} ResponseStatus_t;
/**
* @brief Each compilation unit that consumes the NetworkContext must define it.
* It should contain a single pointer to the type of your desired transport.
* When using multiple transports in the same compilation unit, define this pointer as void *.
*
* @note Transport stacks are defined in FreeRTOS-Plus/Source/Application-Protocols/network_transport.
*/
struct NetworkContext
{
TlsTransportParams_t * pxParams;
};
/*-----------------------------------------------------------*/
/**
* @brief Status reported from the MQTT publish callback.
*/
static ResponseStatus_t xResponseStatus;
/**
* @brief Buffer to hold the provisioned AWS IoT Thing name.
*/
static char pcThingName[ fpdemoMAX_THING_NAME_LENGTH ];
/**
* @brief Length of the AWS IoT Thing name.
*/
static size_t xThingNameLength;
/**
* @brief Buffer to hold responses received from the AWS IoT Fleet Provisioning
* APIs. When the MQTT publish callback receives an expected Fleet Provisioning
* accepted payload, it copies it into this buffer.
*/
static uint8_t pucPayloadBuffer[ democonfigNETWORK_BUFFER_SIZE ];
/**
* @brief Length of the payload stored in #pucPayloadBuffer. This is set by the
* MQTT publish callback when it copies a received payload into #pucPayloadBuffer.
*/
static size_t xPayloadLength;
/**
* @brief The MQTT context used for MQTT operation.
*/
static MQTTContext_t xMqttContext;
/**
* @brief The network context used for mbedTLS operation.
*/
static NetworkContext_t xNetworkContext;
/**
* @brief The parameters for the network context using mbedTLS operation.
*/
static TlsTransportParams_t xTlsTransportParams;
/**
* @brief Static buffer used to hold MQTT messages being sent and received.
*/
static uint8_t ucSharedBuffer[ democonfigNETWORK_BUFFER_SIZE ];
/**
* @brief Static buffer used to hold MQTT messages being sent and received.
*/
static MQTTFixedBuffer_t xBuffer =
{
ucSharedBuffer,
democonfigNETWORK_BUFFER_SIZE
};
/*-----------------------------------------------------------*/
/**
* @brief Callback to receive the incoming publish messages from the MQTT
* broker. Sets xResponseStatus if an expected CreateCertificateFromCsr or
* RegisterThing response is received, and copies the response into
* responseBuffer if the response is an accepted one.
*
* @param[in] pPublishInfo Pointer to publish info of the incoming publish.
* @param[in] usPacketIdentifier Packet identifier of the incoming publish.
*/
static void prvProvisioningPublishCallback( MQTTContext_t * pxMqttContext,
MQTTPacketInfo_t * pxPacketInfo,
MQTTDeserializedInfo_t * pxDeserializedInfo );
/**
* @brief Subscribe to the CreateCertificateFromCsr accepted and rejected topics.
*/
static bool prvSubscribeToCsrResponseTopics( void );
/**
* @brief Unsubscribe from the CreateCertificateFromCsr accepted and rejected topics.
*/
static bool prvUnsubscribeFromCsrResponseTopics( void );
/**
* @brief Subscribe to the RegisterThing accepted and rejected topics.
*/
static bool prvSubscribeToRegisterThingResponseTopics( void );
/**
* @brief Unsubscribe from the RegisterThing accepted and rejected topics.
*/
static bool prvUnsubscribeFromRegisterThingResponseTopics( void );
/**
* @brief The task used to demonstrate the FP API.
*
* This task uses the provided claim key and certificate files to connect to
* AWS and use PKCS #11 to generate a new device key and certificate with a CSR.
* The task then creates a new Thing with the Fleet Provisioning API using the
* newly-created credentials. The task finishes by connecting to the newly-created
* Thing to verify that it was successfully created and accessible using the key/cert.
*
* @param[in] pvParameters Parameters as passed at the time of task creation.
* Not used in this example.
*/
static int prvFleetProvisioningTask( void * pvParameters );
/*-----------------------------------------------------------*/
static void prvProvisioningPublishCallback( MQTTContext_t * pxMqttContext,
MQTTPacketInfo_t * pxPacketInfo,
MQTTDeserializedInfo_t * pxDeserializedInfo )
{
FleetProvisioningStatus_t xStatus;
FleetProvisioningTopic_t xApi;
MQTTPublishInfo_t * pxPublishInfo;
configASSERT( pxMqttContext != NULL );
configASSERT( pxPacketInfo != NULL );
configASSERT( pxDeserializedInfo != NULL );
/* Suppress the unused parameter warning when asserts are disabled in
* build. */
( void ) pxMqttContext;
/* Handle an incoming publish. The lower 4 bits of the publish packet
* type is used for the dup, QoS, and retain flags. Hence masking
* out the lower bits to check if the packet is publish. */
if( ( pxPacketInfo->type & 0xF0U ) == MQTT_PACKET_TYPE_PUBLISH )
{
configASSERT( pxDeserializedInfo->pPublishInfo != NULL );
pxPublishInfo = pxDeserializedInfo->pPublishInfo;
xStatus = FleetProvisioning_MatchTopic(pxPublishInfo->pTopicName,
pxPublishInfo->topicNameLength,
&xApi);
if (xStatus != FleetProvisioningSuccess)
{
LogWarn( ( "Unexpected publish message received. Topic: %.*s.",
( int ) pxPublishInfo->topicNameLength,
( const char * ) pxPublishInfo->pTopicName ) );
}
else
{
if (xApi == FleetProvCborCreateCertFromCsrAccepted)
{
LogInfo( ( "Received accepted response from Fleet Provisioning CreateCertificateFromCsr API." ) );
xResponseStatus = ResponseAccepted;
/* Copy the payload from the MQTT library's buffer to #pucPayloadBuffer. */
( void ) memcpy( ( void * ) pucPayloadBuffer,
( const void * ) pxPublishInfo->pPayload,
( size_t ) pxPublishInfo->payloadLength );
xPayloadLength = pxPublishInfo->payloadLength;
}
else if (xApi == FleetProvCborCreateCertFromCsrRejected)
{
LogError( ( "Received rejected response from Fleet Provisioning CreateCertificateFromCsr API." ) );
xResponseStatus = ResponseRejected;
}
else if (xApi == FleetProvCborRegisterThingAccepted)
{
LogInfo( ( "Received accepted response from Fleet Provisioning RegisterThing API." ) );
xResponseStatus = ResponseAccepted;
/* Copy the payload from the MQTT library's buffer to #pucPayloadBuffer. */
( void ) memcpy( ( void * ) pucPayloadBuffer,
( const void * ) pxPublishInfo->pPayload,
( size_t ) pxPublishInfo->payloadLength );
xPayloadLength = pxPublishInfo->payloadLength;
}
else if (xApi == FleetProvCborRegisterThingRejected)
{
LogError( ( "Received rejected response from Fleet Provisioning RegisterThing API." ) );
xResponseStatus = ResponseRejected;
}
else
{
LogError( ( "Received message on unexpected Fleet Provisioning topic. Topic: %.*s.",
( int ) pxPublishInfo->topicNameLength,
( const char * ) pxPublishInfo->pTopicName ) );
}
}
}
else
{
vHandleOtherIncomingPacket( pxPacketInfo, pxDeserializedInfo->packetIdentifier );
xResponseStatus = ResponseAccepted;
}
}
/*-----------------------------------------------------------*/
static bool prvSubscribeToCsrResponseTopics( void )
{
bool xStatus;
xStatus = xSubscribeToTopic( &xMqttContext,
FP_CBOR_CREATE_CERT_ACCEPTED_TOPIC,
FP_CBOR_CREATE_CERT_ACCEPTED_LENGTH );
if( xStatus == false )
{
LogError( ( "Failed to subscribe to fleet provisioning topic: %.*s.",
FP_CBOR_CREATE_CERT_ACCEPTED_LENGTH,
FP_CBOR_CREATE_CERT_ACCEPTED_TOPIC ) );
}
if( xStatus == true )
{
xStatus = xSubscribeToTopic( &xMqttContext,
FP_CBOR_CREATE_CERT_REJECTED_TOPIC,
FP_CBOR_CREATE_CERT_REJECTED_LENGTH );
if( xStatus == false )
{
LogError( ( "Failed to subscribe to fleet provisioning topic: %.*s.",
FP_CBOR_CREATE_CERT_REJECTED_LENGTH,
FP_CBOR_CREATE_CERT_REJECTED_TOPIC ) );
}
}
return xStatus;
}
/*-----------------------------------------------------------*/
static bool prvUnsubscribeFromCsrResponseTopics( void )
{
bool xStatus;
xStatus = xUnsubscribeFromTopic( &xMqttContext,
FP_CBOR_CREATE_CERT_ACCEPTED_TOPIC,
FP_CBOR_CREATE_CERT_ACCEPTED_LENGTH );
if( xStatus == false )
{
LogError( ( "Failed to unsubscribe from fleet provisioning topic: %.*s.",
FP_CBOR_CREATE_CERT_ACCEPTED_LENGTH,
FP_CBOR_CREATE_CERT_ACCEPTED_TOPIC ) );
}
if( xStatus == true )
{
xStatus = xUnsubscribeFromTopic( &xMqttContext,
FP_CBOR_CREATE_CERT_REJECTED_TOPIC,
FP_CBOR_CREATE_CERT_REJECTED_LENGTH );
if( xStatus == false )
{
LogError( ( "Failed to unsubscribe from fleet provisioning topic: %.*s.",
FP_CBOR_CREATE_CERT_REJECTED_LENGTH,
FP_CBOR_CREATE_CERT_REJECTED_TOPIC ) );
}
}
return xStatus;
}
/*-----------------------------------------------------------*/
static bool prvSubscribeToRegisterThingResponseTopics( void )
{
bool xStatus;
xStatus = xSubscribeToTopic( &xMqttContext,
FP_CBOR_REGISTER_ACCEPTED_TOPIC( democonfigPROVISIONING_TEMPLATE_NAME ),
FP_CBOR_REGISTER_ACCEPTED_LENGTH( fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ) );
if( xStatus == false )
{
LogError( ( "Failed to subscribe to fleet provisioning topic: %.*s.",
FP_CBOR_REGISTER_ACCEPTED_LENGTH( fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ),
FP_CBOR_REGISTER_ACCEPTED_TOPIC( democonfigPROVISIONING_TEMPLATE_NAME ) ) );
}
if( xStatus == true )
{
xStatus = xSubscribeToTopic( &xMqttContext,
FP_CBOR_REGISTER_REJECTED_TOPIC( democonfigPROVISIONING_TEMPLATE_NAME ),
FP_CBOR_REGISTER_REJECTED_LENGTH( fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ) );
if( xStatus == false )
{
LogError( ( "Failed to subscribe to fleet provisioning topic: %.*s.",
FP_CBOR_REGISTER_REJECTED_LENGTH( fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ),
FP_CBOR_REGISTER_REJECTED_TOPIC( democonfigPROVISIONING_TEMPLATE_NAME ) ) );
}
}
return xStatus;
}
/*-----------------------------------------------------------*/
static bool prvUnsubscribeFromRegisterThingResponseTopics( void )
{
bool xStatus;
xStatus = xUnsubscribeFromTopic( &xMqttContext,
FP_CBOR_REGISTER_ACCEPTED_TOPIC( democonfigPROVISIONING_TEMPLATE_NAME ),
FP_CBOR_REGISTER_ACCEPTED_LENGTH( fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ) );
if( xStatus == false )
{
LogError( ( "Failed to unsubscribe from fleet provisioning topic: %.*s.",
FP_CBOR_REGISTER_ACCEPTED_LENGTH( fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ),
FP_CBOR_REGISTER_ACCEPTED_TOPIC( democonfigPROVISIONING_TEMPLATE_NAME ) ) );
}
if( xStatus == true )
{
xStatus = xUnsubscribeFromTopic( &xMqttContext,
FP_CBOR_REGISTER_REJECTED_TOPIC( democonfigPROVISIONING_TEMPLATE_NAME ),
FP_CBOR_REGISTER_REJECTED_LENGTH( fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ) );
if( xStatus == false )
{
LogError( ( "Failed to unsubscribe from fleet provisioning topic: %.*s.",
FP_CBOR_REGISTER_REJECTED_LENGTH( fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ),
FP_CBOR_REGISTER_REJECTED_TOPIC( democonfigPROVISIONING_TEMPLATE_NAME ) ) );
}
}
return xStatus;
}
/*-----------------------------------------------------------*/
/**
* @brief Create the task that demonstrates the Fleet Provisioning library API
*/
void vStartFleetProvisioningDemo()
{
/* This example uses a single application task, which shows that how to use
* Fleet Provisioning library to generate and sign certificates with AWS IoT
* and create new IoT Things using the AWS IoT Fleet Provisioning API */
xTaskCreate( prvFleetProvisioningTask, /* Function that implements the task. */
"DemoTask", /* 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. */
}
/* This example uses a single application task, which shows that how to use
* the Fleet Provisioning library to generate and validate AWS IoT Fleet
* Provisioning MQTT topics, and use the coreMQTT library to communicate with
* the AWS IoT Fleet Provisioning APIs. */
int prvFleetProvisioningTask( void * pvParameters )
{
bool xStatus = false;
/* Buffer for holding the CSR. */
char pcCsr[ fpdemoCSR_BUFFER_LENGTH ] = { 0 };
size_t xCsrLength = 0;
/* Buffer for holding received certificate until it is saved. */
char pcCertificate[ fpdemoCERT_BUFFER_LENGTH ];
size_t xCertificateLength;
/* Buffer for holding the certificate ID. */
char pcCertificateId[ fpdemoCERT_ID_BUFFER_LENGTH ];
size_t xCertificateIdLength;
/* Buffer for holding the certificate ownership token. */
char pcOwnershipToken[ fpdemoOWNERSHIP_TOKEN_BUFFER_LENGTH ];
size_t xOwnershipTokenLength;
bool xConnectionEstablished = false;
CK_SESSION_HANDLE xP11Session;
uint32_t ulDemoRunCount = 0U;
CK_RV xPkcs11Ret = CKR_OK;
/* Silence compiler warnings about unused variables. */
( void ) pvParameters;
/* Set the pParams member of the network context with desired transport. */
xNetworkContext.pxParams = &xTlsTransportParams;
do
{
LogInfo( ( "---------STARTING DEMO---------\r\n" ) );
/* Wait for network to link up. */
if( xPlatformIsNetworkUp() == pdFALSE )
{
LogInfo( ( "Waiting for the network link up event..." ) );
while( xPlatformIsNetworkUp() == pdFALSE )
{
vTaskDelay( pdMS_TO_TICKS( 1000U ) );
}
}
/* Initialize the buffer lengths to their max lengths. */
xCertificateLength = fpdemoCERT_BUFFER_LENGTH;
xCertificateIdLength = fpdemoCERT_ID_BUFFER_LENGTH;
xOwnershipTokenLength = fpdemoOWNERSHIP_TOKEN_BUFFER_LENGTH;
/* Initialize the PKCS #11 module */
xPkcs11Ret = xInitializePkcs11Session( &xP11Session );
if( xPkcs11Ret != CKR_OK )
{
LogError( ( "Failed to initialize PKCS #11." ) );
xStatus = false;
}
else
{
xStatus = xGenerateKeyAndCsr( xP11Session,
pkcs11configLABEL_DEVICE_PRIVATE_KEY_FOR_TLS,
pkcs11configLABEL_DEVICE_PUBLIC_KEY_FOR_TLS,
pcCsr,
fpdemoCSR_BUFFER_LENGTH,
&xCsrLength );
if( xStatus == false )
{
LogError( ( "Failed to generate Key and Certificate Signing Request." ) );
}
xPkcs11CloseSession( xP11Session );
}
/**** Connect to AWS IoT Core with provisioning claim credentials *****/
/* We first use the claim credentials to connect to the broker. These
* credentials should allow use of the RegisterThing API and one of the
* CreateCertificatefromCsr or CreateKeysAndCertificate.
* In this demo we use CreateCertificatefromCsr. */
if( xStatus == true )
{
/* Attempts to connect to the AWS IoT MQTT broker. If the
* connection fails, retries after a timeout. Timeout value will
* exponentially increase until maximum attempts are reached. */
LogInfo( ( "Establishing MQTT session with claim certificate..." ) );
xStatus = xEstablishMqttSession( &xMqttContext,
&xNetworkContext,
&xBuffer,
prvProvisioningPublishCallback,
pkcs11configLABEL_CLAIM_CERTIFICATE,
pkcs11configLABEL_CLAIM_PRIVATE_KEY );
if( xStatus == false )
{
LogError( ( "Failed to establish MQTT session." ) );
}
else
{
LogInfo( ( "Established connection with claim credentials." ) );
xConnectionEstablished = true;
}
}
/**** Call the CreateCertificateFromCsr API ***************************/
/* We use the CreateCertificatefromCsr API to obtain a client certificate
* for a key on the device by means of sending a certificate signing
* request (CSR). */
if( xStatus == true )
{
/* Subscribe to the CreateCertificateFromCsr accepted and rejected
* topics. In this demo we use CBOR encoding for the payloads,
* so we use the CBOR variants of the topics. */
xStatus = prvSubscribeToCsrResponseTopics();
}
if( xStatus == true )
{
/* Create the request payload containing the CSR to publish to the
* CreateCertificateFromCsr APIs. */
xStatus = xGenerateCsrRequest( pucPayloadBuffer,
democonfigNETWORK_BUFFER_SIZE,
pcCsr,
xCsrLength,
&xPayloadLength );
}
if( xStatus == true )
{
/* Publish the CSR to the CreateCertificatefromCsr API. */
xPublishToTopic( &xMqttContext,
FP_CBOR_CREATE_CERT_PUBLISH_TOPIC,
FP_CBOR_CREATE_CERT_PUBLISH_LENGTH,
( char * ) pucPayloadBuffer,
xPayloadLength );
if( xStatus == false )
{
LogError( ( "Failed to publish to fleet provisioning topic: %.*s.",
FP_CBOR_CREATE_CERT_PUBLISH_LENGTH,
FP_CBOR_CREATE_CERT_PUBLISH_TOPIC ) );
}
}
if( xStatus == true )
{
/* From the response, extract the certificate, certificate ID, and
* certificate ownership token. */
xStatus = xParseCsrResponse( pucPayloadBuffer,
xPayloadLength,
pcCertificate,
&xCertificateLength,
pcCertificateId,
&xCertificateIdLength,
pcOwnershipToken,
&xOwnershipTokenLength );
if( xStatus == true )
{
LogInfo( ( "Received certificate with Id: %.*s", ( int ) xCertificateIdLength, pcCertificateId ) );
}
}
if( xStatus == true )
{
/* Save the certificate into PKCS #11. */
xStatus = xLoadCertificate( xP11Session,
pcCertificate,
pkcs11configLABEL_DEVICE_CERTIFICATE_FOR_TLS,
xCertificateLength );
}
if( xStatus == true )
{
/* Unsubscribe from the CreateCertificateFromCsr topics. */
xStatus = prvUnsubscribeFromCsrResponseTopics();
}
/**** Call the RegisterThing API **************************************/
/* We then use the RegisterThing API to activate the received certificate,
* provision AWS IoT resources according to the provisioning template, and
* receive device configuration. */
if( xStatus == true )
{
/* Create the request payload to publish to the RegisterThing API. */
xStatus = xGenerateRegisterThingRequest( pucPayloadBuffer,
democonfigNETWORK_BUFFER_SIZE,
pcOwnershipToken,
xOwnershipTokenLength,
democonfigFP_DEMO_ID,
fpdemoFP_DEMO_ID_LENGTH,
&xPayloadLength );
}
if( xStatus == true )
{
/* Subscribe to the RegisterThing response topics. */
xStatus = prvSubscribeToRegisterThingResponseTopics();
}
if( xStatus == true )
{
/* Publish the RegisterThing request. */
xPublishToTopic( &xMqttContext,
FP_CBOR_REGISTER_PUBLISH_TOPIC( democonfigPROVISIONING_TEMPLATE_NAME ),
FP_CBOR_REGISTER_PUBLISH_LENGTH( fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ),
( char * ) pucPayloadBuffer,
xPayloadLength );
if( xStatus == false )
{
LogError( ( "Failed to publish to fleet provisioning topic: %.*s.",
FP_CBOR_REGISTER_PUBLISH_LENGTH( fpdemoPROVISIONING_TEMPLATE_NAME_LENGTH ),
FP_CBOR_REGISTER_PUBLISH_TOPIC( democonfigPROVISIONING_TEMPLATE_NAME ) ) );
}
}
if( xStatus == true )
{
/* Extract the Thing name from the response. */
xThingNameLength = fpdemoMAX_THING_NAME_LENGTH;
xStatus = xParseRegisterThingResponse( pucPayloadBuffer,
xPayloadLength,
pcThingName,
&xThingNameLength );
if( xStatus == true )
{
LogInfo( ( "Received AWS IoT Thing name: %.*s", ( int ) xThingNameLength, pcThingName ) );
}
}
if( xStatus == true )
{
/* Unsubscribe from the RegisterThing topics. */
prvUnsubscribeFromRegisterThingResponseTopics();
}
/**** Disconnect from AWS IoT Core ************************************/
/* As we have completed the provisioning workflow, we disconnect from
* the connection using the provisioning claim credentials. We will
* establish a new MQTT connection with the newly provisioned
* credentials. */
if( xConnectionEstablished == true )
{
xDisconnectMqttSession( &xMqttContext, &xNetworkContext );
xConnectionEstablished = false;
}
/**** Connect to AWS IoT Core with provisioned certificate ************/
if( xStatus == true )
{
LogInfo( ( "Establishing MQTT session with provisioned certificate..." ) );
xStatus = xEstablishMqttSession( &xMqttContext,
&xNetworkContext,
&xBuffer,
prvProvisioningPublishCallback,
pkcs11configLABEL_DEVICE_CERTIFICATE_FOR_TLS,
pkcs11configLABEL_DEVICE_PRIVATE_KEY_FOR_TLS );
if( xStatus != true )
{
LogError( ( "Failed to establish MQTT session with provisioned "
"credentials. Verify on your AWS account that the "
"new certificate is active and has an attached IoT "
"Policy that allows the \"iot:Connect\" action." ) );
}
else
{
LogInfo( ( "Sucessfully established connection with provisioned credentials." ) );
xConnectionEstablished = true;
}
}
/**** Finish **********************************************************/
if( xConnectionEstablished == true )
{
/* Close the connection. */
xDisconnectMqttSession( &xMqttContext, &xNetworkContext );
xConnectionEstablished = false;
}
/**** Retry in case of failure ****************************************/
/* Increment the demo run count. */
ulDemoRunCount++;
if( xStatus == true )
{
LogInfo( ( "Demo iteration %d is successful.", ulDemoRunCount ) );
}
/* Attempt to retry a failed iteration of demo for up to #fpdemoMAX_DEMO_LOOP_COUNT times. */
else if( ulDemoRunCount < fpdemoMAX_DEMO_LOOP_COUNT )
{
LogWarn( ( "Demo iteration %d failed. Retrying...", ulDemoRunCount ) );
vTaskDelay( fpdemoDELAY_BETWEEN_DEMO_RETRY_ITERATIONS_SECONDS );
}
/* Failed all #fpdemoMAX_DEMO_LOOP_COUNT demo iterations. */
else
{
LogError( ( "All %d demo iterations failed.", fpdemoMAX_DEMO_LOOP_COUNT ) );
break;
}
} while( xStatus != true );
/* Log demo success. */
if( xStatus == true )
{
LogInfo( ( "Demo completed successfully." ) );
LogInfo( ( "-------DEMO FINISHED-------\r\n" ) );
}
/* Delete this task. */
LogInfo( ( "Deleting Fleet Provisioning Demo task." ) );
vTaskDelete( NULL );
return ( xStatus == true ) ? EXIT_SUCCESS : EXIT_FAILURE;
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,95 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef CORE_MQTT_CONFIG_H
#define CORE_MQTT_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 MQTT.
* 3. Include the header file "logging_stack.h", if logging is enabled for MQTT.
*/
#include "logging_levels.h"
/* Logging configuration for the MQTT library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "MQTT"
#endif
#ifndef LIBRARY_LOG_LEVEL
#define LIBRARY_LOG_LEVEL LOG_WARN
#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 Determines the maximum number of MQTT PUBLISH messages, pending
* acknowledgement at a time, that are supported for incoming and outgoing
* direction of messages, separately.
*
* QoS 1 and 2 MQTT PUBLISHes require acknowledgement from the server before
* they can be completed. While they are awaiting the acknowledgement, the
* client must maintain information about their state. The value of this
* macro sets the limit on how many simultaneous PUBLISH states an MQTT
* context maintains, separately, for both incoming and outgoing direction of
* PUBLISHes.
*
* @note The MQTT context maintains separate state records for outgoing
* and incoming PUBLISHes, and thus, 2 * MQTT_STATE_ARRAY_MAX_COUNT amount
* of memory is statically allocated for the state records.
*/
#define MQTT_STATE_ARRAY_MAX_COUNT ( 10U )
/**
* @brief Number of milliseconds to wait for a ping response to a ping
* request as part of the keep-alive mechanism.
*
* If a ping response is not received before this timeout, then
* #MQTT_ProcessLoop will return #MQTTKeepAliveTimeout.
*/
#define MQTT_PINGRESP_TIMEOUT_MS ( 5000U )
#endif /* ifndef CORE_MQTT_CONFIG_H_ */

View File

@ -0,0 +1,215 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#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 "FLEET_PROVISIONING_DEMO"
#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 unique ID used by the demo to differentiate instances.
*
*!!! Please note a #defined constant is used for convenience of demonstration
*!!! only. Production devices can use something unique to the device that can
*!!! be read by software, such as a production serial number, instead of a
*!!! hard coded constant.
*/
#define democonfigFP_DEMO_ID "FPDemoID"__TIME__
/**
* @brief The MQTT client identifier used in this example. Each client identifier
* must be unique so edit as required to ensure no two clients connecting to the
* same broker use the same client identifier.
*
* @note Appending __TIME__ to the client id string will reduce the possibility of a
* client id collision in the broker. Note that the appended time is the compilation
* time. This client id can cause collision, if more than one instance of the same
* binary is used at the same time to connect to the broker.
*/
#ifndef democonfigCLIENT_IDENTIFIER
#define democonfigCLIENT_IDENTIFIER "client"democonfigFP_DEMO_ID
#endif
/**
* @brief Details of the MQTT broker to connect to.
*
* This is the Claim's Rest API Endpoint for AWS IoT.
*
* @note Your AWS IoT Core endpoint can be found in the AWS IoT console under
* Settings/Custom Endpoint, or using the describe-endpoint API.
*
* #define democonfigMQTT_BROKER_ENDPOINT "...insert here..."
*/
/**
* @brief AWS IoT MQTT broker port number.
*
* In general, port 8883 is for secured MQTT connections.
*
* @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol
* name. When using port 8883, ALPN is not required.
*/
#define democonfigMQTT_BROKER_PORT ( 8883 )
/**
* @brief Server's root CA certificate.
*
* For AWS IoT MQTT broker, this certificate is used to identify the AWS IoT
* server and is publicly available. Refer to the AWS documentation available
* in the link below.
* https://docs.aws.amazon.com/iot/latest/developerguide/server-authentication.html#server-authentication-certs
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigROOT_CA_PEM "...insert here..."
*/
/**
* @brief Name of the provisioning template to use for the RegisterThing
* portion of the Fleet Provisioning workflow.
*
* For information about provisioning templates, see the following AWS documentation:
* https://docs.aws.amazon.com/iot/latest/developerguide/provision-template.html#fleet-provision-template
*
* The example template used for this demo is available in the
* example_demo_template.json file in the DemoSetup directory. In the example,
* replace <provisioned-thing-policy> with the policy provisioned devices
* should have. The demo template uses Fn::Join to construct the Thing name by
* concatenating fp_demo_ and the serial number sent by the demo.
*
* @note The provisioning template MUST be created in AWS IoT before running the
* demo.
*
* @note If you followed the manual setup steps on https://freertos.org/iot-fleet-provisioning/demo.html,
* the provisioning template name is "FleetProvisioningDemoTemplate".
* However, if you used CloudFormation to set up the demo, the template name is "CF_FleetProvisioningDemoTemplate"
*
* #define democonfigPROVISIONING_TEMPLATE_NAME "...insert here..."
*/
/**
* @brief Subject name to use when creating the certificate signing request (CSR)
* for provisioning the demo client with using the Fleet Provisioning
* CreateCertificateFromCsr APIs.
*
* This is passed to MbedTLS; see https://tls.mbed.org/api/x509__csr_8h.html#a954eae166b125cea2115b7db8c896e90
*/
#ifndef democonfigCSR_SUBJECT_NAME
#define democonfigCSR_SUBJECT_NAME "CN="democonfigFP_DEMO_ID
#endif
/**
* @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.
*
* @note This demo runs on WinSim and the minimal stack size is functional.
* However, if you are porting components of this demo to other platforms,
* the stack size may need to be increased to accommodate the size of the
* buffers used when generating new keys and certificates.
*
*/
#define democonfigDEMO_STACKSIZE configMINIMAL_STACK_SIZE
/**
* @brief Size of the network buffer for MQTT packets. Must be large enough to
* hold the GetCertificateFromCsr response, which, among other things, includes
* a PEM encoded certificate.
*/
#define democonfigNETWORK_BUFFER_SIZE ( 2048U )
/**
* @brief The name of the operating system that the application is running on.
* The current value is given as an example. Please update for your specific
* operating system.
*/
#define democonfigOS_NAME "FreeRTOS"
/**
* @brief The version of the operating system that the application is running
* on. The current value is given as an example. Please update for your specific
* operating system version.
*/
#define democonfigOS_VERSION tskKERNEL_VERSION_NUMBER
/**
* @brief The name of the hardware platform the application is running on. The
* current value is given as an example. Please update for your specific
* hardware platform.
*/
#define democonfigHARDWARE_PLATFORM_NAME "WinSim"
/**
* @brief The name of the MQTT library used and its version, following an "@"
* symbol.
*/
#include "core_mqtt.h" /* Include coreMQTT header for MQTT_LIBRARY_VERSION macro. */
#define democonfigMQTT_LIB "core-mqtt@"MQTT_LIBRARY_VERSION
#endif /* DEMO_CONFIG_H */

View File

@ -0,0 +1,68 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef FLEET_PROVISIONING_CONFIG_H_
#define FLEET_PROVISIONING_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.
* 3. Include the header file "logging_stack.h".
*/
#include "logging_levels.h"
/* Logging configuration for the Fleet Provisioning library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "FleetProvisioning"
#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 ****************/
#endif /* ifndef FLEET_PROVISIONING_CONFIG_H_ */

View File

@ -0,0 +1,93 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.33027.164
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS-Kernel", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj", "{72C209C4-49A4-4942-A201-44706C9D77EC}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS+TCP", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj", "{C90E6CC5-818B-4C97-8876-0986D989387C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Fleet Provisioning Demo", "fleet_provisioning_demo.vcxproj", "{382DC80F-E278-4BC9-9DB6-59014486DA0F}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Logging", "..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj", "{BE362AC0-B10B-4276-B84E-6304652BA228}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MbedTLS", "..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj", "{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "corePKCS11", "..\..\..\..\VisualStudio_StaticProjects\corePKCS11\corePKCS11.vcxproj", "{19F0FF1A-3368-491A-9932-A2F089508F51}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Statically Linked Libraries", "Statically Linked Libraries", "{1C742BE7-F270-407A-963E-1B83F000D5AD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|Win32.ActiveCfg = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|Win32.Build.0 = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.ActiveCfg = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.Build.0 = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|Win32.ActiveCfg = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|Win32.Build.0 = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.ActiveCfg = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.Build.0 = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|Win32.ActiveCfg = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|Win32.Build.0 = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.ActiveCfg = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.Build.0 = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|Win32.ActiveCfg = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|Win32.Build.0 = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.ActiveCfg = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.Build.0 = Release|x64
{382DC80F-E278-4BC9-9DB6-59014486DA0F}.Debug|Win32.ActiveCfg = Debug|Win32
{382DC80F-E278-4BC9-9DB6-59014486DA0F}.Debug|Win32.Build.0 = Debug|Win32
{382DC80F-E278-4BC9-9DB6-59014486DA0F}.Debug|x64.ActiveCfg = Debug|x64
{382DC80F-E278-4BC9-9DB6-59014486DA0F}.Debug|x64.Build.0 = Debug|x64
{382DC80F-E278-4BC9-9DB6-59014486DA0F}.Release|Win32.ActiveCfg = Release|Win32
{382DC80F-E278-4BC9-9DB6-59014486DA0F}.Release|Win32.Build.0 = Release|Win32
{382DC80F-E278-4BC9-9DB6-59014486DA0F}.Release|x64.ActiveCfg = Release|x64
{382DC80F-E278-4BC9-9DB6-59014486DA0F}.Release|x64.Build.0 = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|Win32.ActiveCfg = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|Win32.Build.0 = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.ActiveCfg = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.Build.0 = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|Win32.ActiveCfg = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|Win32.Build.0 = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.ActiveCfg = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.Build.0 = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|Win32.ActiveCfg = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|Win32.Build.0 = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.ActiveCfg = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.Build.0 = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|Win32.ActiveCfg = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|Win32.Build.0 = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.ActiveCfg = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.Build.0 = Release|x64
{19F0FF1A-3368-491A-9932-A2F089508F51}.Debug|Win32.ActiveCfg = Debug|Win32
{19F0FF1A-3368-491A-9932-A2F089508F51}.Debug|Win32.Build.0 = Debug|Win32
{19F0FF1A-3368-491A-9932-A2F089508F51}.Debug|x64.ActiveCfg = Debug|x64
{19F0FF1A-3368-491A-9932-A2F089508F51}.Debug|x64.Build.0 = Debug|x64
{19F0FF1A-3368-491A-9932-A2F089508F51}.Release|Win32.ActiveCfg = Release|Win32
{19F0FF1A-3368-491A-9932-A2F089508F51}.Release|Win32.Build.0 = Release|Win32
{19F0FF1A-3368-491A-9932-A2F089508F51}.Release|x64.ActiveCfg = Release|x64
{19F0FF1A-3368-491A-9932-A2F089508F51}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{72C209C4-49A4-4942-A201-44706C9D77EC} = {1C742BE7-F270-407A-963E-1B83F000D5AD}
{C90E6CC5-818B-4C97-8876-0986D989387C} = {1C742BE7-F270-407A-963E-1B83F000D5AD}
{BE362AC0-B10B-4276-B84E-6304652BA228} = {1C742BE7-F270-407A-963E-1B83F000D5AD}
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7} = {1C742BE7-F270-407A-963E-1B83F000D5AD}
{19F0FF1A-3368-491A-9932-A2F089508F51} = {1C742BE7-F270-407A-963E-1B83F000D5AD}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3876F3F5-8086-4F8E-BB5E-D8840E7D926C}
EndGlobalSection
GlobalSection(TestCaseManagementSettings) = postSolution
CategoryFile = FreeRTOS_Plus_TCP_Minimal.vsmdi
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,237 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{382dc80f-e278-4bc9-9db6-59014486da0f}</ProjectGuid>
<RootNamespace>corePKCS11_MQTT_Mutual_Auth</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<ProjectName>Fleet Provisioning Demo</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);.;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\AWS\fleet-provisioning\source\include;..\..\Mqtt_Demo_Helpers;$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);.;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\AWS\fleet-provisioning\source\include;..\..\Mqtt_Demo_Helpers;$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);.;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\AWS\fleet-provisioning\source\include;..\..\Mqtt_Demo_Helpers;$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath);.;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\AWS\fleet-provisioning\source\include;..\..\Mqtt_Demo_Helpers;$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Label="Vcpkg">
<VcpkgEnabled>false</VcpkgEnabled>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>
</AdditionalIncludeDirectories>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>
</AdditionalIncludeDirectories>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";_CRT_SECURE_NO_WARNINGS;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>
</AdditionalIncludeDirectories>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";_CRT_SECURE_NO_WARNINGS;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>
</AdditionalIncludeDirectories>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_pk_pkcs11.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_rng_pkcs11.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls_pkcs11.c" />
<ClCompile Include="..\..\..\..\Source\AWS\fleet-provisioning\source\fleet_provisioning.c" />
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder_close_container_checked.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder_float.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborerrorstrings.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser_dup_string.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser_float.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborvalidation.c" />
<ClCompile Include="..\..\Mqtt_Demo_Helpers\mqtt_pkcs11_demo_helpers.c" />
<ClCompile Include="FleetProvisioningDemoExample.c" />
<ClCompile Include="main.c" />
<ClCompile Include="pkcs11_operations.c" />
<ClCompile Include="tinycbor_serializer.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_pkcs11.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls_pkcs11.h" />
<ClInclude Include="..\..\..\..\Source\AWS\fleet-provisioning\source\include\fleet_provisioning.h" />
<ClInclude Include="..\..\..\..\Source\AWS\fleet-provisioning\source\include\fleet_provisioning_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cbor.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborinternal_p.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborjson.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\compilersupport_p.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\tinycbor-version.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\utf8_p.h" />
<ClInclude Include="..\..\Mqtt_Demo_Helpers\mqtt_pkcs11_demo_helpers.h" />
<ClInclude Include="core_mqtt_config.h" />
<ClInclude Include="demo_config.h" />
<ClInclude Include="fleet_provisioning_config.h" />
<ClInclude Include="pkcs11_operations.h" />
<ClInclude Include="tinycbor_serializer.h" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\corePKCS11\corePKCS11.vcxproj">
<Project>{19f0ff1a-3368-491a-9932-a2f089508f51}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj">
<Project>{c90e6cc5-818b-4c97-8876-0986d989387c}</Project>
<Private>false</Private>
<UseLibraryDependencyInputs>false</UseLibraryDependencyInputs>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj">
<Project>{72c209c4-49a4-4942-a201-44706c9d77ec}</Project>
<Private>false</Private>
<UseLibraryDependencyInputs>false</UseLibraryDependencyInputs>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj">
<Project>{be362ac0-b10b-4276-b84e-6304652ba228}</Project>
<Private>false</Private>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj">
<Project>{e1016f3e-94e9-4864-9fd8-1d7c1fefbfd7}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,204 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source">
<UniqueIdentifier>{546ab88a-56ee-4b6f-ac35-b7b63f49ed2f}</UniqueIdentifier>
</Filter>
<Filter Include="Headers">
<UniqueIdentifier>{9049e888-7797-4792-90cb-a1e9e99a92a8}</UniqueIdentifier>
</Filter>
<Filter Include="Config">
<UniqueIdentifier>{2eaca890-15c6-49a3-be88-574abbba0157}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries">
<UniqueIdentifier>{78540744-1e91-4c12-965c-884a2cf92949}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files">
<UniqueIdentifier>{9a6a66e0-e0cf-4ffe-9398-a23f26d3d5bb}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper">
<UniqueIdentifier>{653c873b-f2f7-4848-8db4-4ab67957f4b0}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\include">
<UniqueIdentifier>{56bfdc25-748a-4c0a-a017-1daca6f2b698}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + PKCS11 + MbedTLS Transport">
<UniqueIdentifier>{874d75af-778f-41a1-89dc-076ebf276fea}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + PKCS11 + MbedTLS Transport\include">
<UniqueIdentifier>{1b25efaf-5b58-403c-9308-b591c4061c9e}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports">
<UniqueIdentifier>{a8fad8ec-9a5d-42f0-9b8b-4166cca11354}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports\freertos_plus_tcp">
<UniqueIdentifier>{17955057-1e46-42cb-aa73-a6eb46abc9f5}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT">
<UniqueIdentifier>{c69eabd6-7eed-4959-9351-41b8c3b731b8}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\include">
<UniqueIdentifier>{64a78119-97f6-4252-b793-87cb6e7902d1}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm">
<UniqueIdentifier>{a442e1bd-e141-45a4-860d-a8eccab1b8c2}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\TinyCBOR">
<UniqueIdentifier>{58f51daa-dd72-4e9c-939d-3113f97234ca}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT Fleet Provisioning">
<UniqueIdentifier>{00849fd3-96f4-4fc3-b84f-fab958b5d5b6}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT Fleet Provisioning\include">
<UniqueIdentifier>{9b4954c3-1f90-4e61-bdc1-15e50cbec10a}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm\include">
<UniqueIdentifier>{881fa2ff-3816-405f-9906-1f34585f7341}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c">
<Filter>Additional Libraries\Backoff Algorithm</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborvalidation.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder_close_container_checked.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder_float.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborerrorstrings.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser_dup_string.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser_float.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="tinycbor_serializer.c">
<Filter>Source</Filter>
</ClCompile>
<ClCompile Include="..\..\Mqtt_Demo_Helpers\mqtt_pkcs11_demo_helpers.c">
<Filter>Source</Filter>
</ClCompile>
<ClCompile Include="FleetProvisioningDemoExample.c">
<Filter>Source</Filter>
</ClCompile>
<ClCompile Include="pkcs11_operations.c">
<Filter>Source</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_pk_pkcs11.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + PKCS11 + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_rng_pkcs11.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + PKCS11 + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls_pkcs11.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + PKCS11 + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\ports\freertos_plus_tcp</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + PKCS11 + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\fleet-provisioning\source\fleet_provisioning.c">
<Filter>Additional Libraries\AWS IoT Fleet Provisioning</Filter>
</ClCompile>
<ClCompile Include="main.c">
<Filter>Source</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cbor.h">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborinternal_p.h">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborjson.h">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\compilersupport_p.h">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\tinycbor-version.h">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\utf8_p.h">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClInclude>
<ClInclude Include="core_mqtt_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="demo_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="fleet_provisioning_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="pkcs11_operations.h">
<Filter>Headers</Filter>
</ClInclude>
<ClInclude Include="tinycbor_serializer.h">
<Filter>Headers</Filter>
</ClInclude>
<ClInclude Include="..\..\Mqtt_Demo_Helpers\mqtt_pkcs11_demo_helpers.h">
<Filter>Headers</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_pkcs11.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + PKCS11 + MbedTLS Transport\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls_pkcs11.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + PKCS11 + MbedTLS Transport\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + PKCS11 + MbedTLS Transport\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\fleet-provisioning\source\include\fleet_provisioning.h">
<Filter>Additional Libraries\AWS IoT Fleet Provisioning\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\fleet-provisioning\source\include\fleet_provisioning_config_defaults.h">
<Filter>Additional Libraries\AWS IoT Fleet Provisioning\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h">
<Filter>Additional Libraries\Backoff Algorithm\include</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,84 @@
/*
* FreeRTOS V202212.01
* 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/iot-fleet-provisioning for configuration and usage instructions.
***/
/* Standard includes. */
#include <stdio.h>
#include <time.h>
#include <stdint.h>
/* Visual studio intrinsics used so the __debugbreak() function is available
* should an assert get hit. */
#include <intrin.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#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"
/*-----------------------------------------------------------*/
extern void vStartFleetProvisioningDemo( void );
/*-----------------------------------------------------------*/
int main( void )
{
vPlatformInitLogging();
vStartFleetProvisioningDemo();
/* Initialize FreeRTOS+TCP */
vPlatformInitIpStack();
/* 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.
*/
for( ; ; )
{
configASSERT( pdFALSE );
}
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,402 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file pkcs11_operations.c
*
* @brief This file provides wrapper functions for PKCS11 operations.
*/
/* Standard includes. */
#include <errno.h>
#include <assert.h>
/* Config include. */
#include "demo_config.h"
/* Interface include. */
#include "pkcs11_operations.h"
/* PKCS #11 include. */
#include "core_pkcs11_config.h"
#include "core_pki_utils.h"
#include "mbedtls_utils.h"
#include "mbedtls_pkcs11.h"
/* MbedTLS include. */
#include "mbedtls/error.h"
#include "mbedtls/oid.h"
#include "mbedtls/pk.h"
#include "mbedtls/sha256.h"
#include "mbedtls/x509_crt.h"
#include "mbedtls/x509_csr.h"
/*-----------------------------------------------------------*/
/**
* @brief Delete the specified crypto object from storage.
*
* @param[in] xSession The PKCS #11 session.
* @param[in] pxPkcsLabelsPtr The list of labels to remove.
* @param[in] pxClass The list of corresponding classes.
* @param[in] xCount The length of #pxPkcsLabelsPtr and #pxClass.
*/
static CK_RV prvDestroyProvidedObjects( CK_SESSION_HANDLE xSession,
CK_BYTE_PTR * pxPkcsLabelsPtr,
CK_OBJECT_CLASS * pxClass,
CK_ULONG xCount );
/**
* @brief Generate a new ECDSA key pair using PKCS #11.
*
* @param[in] xSession The PKCS #11 session.
* @param[in] pcPrivateKeyLabel The label to store the private key.
* @param[in] pcPublicKeyLabel The label to store the public key.
* @param[out] xPrivateKeyHandlePtr The handle of the private key.
* @param[out] xPublicKeyHandlePtr The handle of the public key.
*/
static CK_RV prvGenerateKeyPairEC( CK_SESSION_HANDLE xSession,
const char * pcPrivateKeyLabel,
const char * pcPublicKeyLabel,
CK_OBJECT_HANDLE_PTR xPrivateKeyHandlePtr,
CK_OBJECT_HANDLE_PTR xPublicKeyHandlePtr );
/*-----------------------------------------------------------*/
static CK_RV prvDestroyProvidedObjects( CK_SESSION_HANDLE xSession,
CK_BYTE_PTR * pxPkcsLabelsPtr,
CK_OBJECT_CLASS * pxClass,
CK_ULONG xCount )
{
CK_RV xResult;
CK_FUNCTION_LIST_PTR xFunctionList;
CK_OBJECT_HANDLE xObjectHandle;
CK_BYTE * pxLabelPtr;
CK_ULONG xIndex = 0;
xResult = C_GetFunctionList( &xFunctionList );
if( xResult != CKR_OK )
{
LogError( ( "Could not get a PKCS #11 function pointer." ) );
}
else
{
for( xIndex = 0; xIndex < xCount; xIndex++ )
{
pxLabelPtr = pxPkcsLabelsPtr[ xIndex ];
xResult = xFindObjectWithLabelAndClass( xSession, ( char * ) pxLabelPtr,
strnlen( ( char * ) pxLabelPtr, pkcs11configMAX_LABEL_LENGTH ),
pxClass[ xIndex ], &xObjectHandle );
while( ( xResult == CKR_OK ) && ( xObjectHandle != CK_INVALID_HANDLE ) )
{
xResult = xFunctionList->C_DestroyObject( xSession, xObjectHandle );
/* PKCS #11 allows a module to maintain multiple objects with the same
* label and type. The intent of this loop is to try to delete all of
* them. However, to avoid getting stuck, we won't try to find another
* object of the same label/type if the previous delete failed. */
if( xResult == CKR_OK )
{
xResult = xFindObjectWithLabelAndClass( xSession, ( char * ) pxLabelPtr,
strnlen( ( char * ) pxLabelPtr, pkcs11configMAX_LABEL_LENGTH ),
pxClass[ xIndex ], &xObjectHandle );
}
else
{
break;
}
}
}
}
return xResult;
}
/*-----------------------------------------------------------*/
static CK_RV prvGenerateKeyPairEC( CK_SESSION_HANDLE xSession,
const char * pcPrivateKeyLabel,
const char * pcPublicKeyLabel,
CK_OBJECT_HANDLE_PTR xPrivateKeyHandlePtr,
CK_OBJECT_HANDLE_PTR xPublicKeyHandlePtr )
{
CK_RV xResult;
CK_MECHANISM xMechanism = { CKM_EC_KEY_PAIR_GEN, NULL_PTR, 0 };
CK_FUNCTION_LIST_PTR xFunctionList;
CK_BYTE pxEcParams[] = pkcs11DER_ENCODED_OID_P256; /* prime256v1 */
CK_KEY_TYPE xKeyType = CKK_EC;
CK_BBOOL xTrueObject = CK_TRUE;
CK_ATTRIBUTE pxPublicKeyTemplate[] =
{
{ CKA_KEY_TYPE, NULL /* &keyType */, sizeof( xKeyType ) },
{ CKA_VERIFY, NULL /* &trueObject */, sizeof( xTrueObject ) },
{ CKA_EC_PARAMS, NULL /* ecParams */, sizeof( pxEcParams ) },
{ CKA_LABEL, ( void * ) pcPublicKeyLabel, strnlen( pcPublicKeyLabel, pkcs11configMAX_LABEL_LENGTH )}
};
/* Aggregate initializers must not use the address of an automatic variable. */
pxPublicKeyTemplate[ 0 ].pValue = &xKeyType;
pxPublicKeyTemplate[ 1 ].pValue = &xTrueObject;
pxPublicKeyTemplate[ 2 ].pValue = &pxEcParams;
CK_ATTRIBUTE privateKeyTemplate[] =
{
{ CKA_KEY_TYPE, NULL /* &keyType */, sizeof( xKeyType ) },
{ CKA_TOKEN, NULL /* &trueObject */, sizeof( xTrueObject ) },
{ CKA_PRIVATE, NULL /* &trueObject */, sizeof( xTrueObject ) },
{ CKA_SIGN, NULL /* &trueObject */, sizeof( xTrueObject ) },
{ CKA_LABEL, ( void * ) pcPrivateKeyLabel, strnlen( pcPrivateKeyLabel, pkcs11configMAX_LABEL_LENGTH )}
};
/* Aggregate initializers must not use the address of an automatic variable. */
privateKeyTemplate[ 0 ].pValue = &xKeyType;
privateKeyTemplate[ 1 ].pValue = &xTrueObject;
privateKeyTemplate[ 2 ].pValue = &xTrueObject;
privateKeyTemplate[ 3 ].pValue = &xTrueObject;
xResult = C_GetFunctionList( &xFunctionList );
if( xResult != CKR_OK )
{
LogError( ( "Could not get a PKCS #11 function pointer." ) );
}
else
{
xResult = xFunctionList->C_GenerateKeyPair( xSession,
&xMechanism,
pxPublicKeyTemplate,
sizeof( pxPublicKeyTemplate ) / sizeof( CK_ATTRIBUTE ),
privateKeyTemplate, sizeof( privateKeyTemplate ) / sizeof( CK_ATTRIBUTE ),
xPublicKeyHandlePtr,
xPrivateKeyHandlePtr );
}
return xResult;
}
/*-----------------------------------------------------------*/
bool xGenerateKeyAndCsr( CK_SESSION_HANDLE xP11Session,
const char * pcPrivKeyLabel,
const char * pcPubKeyLabel,
char * pcCsrBuffer,
size_t xCsrBufferLength,
size_t * pxOutCsrLength )
{
CK_OBJECT_HANDLE xPrivKeyHandle;
CK_OBJECT_HANDLE xPubKeyHandle;
CK_RV xPkcs11Ret = CKR_OK;
mbedtls_pk_context xPrivKey;
mbedtls_ecdsa_context xEcdsaContext;
mbedtls_x509write_csr xReq;
int32_t ulMbedtlsRet = -1;
const mbedtls_pk_info_t * pxHeader = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY );
configASSERT( pcPrivKeyLabel != NULL );
configASSERT( pcPubKeyLabel != NULL );
configASSERT( pcCsrBuffer != NULL );
configASSERT( pxOutCsrLength != NULL );
xPkcs11Ret = prvGenerateKeyPairEC( xP11Session,
pcPrivKeyLabel,
pcPubKeyLabel,
&xPrivKeyHandle,
&xPubKeyHandle );
if( xPkcs11Ret == CKR_OK )
{
xPkcs11Ret = xPKCS11_initMbedtlsPkContext( &xPrivKey, xP11Session, xPrivKeyHandle );
}
if( xPkcs11Ret == CKR_OK )
{
mbedtls_x509write_csr_init( &xReq );
mbedtls_x509write_csr_set_md_alg( &xReq, MBEDTLS_MD_SHA256 );
ulMbedtlsRet = mbedtls_x509write_csr_set_key_usage( &xReq, MBEDTLS_X509_KU_DIGITAL_SIGNATURE );
if( ulMbedtlsRet == 0 )
{
ulMbedtlsRet = mbedtls_x509write_csr_set_ns_cert_type( &xReq, MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT );
}
if( ulMbedtlsRet == 0 )
{
ulMbedtlsRet = mbedtls_x509write_csr_set_subject_name( &xReq, democonfigCSR_SUBJECT_NAME );
}
if( ulMbedtlsRet == 0 )
{
mbedtls_x509write_csr_set_key( &xReq, &xPrivKey );
ulMbedtlsRet = mbedtls_x509write_csr_pem( &xReq, ( unsigned char * ) pcCsrBuffer,
xCsrBufferLength, &lMbedCryptoRngCallbackPKCS11,
&xP11Session );
}
mbedtls_x509write_csr_free( &xReq );
mbedtls_pk_free( &xPrivKey );
}
*pxOutCsrLength = strlen( pcCsrBuffer );
return( ulMbedtlsRet == 0 );
}
/*-----------------------------------------------------------*/
bool xLoadCertificate( CK_SESSION_HANDLE xP11Session,
const char * pcCertificate,
const char * pcLabel,
size_t xCertificateLength )
{
PKCS11_CertificateTemplate_t xCertificateTemplate;
CK_OBJECT_CLASS xCertificateClass = CKO_CERTIFICATE;
CK_CERTIFICATE_TYPE xCertificateType = CKC_X_509;
CK_FUNCTION_LIST_PTR xFunctionList = NULL;
CK_RV xResult = CKR_OK;
uint8_t * pucDerObject = NULL;
int32_t ulConversion = 0;
size_t xDerLen = 0;
CK_BBOOL xTokenStorage = CK_TRUE;
CK_BYTE pxSubject[] = "TestSubject";
CK_OBJECT_HANDLE xObjectHandle = CK_INVALID_HANDLE;
configASSERT( pcLabel != NULL );
if( pcCertificate == NULL )
{
LogError( ( "Certificate cannot be null." ) );
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
}
if( xResult == CKR_OK )
{
/* Convert the certificate to DER format from PEM. The DER key should
* be about 3/4 the size of the PEM key, so mallocing the PEM key size
* is sufficient. */
pucDerObject = ( uint8_t * ) malloc( xCertificateLength + 1 );
xDerLen = xCertificateLength + 1;
if( pucDerObject != NULL )
{
ulConversion = convert_pem_to_der( ( unsigned char * ) pcCertificate,
xCertificateLength + 1,
pucDerObject, &xDerLen );
if( 0 != ulConversion )
{
LogError( ( "Failed to convert provided certificate." ) );
xResult = CKR_ARGUMENTS_BAD;
}
}
else
{
LogError( ( "Failed to allocate buffer for converting certificate to DER." ) );
xResult = CKR_HOST_MEMORY;
}
}
if( xResult == CKR_OK )
{
xResult = C_GetFunctionList( &xFunctionList );
if( xResult != CKR_OK )
{
LogError( ( "Could not get a PKCS #11 function pointer." ) );
}
}
if( xResult == CKR_OK )
{
/* Initialize the client certificate template. */
xCertificateTemplate.xObjectClass.type = CKA_CLASS;
xCertificateTemplate.xObjectClass.pValue = &xCertificateClass;
xCertificateTemplate.xObjectClass.ulValueLen = sizeof( xCertificateClass );
xCertificateTemplate.xSubject.type = CKA_SUBJECT;
xCertificateTemplate.xSubject.pValue = pxSubject;
xCertificateTemplate.xSubject.ulValueLen = strlen( ( const char * ) pxSubject );
xCertificateTemplate.xValue.type = CKA_VALUE;
xCertificateTemplate.xValue.pValue = pucDerObject;
xCertificateTemplate.xValue.ulValueLen = xDerLen;
xCertificateTemplate.xLabel.type = CKA_LABEL;
xCertificateTemplate.xLabel.pValue = ( CK_VOID_PTR ) pcLabel;
xCertificateTemplate.xLabel.ulValueLen = strnlen( pcLabel, pkcs11configMAX_LABEL_LENGTH );
xCertificateTemplate.xCertificateType.type = CKA_CERTIFICATE_TYPE;
xCertificateTemplate.xCertificateType.pValue = &xCertificateType;
xCertificateTemplate.xCertificateType.ulValueLen = sizeof( CK_CERTIFICATE_TYPE );
xCertificateTemplate.xTokenObject.type = CKA_TOKEN;
xCertificateTemplate.xTokenObject.pValue = &xTokenStorage;
xCertificateTemplate.xTokenObject.ulValueLen = sizeof( xTokenStorage );
/* Best effort clean-up of the existing object, if it exists. */
prvDestroyProvidedObjects( xP11Session, ( CK_BYTE_PTR * ) &pcLabel, &xCertificateClass, 1 );
/* Create an object using the encoded client certificate. */
LogInfo( ( "Writing certificate into label \"%s\".", pcLabel ) );
xResult = xFunctionList->C_CreateObject( xP11Session,
( CK_ATTRIBUTE_PTR ) &xCertificateTemplate,
sizeof( xCertificateTemplate ) / sizeof( CK_ATTRIBUTE ),
&xObjectHandle );
}
if( pucDerObject != NULL )
{
free( pucDerObject );
}
return( xResult == CKR_OK );
}
/*-----------------------------------------------------------*/
bool xPkcs11CloseSession( CK_SESSION_HANDLE xP11Session )
{
CK_RV xResult = CKR_OK;
CK_FUNCTION_LIST_PTR xFunctionList = NULL;
xResult = C_GetFunctionList( &xFunctionList );
if( xResult == CKR_OK )
{
xResult = xFunctionList->C_CloseSession( xP11Session );
}
if( xResult == CKR_OK )
{
xResult = xFunctionList->C_Finalize( NULL );
}
return( xResult == CKR_OK );
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,85 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef PKCS11_OPERATIONS_H_
#define PKCS11_OPERATIONS_H_
/* Standard includes. */
#include <stdlib.h>
#include <stdbool.h>
/* corePKCS11 include. */
#include "core_pkcs11.h"
/**
* @brief Generate a new public-private key pair in the PKCS #11 module, and
* generate a certificate signing request (CSR) for them.
*
* This device-generated private key and CSR can be used with the
* CreateCertificateFromCsr API of the the Fleet Provisioning feature of AWS IoT
* Core in order to provision a unique client certificate.
*
* @param[in] xP11Session The PKCS #11 session to use.
* @param[in] pcPrivKeyLabel PKCS #11 label for the private key.
* @param[in] pcPubKeyLabel PKCS #11 label for the public key.
* @param[out] pcCsrBuffer The buffer to write the CSR to.
* @param[in] xCsrBufferLength Length of #pcCsrBuffer.
* @param[out] pcOutCsrLength The length of the written CSR.
*
* @return True on success.
*/
bool xGenerateKeyAndCsr( CK_SESSION_HANDLE xP11Session,
const char * pcPrivKeyLabel,
const char * pcPubKeyLabel,
char * pcCsrBuffer,
size_t xCsrBufferLength,
size_t * pcOutCsrLength );
/**
* @brief Save the device client certificate into the PKCS #11 module.
*
* @param[in] xP11Session The PKCS #11 session to use.
* @param[in] pcCertificate The certificate to save.
* @param[in] pcLabel PKCS #11 label for the certificate.
* @param[in] xCertificateLength Length of #pcCertificate.
*
* @return True on success.
*/
bool xLoadCertificate( CK_SESSION_HANDLE xP11Session,
const char * pcCertificate,
const char * pcLabel,
size_t xCertificateLength );
/**
* @brief Close the PKCS #11 session.
*
* @param[in] xP11Session The PKCS #11 session to use.
*
* @return True on success.
*/
bool xPkcs11CloseSession( CK_SESSION_HANDLE xP11Session );
#endif /* ifndef PKCS11_OPERATIONS_H_ */

View File

@ -0,0 +1,380 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/* FreeRTOS includes. */
#include <FreeRTOS.h>
/* TinyCBOR library for CBOR encoding and decoding operations. */
#include "cbor.h"
/* Demo config. */
#include "demo_config.h"
/* AWS IoT Fleet Provisioning Library. */
#include "fleet_provisioning.h"
/* Header include. */
#include "tinycbor_serializer.h"
/*-----------------------------------------------------------*/
bool xGenerateCsrRequest( uint8_t * pucBuffer,
size_t xBufferLength,
const char * pcCsr,
size_t xCsrLength,
size_t * pxOutLengthWritten )
{
CborEncoder xEncoder, xMapEncoder;
CborError xCborRet;
configASSERT( pucBuffer != NULL );
configASSERT( pcCsr != NULL );
configASSERT( pxOutLengthWritten != NULL );
/* For details on the CreateCertificatefromCsr request payload format, see:
* https://docs.aws.amazon.com/iot/latest/developerguide/fleet-provision-api.html#create-cert-csr-request-payload
*/
cbor_encoder_init( &xEncoder, pucBuffer, xBufferLength, 0 );
/* The request document is a map with 1 key value pair. */
xCborRet = cbor_encoder_create_map( &xEncoder, &xMapEncoder, 1 );
if( xCborRet == CborNoError )
{
xCborRet = cbor_encode_text_stringz( &xMapEncoder, "certificateSigningRequest" );
}
if( xCborRet == CborNoError )
{
xCborRet = cbor_encode_text_string( &xMapEncoder, pcCsr, xCsrLength );
}
if( xCborRet == CborNoError )
{
xCborRet = cbor_encoder_close_container( &xEncoder, &xMapEncoder );
}
if( xCborRet == CborNoError )
{
*pxOutLengthWritten = cbor_encoder_get_buffer_size( &xEncoder, ( uint8_t * ) pucBuffer );
}
else
{
LogError( ( "Error during CBOR encoding: %s", cbor_error_string( xCborRet ) ) );
if( ( xCborRet & CborErrorOutOfMemory ) != 0 )
{
LogError( ( "Cannot fit CreateCertificateFromCsr request payload into buffer." ) );
}
}
return( xCborRet == CborNoError );
}
/*-----------------------------------------------------------*/
bool xGenerateRegisterThingRequest( uint8_t * pucBuffer,
size_t xBufferLength,
const char * pcCertificateOwnershipToken,
size_t xCertificateOwnershipTokenLength,
const char * pcSerial,
size_t xSerialLength,
size_t * pxOutLengthWritten )
{
CborEncoder xEncoder, xMapEncoder, xParametersEncoder;
CborError xCborRet;
configASSERT( pucBuffer != NULL );
configASSERT( pcCertificateOwnershipToken != NULL );
configASSERT( pcSerial != NULL );
configASSERT( pxOutLengthWritten != NULL );
/* For details on the RegisterThing request payload format, see:
* https://docs.aws.amazon.com/iot/latest/developerguide/fleet-provision-api.html#register-thing-request-payload
*/
cbor_encoder_init( &xEncoder, pucBuffer, xBufferLength, 0 );
/* The RegisterThing request payload is a map with two keys. */
xCborRet = cbor_encoder_create_map( &xEncoder, &xMapEncoder, 2 );
if( xCborRet == CborNoError )
{
xCborRet = cbor_encode_text_stringz( &xMapEncoder, "certificateOwnershipToken" );
}
if( xCborRet == CborNoError )
{
xCborRet = cbor_encode_text_string( &xMapEncoder, pcCertificateOwnershipToken, xCertificateOwnershipTokenLength );
}
if( xCborRet == CborNoError )
{
xCborRet = cbor_encode_text_stringz( &xMapEncoder, "parameters" );
}
if( xCborRet == CborNoError )
{
/* Parameters in this example is length 1. */
xCborRet = cbor_encoder_create_map( &xMapEncoder, &xParametersEncoder, 1 );
}
if( xCborRet == CborNoError )
{
xCborRet = cbor_encode_text_stringz( &xParametersEncoder, "SerialNumber" );
}
if( xCborRet == CborNoError )
{
xCborRet = cbor_encode_text_string( &xParametersEncoder, pcSerial, xSerialLength );
}
if( xCborRet == CborNoError )
{
xCborRet = cbor_encoder_close_container( &xMapEncoder, &xParametersEncoder );
}
if( xCborRet == CborNoError )
{
xCborRet = cbor_encoder_close_container( &xEncoder, &xMapEncoder );
}
if( xCborRet == CborNoError )
{
*pxOutLengthWritten = cbor_encoder_get_buffer_size( &xEncoder, ( uint8_t * ) pucBuffer );
}
else
{
LogError( ( "Error during CBOR encoding: %s", cbor_error_string( xCborRet ) ) );
if( ( xCborRet & CborErrorOutOfMemory ) != 0 )
{
LogError( ( "Cannot fit RegisterThing request payload into buffer." ) );
}
}
return( xCborRet == CborNoError );
}
/*-----------------------------------------------------------*/
bool xParseCsrResponse( const uint8_t * pucResponse,
size_t xLength,
char * pcCertificateBuffer,
size_t * pxCertificateBufferLength,
char * pcCertificateIdBuffer,
size_t * pxCertificateIdBufferLength,
char * pcOwnershipTokenBuffer,
size_t * pxOwnershipTokenBufferLength )
{
CborError xCborRet;
CborParser xParser;
CborValue xMap;
CborValue xValue;
configASSERT( pucResponse != NULL );
configASSERT( pcCertificateBuffer != NULL );
configASSERT( pxCertificateBufferLength != NULL );
configASSERT( pcCertificateIdBuffer != NULL );
configASSERT( pxCertificateIdBufferLength != NULL );
configASSERT( *pxCertificateIdBufferLength >= 64 );
configASSERT( pcOwnershipTokenBuffer != NULL );
configASSERT( pxOwnershipTokenBufferLength != NULL );
/* For details on the CreateCertificatefromCsr response payload format, see:
* https://docs.aws.amazon.com/iot/latest/developerguide/fleet-provision-api.html#register-thing-response-payload
*/
xCborRet = cbor_parser_init( pucResponse, xLength, 0, &xParser, &xMap );
if( xCborRet != CborNoError )
{
LogError( ( "Error initializing parser for CreateCertificateFromCsr response: %s.", cbor_error_string( xCborRet ) ) );
}
else if( !cbor_value_is_map( &xMap ) )
{
LogError( ( "CreateCertificateFromCsr response is not a valid map container type." ) );
}
else
{
xCborRet = cbor_value_map_find_value( &xMap, "certificatePem", &xValue );
if( xCborRet != CborNoError )
{
LogError( ( "Error searching CreateCertificateFromCsr response: %s.", cbor_error_string( xCborRet ) ) );
}
else if( xValue.type == CborInvalidType )
{
LogError( ( "\"certificatePem\" not found in CreateCertificateFromCsr response." ) );
}
else if( xValue.type != CborTextStringType )
{
LogError( ( "Value for \"certificatePem\" key in CreateCertificateFromCsr response is not a text string type." ) );
}
else
{
xCborRet = cbor_value_copy_text_string( &xValue, pcCertificateBuffer, pxCertificateBufferLength, NULL );
if( xCborRet == CborErrorOutOfMemory )
{
size_t requiredLen = 0;
( void ) cbor_value_calculate_string_length( &xValue, &requiredLen );
LogError( ( "Certificate buffer insufficiently large. Certificate length: %lu", ( unsigned long ) requiredLen ) );
}
else if( xCborRet != CborNoError )
{
LogError( ( "Failed to parse \"certificatePem\" value from CreateCertificateFromCsr response: %s.", cbor_error_string( xCborRet ) ) );
}
}
}
if( xCborRet == CborNoError )
{
xCborRet = cbor_value_map_find_value( &xMap, "certificateId", &xValue );
if( xCborRet != CborNoError )
{
LogError( ( "Error searching CreateCertificateFromCsr response: %s.", cbor_error_string( xCborRet ) ) );
}
else if( xValue.type == CborInvalidType )
{
LogError( ( "\"certificateId\" not found in CreateCertificateFromCsr response." ) );
}
else if( xValue.type != CborTextStringType )
{
LogError( ( "\"certificateId\" is an unexpected type in CreateCertificateFromCsr response." ) );
}
else
{
xCborRet = cbor_value_copy_text_string( &xValue, pcCertificateIdBuffer, pxCertificateIdBufferLength, NULL );
if( xCborRet == CborErrorOutOfMemory )
{
size_t requiredLen = 0;
( void ) cbor_value_calculate_string_length( &xValue, &requiredLen );
LogError( ( "Certificate ID buffer insufficiently large. Certificate ID length: %lu", ( unsigned long ) requiredLen ) );
}
else if( xCborRet != CborNoError )
{
LogError( ( "Failed to parse \"certificateId\" value from CreateCertificateFromCsr response: %s.", cbor_error_string( xCborRet ) ) );
}
}
}
if( xCborRet == CborNoError )
{
xCborRet = cbor_value_map_find_value( &xMap, "certificateOwnershipToken", &xValue );
if( xCborRet != CborNoError )
{
LogError( ( "Error searching CreateCertificateFromCsr response: %s.", cbor_error_string( xCborRet ) ) );
}
else if( xValue.type == CborInvalidType )
{
LogError( ( "\"certificateOwnershipToken\" not found in CreateCertificateFromCsr response." ) );
}
else if( xValue.type != CborTextStringType )
{
LogError( ( "\"certificateOwnershipToken\" is an unexpected type in CreateCertificateFromCsr response." ) );
}
else
{
xCborRet = cbor_value_copy_text_string( &xValue, pcOwnershipTokenBuffer, pxOwnershipTokenBufferLength, NULL );
if( xCborRet == CborErrorOutOfMemory )
{
size_t requiredLen = 0;
( void ) cbor_value_calculate_string_length( &xValue, &requiredLen );
LogError( ( "Certificate ownership token buffer insufficiently large. Certificate ownership token buffer length: %lu", ( unsigned long ) requiredLen ) );
}
else if( xCborRet != CborNoError )
{
LogError( ( "Failed to parse \"certificateOwnershipToken\" value from CreateCertificateFromCsr response: %s.", cbor_error_string( xCborRet ) ) );
}
}
}
return( xCborRet == CborNoError );
}
/*-----------------------------------------------------------*/
bool xParseRegisterThingResponse( const uint8_t * pucResponse,
size_t xLength,
char * pcThingNameBuffer,
size_t * pxThingNameBufferLength )
{
CborError cborRet;
CborParser parser;
CborValue map;
CborValue value;
configASSERT( pucResponse != NULL );
configASSERT( pcThingNameBuffer != NULL );
configASSERT( pxThingNameBufferLength != NULL );
/* For details on the RegisterThing response payload format, see:
* https://docs.aws.amazon.com/iot/latest/developerguide/fleet-provision-api.html#register-thing-response-payload
*/
cborRet = cbor_parser_init( pucResponse, xLength, 0, &parser, &map );
if( cborRet != CborNoError )
{
LogError( ( "Error initializing parser for RegisterThing response: %s.", cbor_error_string( cborRet ) ) );
}
else if( !cbor_value_is_map( &map ) )
{
LogError( ( "RegisterThing response not a map type." ) );
}
else
{
cborRet = cbor_value_map_find_value( &map, "thingName", &value );
if( cborRet != CborNoError )
{
LogError( ( "Error searching RegisterThing response: %s.", cbor_error_string( cborRet ) ) );
}
else if( value.type == CborInvalidType )
{
LogError( ( "\"thingName\" not found in RegisterThing response." ) );
}
else if( value.type != CborTextStringType )
{
LogError( ( "\"thingName\" is an unexpected type in RegisterThing response." ) );
}
else
{
cborRet = cbor_value_copy_text_string( &value, pcThingNameBuffer, pxThingNameBufferLength, NULL );
if( cborRet == CborErrorOutOfMemory )
{
size_t requiredLen = 0;
( void ) cbor_value_calculate_string_length( &value, &requiredLen );
LogError( ( "Thing name buffer insufficiently large. Thing name length: %lu", ( unsigned long ) requiredLen ) );
}
else if( cborRet != CborNoError )
{
LogError( ( "Failed to parse \"thingName\" value from RegisterThing response: %s.", cbor_error_string( cborRet ) ) );
}
}
}
return( cborRet == CborNoError );
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,115 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* This file declares functions for serializing and parsing CBOR encoded Fleet
* Provisioning API payloads.
*/
/* Standard includes. */
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
/**
* @brief Creates the request payload to be published to the
* CreateCertificateFromCsr API in order to request a certificate from AWS IoT
* for the included Certificate Signing Request (CSR).
*
* @param[in] pucBuffer Buffer into which to write the publish request payload.
* @param[in] xBufferLength Length of #pucBuffer.
* @param[in] pcCsr The CSR to include in the request payload.
* @param[in] xCsrLength The length of #pcCsr.
* @param[out] pxOutLengthWritten The length of the publish request payload.
*/
bool xGenerateCsrRequest( uint8_t * pucBuffer,
size_t xBufferLength,
const char * pcCsr,
size_t xCsrLength,
size_t * pxOutLengthWritten );
/**
* @brief Creates the request payload to be published to the RegisterThing API
* in order to activate the provisioned certificate and receive a Thing name.
*
* @param[in] pucBuffer Buffer into which to write the publish request payload.
* @param[in] xBufferLength Length of #buffer.
* @param[in] pcCertificateOwnershipToken The certificate's certificate
* ownership token.
* @param[in] xCertificateOwnershipTokenLength Length of
* #certificateOwnershipToken.
* @param[out] pxOutLengthWritten The length of the publish request payload.
*/
bool xGenerateRegisterThingRequest( uint8_t * pucBuffer,
size_t xBufferLength,
const char * pcCertificateOwnershipToken,
size_t xCertificateOwnershipTokenLength,
const char * pcSerial,
size_t xSerialLength,
size_t * pxOutLengthWritten );
/**
* @brief Extracts the certificate, certificate ID, and certificate ownership
* token from a CreateCertificateFromCsr accepted response. These are copied
* to the provided buffers so that they can outlive the data in the response
* buffer and as CBOR strings may be chunked.
*
* @param[in] pucResponse The response payload.
* @param[in] xLength Length of #pucResponse.
* @param[in] pcCertificateBuffer The buffer to which to write the certificate.
* @param[in,out] pxCertificateBufferLength The length of #pcCertificateBuffer.
* The length written is output here.
* @param[in] pcCertificateIdBuffer The buffer to which to write the certificate
* ID.
* @param[in,out] pxCertificateIdBufferLength The length of
* #pcCertificateIdBuffer. The length written is output here.
* @param[in] pcOwnershipTokenBuffer The buffer to which to write the
* certificate ownership token.
* @param[in,out] pxOwnershipTokenBufferLength The length of
* #pcOwnershipTokenBuffer. The length written is output here.
*/
bool xParseCsrResponse( const uint8_t * pucResponse,
size_t xLength,
char * pcCertificateBuffer,
size_t * pxCertificateBufferLength,
char * pcCertificateIdBuffer,
size_t * pxCertificateIdBufferLength,
char * pcOwnershipTokenBuffer,
size_t * pxOwnershipTokenBufferLength );
/**
* @brief Extracts the Thing name from a RegisterThing accepted response.
*
* @param[in] pucResponse The response document.
* @param[in] xLength Length of #pucResponse.
* @param[in] pcThingNameBuffer The buffer to which to write the Thing name.
* @param[in,out] pxThingNameBufferLength The length of #pcThingNameBuffer. The
* written length is output here.
*/
bool xParseRegisterThingResponse( const uint8_t * pucResponse,
size_t xLength,
char * pcThingNameBuffer,
size_t * pxThingNameBufferLength );

View File

@ -0,0 +1,192 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{9a8fd41d-dd8d-42c0-825a-266aebd15c99}</ProjectGuid>
<RootNamespace>JobsDemo</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\AWS\jobs\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\network_transport;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\AWS\jobs\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\network_transport;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\AWS\jobs\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\network_transport;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>.\;..\..\Mqtt_Demo_Helpers;..\..\..\..\Source\AWS\jobs\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\Application-Protocols\network_transport;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj">
<Project>{c90e6cc5-818b-4c97-8876-0986d989387c}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj">
<Project>{72c209c4-49a4-4942-a201-44706c9d77ec}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj">
<Project>{be362ac0-b10b-4276-b84e-6304652ba228}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj">
<Project>{e1016f3e-94e9-4864-9fd8-1d7c1fefbfd7}</Project>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.c" />
<ClCompile Include="..\..\..\..\Source\AWS\jobs\source\jobs.c" />
<ClCompile Include="..\..\..\..\Source\coreJSON\source\core_json.c" />
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c" />
<ClCompile Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.c" />
<ClCompile Include="DemoTasks\JobsDemoExample.c" />
<ClCompile Include="main.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.h" />
<ClInclude Include="..\..\..\..\Source\AWS\jobs\source\include\jobs.h" />
<ClInclude Include="..\..\..\..\Source\coreJSON\source\include\core_json.h" />
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h" />
<ClInclude Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.h" />
<ClInclude Include="core_mqtt_config.h" />
<ClInclude Include="demo_config.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,153 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="Additional Network Transport Files">
<UniqueIdentifier>{77910aca-8b76-4e4d-b7d4-cfe4e56b5b64}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries">
<UniqueIdentifier>{172d061d-e623-438b-833f-4114ba0abf60}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT Jobs">
<UniqueIdentifier>{7eaed6c6-f58a-45e5-b5ca-deef0173342c}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT Jobs\include">
<UniqueIdentifier>{baa73419-9309-46d4-b6ed-3d45224d160c}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreJSON">
<UniqueIdentifier>{966a910d-f680-4fa5-945d-7549e0f00dcf}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT">
<UniqueIdentifier>{81e3ec32-9c87-43c1-a942-676c8eaf748f}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreJSON\include">
<UniqueIdentifier>{b998bcc8-3228-4f9c-a8b2-cbe089f23a8b}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\include">
<UniqueIdentifier>{84f59601-7949-44e5-936c-eea0c72696fc}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\interface">
<UniqueIdentifier>{a76094d7-35e4-4d25-a0e3-6f5d41918de7}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm">
<UniqueIdentifier>{51f46bf6-a773-4e3f-afc4-edbdb1e64274}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm\include">
<UniqueIdentifier>{be40f75a-0897-4fa0-b167-41164a4b5767}</UniqueIdentifier>
</Filter>
<Filter Include="Config">
<UniqueIdentifier>{3ad3935f-a395-4b93-9d2e-3a8d964a7293}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper">
<UniqueIdentifier>{6f4feeea-d54a-4efd-8c7d-702c02e075eb}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\include">
<UniqueIdentifier>{f0cce363-133c-49e3-b12d-0eecd41ec82c}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport">
<UniqueIdentifier>{50ae4d20-b607-4b93-936c-fc7cc8463930}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include">
<UniqueIdentifier>{ca775260-7b8f-4425-9259-ffa0fd3fac14}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports">
<UniqueIdentifier>{34be0896-d864-4bba-96d0-c6076dbb5c62}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports\freertos_plus_tcp">
<UniqueIdentifier>{3a2cda24-c8a2-4008-9b35-70b14cc6022c}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="DemoTasks\JobsDemoExample.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\jobs\source\jobs.c">
<Filter>Additional Libraries\AWS IoT Jobs</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\coreJSON\source\core_json.c">
<Filter>Additional Libraries\coreJSON</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c">
<Filter>Additional Libraries\Backoff Algorithm</Filter>
</ClCompile>
<ClCompile Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\ports\freertos_plus_tcp</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\..\Source\AWS\jobs\source\include\jobs.h">
<Filter>Additional Libraries\AWS IoT Jobs\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\coreJSON\source\include\core_json.h">
<Filter>Additional Libraries\coreJSON\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h">
<Filter>Additional Libraries\coreMQTT\interface</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h">
<Filter>Additional Libraries\Backoff Algorithm\include</Filter>
</ClInclude>
<ClInclude Include="..\..\Mqtt_Demo_Helpers\mqtt_demo_helpers.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="demo_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="core_mqtt_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\include</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,77 @@
/*
* FreeRTOS V202212.01
* 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://aws.amazon.com/freertos
*/
#ifndef CORE_MQTT_CONFIG_H
#define CORE_MQTT_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 MQTT.
* 3. Include the header file "logging_stack.h", if logging is enabled for MQTT.
*/
#include "logging_levels.h"
/* Logging configuration for the MQTT library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "MQTT"
#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 ****************/
/**
* @brief The maximum number of MQTT PUBLISH messages that may be pending
* acknowledgement at any time.
*
* QoS 1 and 2 MQTT PUBLISHes require acknowledgment from the server before
* they can be completed. While they are awaiting the acknowledgment, the
* client must maintain information about their state. The value of this
* macro sets the limit on how many simultaneous PUBLISH states an MQTT
* context maintains.
*/
#define MQTT_STATE_ARRAY_MAX_COUNT 10U
#endif /* ifndef CORE_MQTT_CONFIG_H */

View File

@ -0,0 +1,232 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef DEMO_CONFIG_H
#define DEMO_CONFIG_H
/* FreeRTOS config include. */
#include "FreeRTOSConfig.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 "JobsDemo"
#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 Thing resource registered on your AWS IoT account to use in the demo.
* A Thing resource is required to communicate with the AWS IoT Jobs service.
*
* @note The Things associated with your AWS account can be found in the
* AWS IoT console under Manage/Things, or using the ListThings REST API (that can
* be called with the AWS CLI command line tool).
*
* #define democonfigTHING_NAME "...insert here..."
*/
/**
* @brief The MQTT client identifier used in this example. Each client identifier
* must be unique so edit as required to ensure no two clients connecting to the
* same broker use the same client identifier.
*
* #define democonfigCLIENT_IDENTIFIER "...insert here..."
*/
/**
* @brief The AWS IoT broker endpoint to connect to in the demo.
*
* @note Your AWS IoT Core endpoint can be found in the AWS IoT console under
* Settings/Custom Endpoint, or using the describe-endpoint REST API (with
* AWS CLI command line tool).
*
* #define democonfigMQTT_BROKER_ENDPOINT "...insert here..."
*/
/**
* @brief The port to use for the demo.
*
* In general, port 8883 is for secured MQTT connections.
*
* @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol
* name. Using ALPN with this demo would require additional changes, including
* setting the `pAlpnProtos` member of the `NetworkCredentials_t` struct before
* forming the TLS connection. When using port 8883, ALPN is not required.
*
* #define democonfigMQTT_BROKER_PORT ( insert here. )
*/
/**
* @brief Root CA certificate of AWS IoT broker.
*
* This certificate is used to identify the AWS IoT server and is publicly
* available. Refer to the link below.
* https://www.amazontrust.com/repository/AmazonRootCA1.pem
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigROOT_CA_PEM "...insert here..."
*/
/**
* @brief Client certificate.
*
* Please refer to the AWS documentation below for details
* regarding client authentication.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigCLIENT_CERTIFICATE_PEM "...insert here..."
*/
/**
* @brief Client's private key.
*
* Please refer to the AWS documentation below for details
* regarding client authentication.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
*
* @note This private key should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN RSA PRIVATE KEY-----\n"\
* "...base64 data...\n"\
* "-----END RSA PRIVATE KEY-----\n"
*
* #define democonfigCLIENT_PRIVATE_KEY_PEM "...insert here..."
*/
/**
* @brief The username value for authenticating client to the MQTT broker when
* username/password based client authentication is used.
*
* Please refer to the AWS IoT documentation below for
* details regarding client authentication with a username and password.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* #define democonfigCLIENT_USERNAME "...insert here..."
*/
/**
* @brief The password value for authenticating client to the MQTT broker when
* username/password based client authentication is used.
*
* Please refer to the AWS IoT documentation below for
* details regarding client authentication with a username and password.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* #define democonfigCLIENT_PASSWORD "...insert here..."
*/
/**
* @brief The name of the operating system that the application is running on.
* The current value is given as an example. Please update for your specific
* operating system.
*/
#define democonfigOS_NAME "FreeRTOS"
/**
* @brief The version of the operating system that the application is running
* on. The current value is given as an example. Please update for your specific
* operating system version.
*/
#define democonfigOS_VERSION tskKERNEL_VERSION_NUMBER
/**
* @brief The name of the hardware platform the application is running on. The
* current value is given as an example. Please update for your specific
* hardware platform.
*/
#define democonfigHARDWARE_PLATFORM_NAME "WinSim"
/**
* @brief The name of the MQTT library used and its version, following an "@"
* symbol.
*/
#include "core_mqtt.h" /* Include coreMQTT header for MQTT_LIBRARY_VERSION macro. */
#define democonfigMQTT_LIB "core-mqtt@"MQTT_LIBRARY_VERSION
/**
* @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
/**
* @brief Size of the network buffer for MQTT packets.
*/
#define democonfigNETWORK_BUFFER_SIZE ( 1024U )
#endif /* DEMO_CONFIG_H */

View File

@ -0,0 +1,79 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31205.134
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Jobs_Demo", "Jobs_Demo.vcxproj", "{9A8FD41D-DD8D-42C0-825A-266AEBD15C99}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS+TCP", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj", "{C90E6CC5-818B-4C97-8876-0986D989387C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS-Kernel", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj", "{72C209C4-49A4-4942-A201-44706C9D77EC}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MbedTLS", "..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj", "{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Logging", "..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj", "{BE362AC0-B10B-4276-B84E-6304652BA228}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Statically Linked Libraries", "Statically Linked Libraries", "{08E4E650-9DDF-4FF4-8DF7-8C6AF2CC51A4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9A8FD41D-DD8D-42C0-825A-266AEBD15C99}.Debug|x64.ActiveCfg = Debug|x64
{9A8FD41D-DD8D-42C0-825A-266AEBD15C99}.Debug|x64.Build.0 = Debug|x64
{9A8FD41D-DD8D-42C0-825A-266AEBD15C99}.Debug|x86.ActiveCfg = Debug|Win32
{9A8FD41D-DD8D-42C0-825A-266AEBD15C99}.Debug|x86.Build.0 = Debug|Win32
{9A8FD41D-DD8D-42C0-825A-266AEBD15C99}.Release|x64.ActiveCfg = Release|x64
{9A8FD41D-DD8D-42C0-825A-266AEBD15C99}.Release|x64.Build.0 = Release|x64
{9A8FD41D-DD8D-42C0-825A-266AEBD15C99}.Release|x86.ActiveCfg = Release|Win32
{9A8FD41D-DD8D-42C0-825A-266AEBD15C99}.Release|x86.Build.0 = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.ActiveCfg = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.Build.0 = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x86.ActiveCfg = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x86.Build.0 = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.ActiveCfg = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.Build.0 = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x86.ActiveCfg = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x86.Build.0 = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.ActiveCfg = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.Build.0 = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x86.ActiveCfg = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x86.Build.0 = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.ActiveCfg = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.Build.0 = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x86.ActiveCfg = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x86.Build.0 = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.ActiveCfg = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.Build.0 = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x86.ActiveCfg = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x86.Build.0 = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.ActiveCfg = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.Build.0 = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x86.ActiveCfg = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x86.Build.0 = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.ActiveCfg = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.Build.0 = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x86.ActiveCfg = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x86.Build.0 = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.ActiveCfg = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.Build.0 = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x86.ActiveCfg = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C90E6CC5-818B-4C97-8876-0986D989387C} = {08E4E650-9DDF-4FF4-8DF7-8C6AF2CC51A4}
{72C209C4-49A4-4942-A201-44706C9D77EC} = {08E4E650-9DDF-4FF4-8DF7-8C6AF2CC51A4}
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7} = {08E4E650-9DDF-4FF4-8DF7-8C6AF2CC51A4}
{BE362AC0-B10B-4276-B84E-6304652BA228} = {08E4E650-9DDF-4FF4-8DF7-8C6AF2CC51A4}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {616AA544-F9F0-4165-82DA-7337B0FF599F}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,95 @@
/*
* FreeRTOS V202212.01
* 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/coremqtt for configuration and usage instructions.
***/
/* Standard includes. */
#include <stdio.h>
#include <time.h>
/* Visual studio intrinsics used so the __debugbreak() function is available
* should an assert get hit. */
#include <intrin.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#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"
/*-----------------------------------------------------------*/
extern void prvJobsDemoTask( void * pvParameters );
extern void vPlatformInitLogging( void );
/*-----------------------------------------------------------*/
int main( void )
{
vPlatformInitLogging();
/*
* This example uses a single application task, which shows that how to
* use Jobs library to generate and validate AWS IoT Jobs service MQTT topics
* via coreMQTT library to communicate with the AWS IoT Jobs service.
*/
xTaskCreate( prvJobsDemoTask, /* Function that implements the task. */
"DemoTask", /* 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. */
/* Initialize the FreeRTOS+TCP Stack */
vPlatformInitIpStack();
/* 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.
*/
for( ; ; )
{
configASSERT( pdFALSE );
}
}
/*-----------------------------------------------------------*/

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,137 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef MQTT_DEMO_HELPERS_H
#define MQTT_DEMO_HELPERS_H
/* MQTT API header. */
#include "core_mqtt.h"
/* Transport interface implementation include header for TLS. */
#include "transport_mbedtls.h"
/**
* @brief Establish a MQTT connection.
*
* @param[in, out] pxMqttContext The memory for the MQTTContext_t that will be used for the
* MQTT connection.
* @param[out] pxNetworkContext The memory for the NetworkContext_t required for the
* MQTT connection.
* @param[in] pxNetworkBuffer The buffer space for initializing the @p pxMqttContext MQTT
* context used in the MQTT connection.
* @param[in] eventCallback The callback function used to receive incoming
* publishes and incoming acks from MQTT library.
*
* @return The status of the final connection attempt.
*/
BaseType_t xEstablishMqttSession( MQTTContext_t * pxMqttContext,
NetworkContext_t * pxNetworkContext,
MQTTFixedBuffer_t * pxNetworkBuffer,
MQTTEventCallback_t eventCallback );
/**
* @brief Handle the incoming packet if it's not related to the device shadow.
*
* @param[in] pxPacketInfo Packet Info pointer for the incoming packet.
* @param[in] usPacketIdentifier Packet identifier of the incoming packet.
*/
void vHandleOtherIncomingPacket( MQTTPacketInfo_t * pxPacketInfo,
uint16_t usPacketIdentifier );
/**
* @brief Close the MQTT connection.
*
* @param[in, out] pxMqttContext The MQTT context for the MQTT connection to close.
* @param[in, out] pxNetworkContext The network context for the TLS session to
* terminate.
*
* @return pdPASS if DISCONNECT was successfully sent;
* pdFAIL otherwise.
*/
BaseType_t xDisconnectMqttSession( MQTTContext_t * pxMqttContext,
NetworkContext_t * pxNetworkContext );
/**
* @brief Subscribe to a MQTT topic filter.
*
* @param[in] pxMqttContext The MQTT context for the MQTT connection.
* @param[in] pcTopicFilter Pointer to the shadow topic buffer.
* @param[in] usTopicFilterLength Indicates the length of the shadow
* topic buffer.
*
* @return pdPASS if SUBSCRIBE was successfully sent;
* pdFAIL otherwise.
*/
BaseType_t xSubscribeToTopic( MQTTContext_t * pxMqttContext,
const char * pcTopicFilter,
uint16_t usTopicFilterLength );
/**
* @brief Sends an MQTT UNSUBSCRIBE to unsubscribe from the shadow
* topic.
*
* @param[in] pxMqttContext The MQTT context for the MQTT connection.
* @param[in] pcTopicFilter Pointer to the MQTT topic filter.
* @param[in] usTopicFilterLength Indicates the length of the topic filter.
*
* @return pdPASS if UNSUBSCRIBE was successfully sent;
* pdFAIL otherwise.
*/
BaseType_t xUnsubscribeFromTopic( MQTTContext_t * pxMqttContext,
const char * pcTopicFilter,
uint16_t usTopicFilterLength );
/**
* @brief Publish a message to a MQTT topic.
*
* @param[in] pxMqttContext The MQTT context for the MQTT connection.
* @param[in] pcTopicFilter Points to the topic.
* @param[in] topicFilterLength The length of the topic.
* @param[in] pcPayload Points to the payload.
* @param[in] payloadLength The length of the payload.
*
* @return pdPASS if PUBLISH was successfully sent;
* pdFAIL otherwise.
*/
BaseType_t xPublishToTopic( MQTTContext_t * pxMqttContext,
const char * pcTopicFilter,
int32_t topicFilterLength,
const char * pcPayload,
size_t payloadLength );
/**
* @brief Invoke the core MQTT library's process loop function.
*
* @param[in] pxMqttContext The MQTT context for the MQTT connection.
* @param[in] ulTimeoutMs Minimum time for the loop to run, if no error occurs.
*
* @return pdPASS if process loop was successful;
* pdFAIL otherwise.
*/
BaseType_t xProcessLoop( MQTTContext_t * pxMqttContext,
uint32_t ulTimeoutMs );
#endif /* ifndef MQTT_DEMO_HELPERS_H */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,141 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef MQTT_PKCS11_DEMO_HELPERS_H
#define MQTT_PKCS11_DEMO_HELPERS_H
/* MQTT API header. */
#include "core_mqtt.h"
/* Transport interface implementation include header for TLS. */
#include "transport_mbedtls_pkcs11.h"
/**
* @brief Establish a MQTT connection.
*
* @param[in, out] pxMqttContext The memory for the MQTTContext_t that will be used for the
* MQTT connection.
* @param[out] pxNetworkContext The memory for the NetworkContext_t required for the
* MQTT connection.
* @param[in] pxNetworkBuffer The buffer space for initializing the @p pxMqttContext MQTT
* context used in the MQTT connection.
* @param[in] eventCallback The callback function used to receive incoming
* publishes and incoming acks from MQTT library.
* @param[in] pcClientCertLabel The client certificate PKCS #11 label to use.
* @param[in] pcPrivateKeyLabel The private key PKCS #11 label for the client certificate.
*
* @return The status of the final connection attempt.
*/
BaseType_t xEstablishMqttSession( MQTTContext_t * pxMqttContext,
NetworkContext_t * pxNetworkContext,
MQTTFixedBuffer_t * pxNetworkBuffer,
MQTTEventCallback_t eventCallback,
char * pcClientCertLabel,
char * pcPrivateKeyLabel );
/**
* @brief Handle the incoming packet if it's not related to the device shadow.
*
* @param[in] pxPacketInfo Packet Info pointer for the incoming packet.
* @param[in] usPacketIdentifier Packet identifier of the incoming packet.
*/
void vHandleOtherIncomingPacket( MQTTPacketInfo_t * pxPacketInfo,
uint16_t usPacketIdentifier );
/**
* @brief Close the MQTT connection.
*
* @param[in, out] pxMqttContext The MQTT context for the MQTT connection to close.
* @param[in, out] pxNetworkContext The network context for the TLS session to
* terminate.
*
* @return pdPASS if DISCONNECT was successfully sent;
* pdFAIL otherwise.
*/
BaseType_t xDisconnectMqttSession( MQTTContext_t * pxMqttContext,
NetworkContext_t * pxNetworkContext );
/**
* @brief Subscribe to a MQTT topic filter.
*
* @param[in] pxMqttContext The MQTT context for the MQTT connection.
* @param[in] pcTopicFilter Pointer to the shadow topic buffer.
* @param[in] usTopicFilterLength Indicates the length of the shadow
* topic buffer.
*
* @return pdPASS if SUBSCRIBE was successfully sent;
* pdFAIL otherwise.
*/
BaseType_t xSubscribeToTopic( MQTTContext_t * pxMqttContext,
const char * pcTopicFilter,
uint16_t usTopicFilterLength );
/**
* @brief Sends an MQTT UNSUBSCRIBE to unsubscribe from the shadow
* topic.
*
* @param[in] pxMqttContext The MQTT context for the MQTT connection.
* @param[in] pcTopicFilter Pointer to the MQTT topic filter.
* @param[in] usTopicFilterLength Indicates the length of the topic filter.
*
* @return pdPASS if UNSUBSCRIBE was successfully sent;
* pdFAIL otherwise.
*/
BaseType_t xUnsubscribeFromTopic( MQTTContext_t * pxMqttContext,
const char * pcTopicFilter,
uint16_t usTopicFilterLength );
/**
* @brief Publish a message to a MQTT topic.
*
* @param[in] pxMqttContext The MQTT context for the MQTT connection.
* @param[in] pcTopicFilter Points to the topic.
* @param[in] topicFilterLength The length of the topic.
* @param[in] pcPayload Points to the payload.
* @param[in] payloadLength The length of the payload.
*
* @return pdPASS if PUBLISH was successfully sent;
* pdFAIL otherwise.
*/
BaseType_t xPublishToTopic( MQTTContext_t * pxMqttContext,
const char * pcTopicFilter,
int32_t topicFilterLength,
const char * pcPayload,
size_t payloadLength );
/**
* @brief Invoke the core MQTT library's process loop function.
*
* @param[in] pxMqttContext The MQTT context for the MQTT connection.
* @param[in] ulTimeoutMs Minimum time for the loop to run, if no error occurs.
*
* @return pdPASS if process loop was successful;
* pdFAIL otherwise.
*/
BaseType_t xProcessLoop( MQTTContext_t * pxMqttContext,
uint32_t ulTimeoutMs );
#endif /* ifndef MQTT_PKCS11_DEMO_HELPERS_H */

View File

@ -0,0 +1,293 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/* Standard includes. */
#include <assert.h>
#include "http_demo_utils.h"
/* Exponential backoff retry include. */
#include "backoff_algorithm.h"
/*-----------------------------------------------------------*/
/**
* @brief The maximum number of retries for network operation with server.
*/
#define RETRY_MAX_ATTEMPTS ( 5U )
/**
* @brief The maximum back-off delay (in milliseconds) for retrying failed
* operation with server.
*/
#define RETRY_MAX_BACKOFF_DELAY_MS ( 5000U )
/**
* @brief The base back-off delay (in milliseconds) to use for network operation
* retry attempts.
*/
#define RETRY_BACKOFF_BASE_MS ( 500U )
/**
* @brief The separator between the "https" scheme and the host in a URL.
*/
#define SCHEME_SEPARATOR "://"
/**
* @brief The length of the "://" separator.
*/
#define SCHEME_SEPARATOR_LEN ( sizeof( SCHEME_SEPARATOR ) - 1 )
/*-----------------------------------------------------------*/
/**
* @brief Each compilation unit that consumes the NetworkContext must define it.
* It should contain a single pointer to the type of your desired transport.
* This utility is used by both TLS and plaintext HTTP demos, so define this pointer as void *.
*
* @note Transport stacks are defined in FreeRTOS-Plus/Source/Application-Protocols/network_transport.
*/
struct NetworkContext
{
void * pParams;
};
/*-----------------------------------------------------------*/
extern UBaseType_t uxRand();
/*-----------------------------------------------------------*/
BaseType_t connectToServerWithBackoffRetries( TransportConnect_t connectFunction,
NetworkContext_t * pxNetworkContext )
{
BaseType_t xReturn = pdFAIL;
/* Status returned by the retry utilities. */
BackoffAlgorithmStatus_t xBackoffAlgStatus = BackoffAlgorithmSuccess;
/* Struct containing the next backoff time. */
BackoffAlgorithmContext_t xReconnectParams;
uint16_t usNextBackoff = 0U;
assert( connectFunction != NULL );
/* Initialize reconnect attempts and interval */
BackoffAlgorithm_InitializeParams( &xReconnectParams,
RETRY_BACKOFF_BASE_MS,
RETRY_MAX_BACKOFF_DELAY_MS,
RETRY_MAX_ATTEMPTS );
/* Attempt to connect to the HTTP server. If connection fails, retry after a
* timeout. The timeout value will exponentially increase until either the
* maximum timeout value is reached or the set number of attempts are
* exhausted.*/
do
{
xReturn = connectFunction( pxNetworkContext );
if( xReturn != pdPASS )
{
/* Generate a random number and calculate backoff value (in milliseconds) for
* the next connection retry.
* Note: It is recommended to seed the random number generator with a device-specific
* entropy source so that possibility of multiple devices retrying failed network operations
* at similar intervals can be avoided. */
xBackoffAlgStatus = BackoffAlgorithm_GetNextBackoff( &xReconnectParams, uxRand(), &usNextBackoff );
if( xBackoffAlgStatus == BackoffAlgorithmSuccess )
{
LogWarn( ( "Connection to the HTTP server failed. "
"Retrying connection with backoff and jitter." ) );
LogInfo( ( "Retry attempt %lu out of maximum retry attempts %lu.",
xReconnectParams.attemptsDone,
RETRY_MAX_ATTEMPTS ) );
}
}
} while( ( xReturn == pdFAIL ) && ( xBackoffAlgStatus == BackoffAlgorithmSuccess ) );
if( xReturn == pdFAIL )
{
LogError( ( "Connection to the server failed, all attempts exhausted." ) );
}
return xReturn;
}
/*-----------------------------------------------------------*/
HTTPStatus_t getUrlPath( const char * pcUrl,
size_t xUrlLen,
const char ** pcPath,
size_t * pxPathLen )
{
HTTPStatus_t xHttpStatus = HTTPSuccess;
const char * pcHostStart = NULL;
const char * pcPathStart = NULL;
size_t xHostLen = 0, i = 0, xPathStartIndex = 0, xPathLen = 0;
if( ( pcUrl == NULL ) || ( pcPath == NULL ) || ( pxPathLen == NULL ) )
{
LogError( ( "NULL parameter passed to getUrlPath()." ) );
xHttpStatus = HTTPInvalidParameter;
}
if( xHttpStatus == HTTPSuccess )
{
xHttpStatus = getUrlAddress( pcUrl, xUrlLen, &pcHostStart, &xHostLen );
}
if( xHttpStatus == HTTPSuccess )
{
/* Search for the start of the path. */
for( i = ( pcHostStart - pcUrl ) + xHostLen; i < xUrlLen; i++ )
{
if( pcUrl[ i ] == '/' )
{
pcPathStart = &pcUrl[ i ];
xPathStartIndex = i;
break;
}
}
if( pcPathStart != NULL )
{
/* The end of the path will be either the start of the query,
* start of the fragment, or end of the URL. If this is an S3
* presigned URL, then there must be a query. */
for( i = xPathStartIndex; i < xUrlLen; i++ )
{
if( pcUrl[ i ] == '?' )
{
break;
}
}
xPathLen = i - xPathStartIndex;
}
if( xPathLen == 0 )
{
LogError( ( "Could not parse path from input URL %.*s",
( int32_t ) xUrlLen,
pcUrl ) );
xHttpStatus = HTTPNoResponse;
}
}
if( xHttpStatus == HTTPSuccess )
{
*pxPathLen = xPathLen;
*pcPath = pcPathStart;
}
if( xHttpStatus != HTTPSuccess )
{
LogError( ( "Error parsing the path from URL %s. Error code: %d",
pcUrl,
xHttpStatus ) );
}
return xHttpStatus;
}
/*-----------------------------------------------------------*/
HTTPStatus_t getUrlAddress( const char * pcUrl,
size_t xUrlLen,
const char ** pcAddress,
size_t * pxAddressLen )
{
HTTPStatus_t xHttpStatus = HTTPSuccess;
const char * pcHostStart = NULL;
const char * pcHostEnd = NULL;
size_t i = 0, xHostLen = 0;
if( ( pcUrl == NULL ) || ( pcAddress == NULL ) || ( pxAddressLen == NULL ) )
{
LogError( ( "NULL parameter passed to getUrlAddress()." ) );
xHttpStatus = HTTPInvalidParameter;
}
if( xHttpStatus == HTTPSuccess )
{
/* Search for the start of the hostname using the "://" separator. */
for( i = 0; i < ( xUrlLen - SCHEME_SEPARATOR_LEN ); i++ )
{
if( strncmp( &( pcUrl[ i ] ), SCHEME_SEPARATOR, SCHEME_SEPARATOR_LEN ) == 0 )
{
pcHostStart = pcUrl + i + SCHEME_SEPARATOR_LEN;
break;
}
}
if( pcHostStart == NULL )
{
LogError( ( "Could not find \"://\" scheme separator in input URL %.*s",
( int32_t ) xUrlLen,
pcUrl ) );
xHttpStatus = HTTPParserInternalError;
}
else
{
/* Search for the end of the hostname assuming that the object path
* is next. Assume that there is no port number as this is used for
* S3 presigned URLs. */
for( pcHostEnd = pcHostStart; pcHostEnd < ( pcUrl + xUrlLen ); pcHostEnd++ )
{
if( *pcHostEnd == '/' )
{
xHostLen = ( size_t ) ( pcHostEnd - pcHostStart );
break;
}
}
}
}
if( xHttpStatus == HTTPSuccess )
{
*pxAddressLen = xHostLen;
if( xHostLen == 0 )
{
LogError( ( "Could not find end of host in input URL %.*s",
( int32_t ) xUrlLen,
pcUrl ) );
xHttpStatus = HTTPNoResponse;
*pcAddress = NULL;
}
else
{
*pcAddress = pcHostStart;
}
}
if( xHttpStatus != HTTPSuccess )
{
LogError( ( "Error parsing the address from URL %s. Error code %d",
pcUrl,
xHttpStatus ) );
}
return xHttpStatus;
}

View File

@ -0,0 +1,127 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef HTTP_DEMO_UTILS_H
#define HTTP_DEMO_UTILS_H
/* Standard includes. */
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
/* Kernel includes. */
#include "FreeRTOS.h"
#include "task.h"
/* HTTP API header. */
#include "core_http_client.h"
/**
* @brief Function pointer for establishing connection to a server.
*
* @param[out] pxNetworkContext Implementation-defined network context.
*
* @return pdFAIL on failure; pdPASS on successful connection.
*/
typedef BaseType_t ( * TransportConnect_t )( NetworkContext_t * pxNetworkContext );
/**
* @brief Connect to a server with reconnection retries.
*
* If connection fails, retry is attempted after a timeout. The timeout value
* will exponentially increase until either the maximum timeout value is reached
* or the set number of attempts are exhausted.
*
* @param[in] connectFunction Function pointer for establishing connection to a
* server.
* @param[out] pxNetworkContext Implementation-defined network context.
*
* @return pdFAIL on failure; pdPASS on successful connection.
*/
BaseType_t connectToServerWithBackoffRetries( TransportConnect_t connectFunction,
NetworkContext_t * pxNetworkContext );
/**
* @brief Retrieve the path from the input URL.
*
* This function retrieves the location and length of the path from within the
* input the URL. The query is not included in the length returned.
*
* The URL MUST start with "http://" or "https://" to find the path.
*
* For example, if pcUrl is:
* "https://www.somewebsite.com/path/to/item.txt?optionalquery=stuff"
*
* Then pcPath and pxPathLen will be the following:
* *pcPath = "/path/to/item.txt?optionalquery=stuff"
* *pxPathLen = 17
*
* @param[in] pcUrl URL string to parse.
* @param[in] xUrlLen The length of the URL string input.
* @param[out] pcPath pointer within input url that the path starts at.
* @param[out] pxPathLen Length of the path.
*
* @return The status of the parsing attempt:
* HTTPSuccess if the path was successfully parsed,
* HTTPParserInternalError if there was an error parsing the URL,
* or HTTPNoResponse if the path was not found.
*/
HTTPStatus_t getUrlPath( const char * pcUrl,
size_t xUrlLen,
const char ** pcPath,
size_t * pxPathLen );
/**
* @brief Retrieve the Address from the input URL.
*
* This function retrieves the location and length of the address from within
* the input URL. The path and query are not included in the length returned.
*
* The URL MUST start with "http://" or "https://" to find the address.
*
* For example, if pcUrl is:
* "https://www.somewebsite.com/path/to/item.txt?optionalquery=stuff"
*
* Then pcAddress and pxAddressLen will be the following:
* *pcAddress = "www.somewebsite.com/path/to/item.txt?optionalquery=stuff"
* *pxAddressLen = 19
*
* @param[in] pcUrl URL string to parse.
* @param[in] xUrlLen The length of the URL string input.
* @param[out] pcAddress pointer within input url that the address starts at.
* @param[out] pxAddressLen Length of the address.
*
* @return The status of the parsing attempt:
* HTTPSuccess if the path was successfully parsed,
* HTTPParserInternalError if there was an error parsing the URL,
* or HTTPNoResponse if the path was not found.
*/
HTTPStatus_t getUrlAddress( const char * pcUrl,
size_t xUrlLen,
const char ** pcAddress,
size_t * pxAddressLen );
#endif /* ifndef HTTP_DEMO_UTILS_H */

View File

@ -0,0 +1,49 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file aws_ota_codesigner_certificate.h
* @brief Code signer certificate as char array.
*
* Define this char array containing the PEM encode signing certificate.
* Note - It is highly recommended to use this for demo purpose and store
* certificates in secure location in production devices.
*/
#ifndef __CODESIGNER_CERTIFICATE__H__
#define __CODESIGNER_CERTIFICATE__H__
/*
* PEM-encoded code signer certificate
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"
* "...base64 data...\n"
* "-----END CERTIFICATE-----\n";
*/
static const char signingcredentialSIGNING_CERTIFICATE_PEM[] = "...Insert here...";
#endif

View File

@ -0,0 +1,45 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file code_signature_verification.h
* @brief Interface for code signature verification functions.
*
*/
#ifndef CODE_SIGNATURE_VERIFICATION_H
#define CODE_SIGNATURE_VERIFICATION_H
#include "FreeRTOS.h"
/**
* @brief Validate the integrity of the new image to be activated.
* @param[in] pFileContext pointer to File context
* @return OtaPalMainStatus_t , OtaPalSuccess if the signature of the image is valid.
*/
OtaPalMainStatus_t xValidateImageSignature( OtaFileContext_t* const pFileContext );
#endif

View File

@ -0,0 +1,465 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file code_signature_verification_mbedtls.c
* @brief Code signature verification using mbedtls crypto.
*
* The file demonstrates implements the code signature verification functionality on
* the specified file using mbedtls for SHA256 ECDSA.
*/
/* C runtime includes. */
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* mbedTLS includes. */
#if !defined( MBEDTLS_CONFIG_FILE )
#include "mbedtls_config_v3.2.1.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "mbedtls/platform.h"
#include "mbedtls/sha256.h"
#include "mbedtls/sha1.h"
#include "mbedtls/pk.h"
#include "mbedtls/x509_crt.h"
/* OTA includes. */
#include "ota.h"
/* Signature verification includes. */
#include "code_signature_verification.h"
#include "aws_ota_codesigner_certificate.h"
/**
* @brief SHA256 buffer size for storing cryptographic hash computation results.
*/
#define SHA256_DIGEST_BYTES 32
/* Size of buffer used in file operations on this platform (Windows). */
#define OTA_PAL_WIN_BUF_SIZE ( ( size_t ) 4096UL )
/**
* @brief Library-independent cryptographic algorithm identifiers.
*/
#define HASH_ALGORITHM_SHA1 1
#define HASH_ALGORITHM_SHA256 2
#define ASYMMETRIC_ALGORITHM_RSA 1
#define ASYMMETRIC_ALGORITHM_ECDSA 2
/**
* @brief Internal signature verification context structure.
*/
typedef struct SignatureVerificationState
{
BaseType_t xAsymmetricAlgorithm;
BaseType_t xHashAlgorithm;
mbedtls_sha256_context xSHA256Context;
} SignatureVerificationState_t, * SignatureVerificationStatePtr_t;
/**
* @brief Initializes digital signature verification.
*
* @param[out] ppvContext Opaque context structure.
* @param[in] xAsymmetricAlgorithm Cryptographic public key cryptosystem.
* @param[in] xHashAlgorithm Cryptographic hash algorithm that was used for signing.
*
* @return pdTRUE if initialization succeeds, or pdFALSE otherwise.
*/
static BaseType_t prvSignatureVerificationStart(void** ppvContext,
BaseType_t xAsymmetricAlgorithm,
BaseType_t xHashAlgorithm);
/**
* @brief Updates a cryptographic hash computation with the specified byte array.
*
* @param[in] pvContext Opaque context structure.
* @param[in] pucData Byte array that was signed.
* @param[in] xDataLength Length in bytes of data that was signed.
*/
static void prvSignatureVerificationUpdate(void* pvContext,
const uint8_t* pucData,
size_t xDataLength);
/**
* @brief Verifies a digital signature computation using the public key from the
* specified certificate.
*
* @param[in] pvContext Opaque context structure.
* @param[in] pucSignerCertificate Base64 and DER encoded X.509 certificate of the
* signer.
* @param[in] xSignerCertificateLength Length in bytes of the certificate.
* @param[in] pucSignature Digital signature result to verify.
* @param[in] xSignatureLength in bytes of digital signature result.
*
* @return pdTRUE if the signature is correct or pdFALSE if the signature is invalid.
*/
static BaseType_t prvSignatureVerificationFinal(void* pvContext,
char* pcSignerCertificate,
size_t xSignerCertificateLength,
uint8_t* pucSignature,
size_t xSignatureLength);
/* Read the specified signer certificate from the filesystem into a local buffer. The allocated
* memory becomes the property of the caller who is responsible for freeing it.
*/
static uint8_t* otaPal_ReadAndAssumeCertificate(const uint8_t* const pucCertName,
uint32_t* const ulSignerCertSize)
{
FILE* pFile;
uint8_t* pucSignerCert = NULL;
uint8_t* pucCertData = NULL;
int32_t lSize = 0; /* For MISRA mandatory. */
int32_t lWindowsError;
pFile = fopen((const char*)pucCertName, "rb"); /*lint !e586
* C standard library call is being used for portability. */
if (pFile != NULL)
{
lWindowsError = fseek(pFile, 0, SEEK_END); /*lint !e586
* C standard library call is being used for portability. */
if (lWindowsError == 0) /* fseek returns a non-zero value on error. */
{
lSize = (int32_t)ftell(pFile); /*lint !e586 Allow call in this context. */
if (lSize != -1L) /* ftell returns -1 on error. */
{
lWindowsError = fseek(pFile, 0, SEEK_SET); /*lint !e586
* C standard library call is being used for portability. */
}
else /* ftell returned an error, pucSignerCert remains NULL. */
{
lWindowsError = -1L;
}
} /* else fseek returned an error, pucSignerCert remains NULL. */
if (lWindowsError == 0)
{
/* Allocate memory for the signer certificate plus a terminating zero so we can load and return it to the caller. */
pucSignerCert = pvPortMalloc(lSize + 1); /*lint !e732 !e9034 !e9079 Allow conversion. */
}
if (pucSignerCert != NULL)
{
if (fread(pucSignerCert, 1, lSize, pFile) == (size_t)lSize) /*lint !e586 !e732 !e9034
* C standard library call is being used for portability. */
{
/* The crypto code requires the terminating zero to be part of the length so add 1 to the size. */
*ulSignerCertSize = lSize + 1;
pucSignerCert[lSize] = 0;
}
else
{ /* There was a problem reading the certificate file so free the memory and abort. */
vPortFree(pucSignerCert);
pucSignerCert = NULL;
}
}
else
{
LogError(("Failed to allocate memory for signer cert contents.\r\n"));
/* Nothing special to do. */
}
lWindowsError = fclose(pFile); /*lint !e586
* C standard library call is being used for portability. */
if (lWindowsError != 0)
{
LogError(("File pointer operation failed.\r\n"));
pucSignerCert = NULL;
}
}
else
{
LogError(("No such certificate file: %s. Using aws_ota_codesigner_certificate.h.\r\n",
(const char*)pucCertName));
/* Allocate memory for the signer certificate plus a terminating zero so we can copy it and return to the caller. */
lSize = sizeof(signingcredentialSIGNING_CERTIFICATE_PEM);
pucSignerCert = pvPortMalloc(lSize); /*lint !e9029 !e9079 !e838 malloc proto requires void*. */
pucCertData = (uint8_t*)signingcredentialSIGNING_CERTIFICATE_PEM; /*lint !e9005 we don't modify the cert but it could be set by PKCS11 so it's not const. */
if (pucSignerCert != NULL)
{
memcpy(pucSignerCert, pucCertData, lSize);
*ulSignerCertSize = lSize;
}
else
{
LogError(("No memory for certificate of size %d!\r\n", lSize));
}
}
return pucSignerCert; /*lint !e480 !e481 fopen and fclose are being used by-design. */
}
/**
* @brief Verifies a cryptographic signature based on the signer
* certificate, hash algorithm, and the data that was signed.
*/
static BaseType_t prvVerifySignature(char* pcSignerCertificate,
size_t xSignerCertificateLength,
BaseType_t xHashAlgorithm,
uint8_t* pucHash,
size_t xHashLength,
uint8_t* pucSignature,
size_t xSignatureLength)
{
BaseType_t xResult = pdTRUE;
mbedtls_x509_crt xCertCtx;
mbedtls_md_type_t xMbedHashAlg = MBEDTLS_MD_SHA256;
(void)xHashAlgorithm;
memset(&xCertCtx, 0, sizeof(mbedtls_x509_crt));
/*
* Decode and create a certificate context
*/
mbedtls_x509_crt_init(&xCertCtx);
if (0 != mbedtls_x509_crt_parse(
&xCertCtx, (const unsigned char*)pcSignerCertificate, xSignerCertificateLength))
{
xResult = pdFALSE;
}
/*
* Verify the signature using the public key from the decoded certificate
*/
if (pdTRUE == xResult)
{
if (0 != mbedtls_pk_verify(
&xCertCtx.pk,
xMbedHashAlg,
pucHash,
xHashLength,
pucSignature,
xSignatureLength))
{
xResult = pdFALSE;
}
}
/*
* Clean-up
*/
mbedtls_x509_crt_free(&xCertCtx);
return xResult;
}
/**
* @brief Creates signature verification context.
*/
static BaseType_t prvSignatureVerificationStart(void** ppvContext,
BaseType_t xAsymmetricAlgorithm,
BaseType_t xHashAlgorithm)
{
BaseType_t xResult = pdTRUE;
SignatureVerificationState_t* pxCtx = NULL;
/*
* Allocate the context
*/
if (NULL == (pxCtx = (SignatureVerificationStatePtr_t)pvPortMalloc(
sizeof(*pxCtx)))) /*lint !e9087 Allow casting void* to other types. */
{
xResult = pdFALSE;
}
if (pdTRUE == xResult)
{
*ppvContext = pxCtx;
/*
* Store the algorithm identifiers
*/
pxCtx->xAsymmetricAlgorithm = xAsymmetricAlgorithm;
pxCtx->xHashAlgorithm = xHashAlgorithm;
/*
* Initialize the requested hash type
*/
mbedtls_sha256_init(&pxCtx->xSHA256Context);
(void)mbedtls_sha256_starts(&pxCtx->xSHA256Context, 0);
}
return xResult;
}
/**
* @brief Adds bytes to an in-progress hash for subsequent signature verification.
*/
static void prvSignatureVerificationUpdate(void* pvContext,
const uint8_t* pucData,
size_t xDataLength)
{
SignatureVerificationState_t* pxCtx = (SignatureVerificationStatePtr_t)pvContext; /*lint !e9087 Allow casting void* to other types. */
/*
* Add the data to the hash of the requested type
*/
(void)mbedtls_sha256_update(&pxCtx->xSHA256Context, pucData, xDataLength);
}
/**
* @brief Performs signature verification on a cryptographic hash.
*/
static BaseType_t prvSignatureVerificationFinal(void* pvContext,
char* pcSignerCertificate,
size_t xSignerCertificateLength,
uint8_t* pucSignature,
size_t xSignatureLength)
{
BaseType_t xResult = pdFALSE;
if (pvContext != NULL)
{
SignatureVerificationStatePtr_t pxCtx = (SignatureVerificationStatePtr_t)pvContext; /*lint !e9087 Allow casting void* to other types. */
uint8_t ucSHA256[SHA256_DIGEST_BYTES]; /* Reserve enough space for the larger for SHA256 results. */
uint8_t* pucHash = NULL;
size_t xHashLength = 0;
if ((pcSignerCertificate != NULL) &&
(pucSignature != NULL) &&
(xSignerCertificateLength > 0UL) &&
(xSignatureLength > 0UL))
{
/*
* Finish the hash.
*/
(void)mbedtls_sha256_finish(&pxCtx->xSHA256Context, ucSHA256);
pucHash = ucSHA256;
xHashLength = SHA256_DIGEST_BYTES;
/*
* Verify the signature.
*/
xResult = prvVerifySignature(pcSignerCertificate,
xSignerCertificateLength,
pxCtx->xHashAlgorithm,
pucHash,
xHashLength,
pucSignature,
xSignatureLength);
}
else
{
/* Allow function to be called with only the context pointer for cleanup after a failure. */
}
/*
* Clean-up
*/
vPortFree(pxCtx);
}
return xResult;
}
/* Verify the signature of the specified file. */
OtaPalMainStatus_t xValidateImageSignature(OtaFileContext_t* const C)
{
OtaPalMainStatus_t eResult = OtaPalSuccess;
uint32_t ulBytesRead;
uint32_t ulSignerCertSize;
uint8_t* pucBuf, * pucSignerCert;
void* pvSigVerifyContext;
/* Verify an ECDSA-SHA256 signature. */
if (pdFALSE == prvSignatureVerificationStart(&pvSigVerifyContext, ASYMMETRIC_ALGORITHM_ECDSA, HASH_ALGORITHM_SHA256))
{
eResult = OtaPalSignatureCheckFailed;
}
else
{
LogInfo(("Started %s signature verification, file: %s\r\n",
OTA_JsonFileSignatureKey, (const char*)C->pCertFilepath));
pucSignerCert = otaPal_ReadAndAssumeCertificate((const uint8_t* const)C->pCertFilepath, &ulSignerCertSize);
if (pucSignerCert != NULL)
{
pucBuf = pvPortMalloc( OTA_PAL_WIN_BUF_SIZE ); /*lint !e9079 Allow conversion. */
if (pucBuf != NULL)
{
/* Rewind the received file to the beginning. */
if (fseek(C->pFile, 0L, SEEK_SET) == 0) /*lint !e586
* C standard library call is being used for portability. */
{
do
{
ulBytesRead = fread(pucBuf, 1, OTA_PAL_WIN_BUF_SIZE, C->pFile); /*lint !e586
* C standard library call is being used for portability. */
/* Include the file chunk in the signature validation. Zero size is OK. */
prvSignatureVerificationUpdate(pvSigVerifyContext, pucBuf, ulBytesRead);
} while (ulBytesRead > 0UL);
if (pdFALSE == prvSignatureVerificationFinal(pvSigVerifyContext,
(char*)pucSignerCert,
(size_t)ulSignerCertSize,
C->pSignature->data,
C->pSignature->size)) /*lint !e732 !e9034 Allow comparison in this context. */
{
eResult = OtaPalSignatureCheckFailed;
}
pvSigVerifyContext = NULL; /* The context has been freed by prvSignatureVerificationFinal(). */
}
else
{
/* Nothing special to do. */
}
/* Free the temporary file page buffer. */
vPortFree(pucBuf);
}
else
{
LogError(("Failed to allocate buffer memory.\r\n"));
eResult = OtaPalOutOfMemory;
}
/* Free the signer certificate that we now own after prvReadAndAssumeCertificate(). */
vPortFree(pucSignerCert);
}
else
{
eResult = OtaPalBadSignerCert;
}
}
return eResult;
}

View File

@ -0,0 +1,419 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file ota_pal.c
* @brief OTA PAL implementation for Windows platform.
*/
/* Standard includes. */
#include <stdio.h>
#include <stdlib.h>
/* Kernel includes. */
#include "FreeRTOS.h"
/* Library config includes. */
#include "ota_config.h"
/* OTA Library include. */
#include "ota.h"
#include "ota_pal.h"
#include "code_signature_verification.h"
/* Specify the OTA signature algorithm we support on this platform. */
const char OTA_JsonFileSignatureKey[ OTA_FILE_SIG_KEY_STR_MAX_LENGTH ] = "sig-sha256-ecdsa";
static OtaPalMainStatus_t otaPal_CheckFileSignature( OtaFileContext_t * const C );
/*-----------------------------------------------------------*/
static inline BaseType_t prvContextValidate( OtaFileContext_t* pFileContext )
{
return( ( pFileContext != NULL ) &&
( pFileContext->pFile != NULL ) ); /*lint !e9034 Comparison is correct for file pointer type. */
}
/* Used to set the high bit of Windows error codes for a negative return value. */
#define OTA_PAL_INT16_NEGATIVE_MASK ( 1 << 15 )
/* Attempt to create a new receive file for the file chunks as they come in. */
OtaPalStatus_t otaPal_CreateFileForRx( OtaFileContext_t* const C )
{
OtaPalMainStatus_t mainErr = OtaPalUninitialized;
OtaPalSubStatus_t subErr = 0;
if( C != NULL )
{
if ( C->pFilePath != NULL )
{
C->pFile = fopen( ( const char * )C->pFilePath, "w+b" ); /*lint !e586
* C standard library call is being used for portability. */
if ( C->pFile != NULL )
{
mainErr = OtaPalSuccess;
LogInfo( ( "Receive file created.\r\n" ) );
}
else
{
mainErr = OtaPalRxFileCreateFailed;
subErr = errno;
LogError( ( "ERROR - Failed to start operation: already active!\r\n" ) );
}
}
else
{
mainErr = OtaPalRxFileCreateFailed;
LogError( ( "ERROR - Invalid filepath in filecontext.\r\n" ) );
}
}
else
{
mainErr = OtaPalRxFileCreateFailed;
LogError( ( "ERROR - Invalid file context provided.\r\n" ) );
}
return OTA_PAL_COMBINE_ERR(mainErr,subErr);
}
/* Abort receiving the specified OTA update by closing the file. */
OtaPalStatus_t otaPal_Abort( OtaFileContext_t * const C )
{
/* Set default return status to uninitialized. */
OtaPalMainStatus_t mainErr = OtaPalUninitialized;
OtaPalSubStatus_t subErr = 0;
int32_t lFileCloseResult;
if( NULL != C )
{
/* Close the OTA update file if it's open. */
if( NULL != C->pFile )
{
lFileCloseResult = fclose( C->pFile ); /*lint !e482 !e586
* Context file handle state is managed by this API. */
C->pFile = NULL;
if( 0 == lFileCloseResult )
{
LogInfo( ( "File closed.\r\n" ) );
mainErr = OtaPalSuccess;
}
else /* Failed to close file. */
{
LogError( ( "ERROR - Closing file failed.\r\n" ) );
mainErr = OtaPalFileAbort;
subErr = errno;
}
}
else
{
/* Nothing to do. No open file associated with this context. */
mainErr = OtaPalSuccess;
}
}
else /* Context was not valid. */
{
LogError( ( "ERROR - Invalid context.\r\n" ) );
mainErr = OtaPalFileAbort;
}
return OTA_PAL_COMBINE_ERR(mainErr,subErr);
}
/* Write a block of data to the specified file. */
int16_t otaPal_WriteBlock( OtaFileContext_t * const C,
uint32_t ulOffset,
uint8_t * const pacData,
uint32_t ulBlockSize )
{
int32_t lResult = 0;
if( prvContextValidate( C ) == pdTRUE )
{
lResult = fseek( C->pFile, ulOffset, SEEK_SET ); /*lint !e586 !e713 !e9034
* C standard library call is being used for portability. */
if( 0 == lResult )
{
lResult = fwrite( pacData, 1, ulBlockSize, C->pFile ); /*lint !e586 !e713 !e9034
* C standard library call is being used for portability. */
if( lResult < 0 )
{
LogError( ( "ERROR - fwrite failed\r\n" ) );
/* Mask to return a negative value. */
lResult = OTA_PAL_INT16_NEGATIVE_MASK | errno; /*lint !e40 !e9027
* Errno is being used in accordance with host API documentation.
* Bitmasking is being used to preserve host API error with library status code. */
}
}
else
{
LogError( ( "ERROR - fseek failed\r\n" ) );
/* Mask to return a negative value. */
lResult = OTA_PAL_INT16_NEGATIVE_MASK | errno; /*lint !e40 !e9027
* Errno is being used in accordance with host API documentation.
* Bitmasking is being used to preserve host API error with library status code. */
}
}
else /* Invalid context or file pointer provided. */
{
LogError( ( "ERROR - Invalid context.\r\n" ) );
lResult = -1; /*TODO: Need a negative error code from the PAL here. */
}
return ( int16_t ) lResult;
}
/* Close the specified file. This shall authenticate the file if it is marked as secure. */
OtaPalStatus_t otaPal_CloseFile( OtaFileContext_t * const C )
{
OtaPalMainStatus_t mainErr = OtaPalUninitialized;
OtaPalSubStatus_t subErr = 0;
int32_t lWindowsError = 0;
if( prvContextValidate( C ) == pdTRUE )
{
if( C->pSignature != NULL )
{
/* Verify the file signature, close the file and return the signature verification result. */
mainErr = otaPal_CheckFileSignature( C );
}
else
{
LogError( ( "NULL OTA Signature structure.\r\n" ) );
mainErr = OtaPalSignatureCheckFailed;
}
/* Close the file. */
lWindowsError = fclose( C->pFile ); /*lint !e482 !e586
* C standard library call is being used for portability. */
C->pFile = NULL;
if( lWindowsError != 0 )
{
LogError( ( "Failed to close OTA update file.\r\n" ) );
mainErr = OtaPalFileClose;
subErr = errno;
}
if( mainErr == OtaPalSuccess )
{
LogInfo( ( "%s signature verification passed.\r\n", OTA_JsonFileSignatureKey ) );
}
else
{
LogError( ( "Failed to pass %s signature verification: %d.\r\n",
OTA_JsonFileSignatureKey, OTA_PAL_COMBINE_ERR(mainErr,subErr) ) );
/* If we fail to verify the file signature that means the image is not valid. We need to set the image state to aborted. */
otaPal_SetPlatformImageState( C, OtaImageStateAborted );
}
}
else /* Invalid OTA Context. */
{
/* FIXME: Invalid error code for a null file context and file handle. */
LogError( ( "Invalid file context.\r\n" ) );
mainErr = OtaPalFileClose;
}
return OTA_PAL_COMBINE_ERR(mainErr,subErr);
}
/* Verify the signature of the specified file. */
static OtaPalMainStatus_t otaPal_CheckFileSignature( OtaFileContext_t* const C )
{
OtaPalMainStatus_t eResult = OtaPalSignatureCheckFailed;
if ( prvContextValidate( C ) == pdTRUE )
{
eResult = xValidateImageSignature( C );
}
else
{
LogError( ( "OTA image signature is invalid.\r\n" ) );
}
return eResult;
}
/*-----------------------------------------------------------*/
OtaPalStatus_t otaPal_ResetDevice( OtaFileContext_t* const pFileContext )
{
(void)pFileContext;
/* Return no error. Windows implementation does not reset device. */
return OTA_PAL_COMBINE_ERR(OtaPalSuccess,0);
}
/*-----------------------------------------------------------*/
OtaPalStatus_t otaPal_ActivateNewImage( OtaFileContext_t* const pFileContext )
{
(void)pFileContext;
/* Return no error. Windows implementation simply does nothing on activate.
* To run the new firmware image, double click the newly downloaded exe */
return OTA_PAL_COMBINE_ERR(OtaPalSuccess,0);
}
/*
* Set the final state of the last transferred (final) OTA file (or bundle).
* On Windows, the state of the OTA image is stored in PlaformImageState.txt.
*/
OtaPalStatus_t otaPal_SetPlatformImageState( OtaFileContext_t * const pFileContext, OtaImageState_t eState )
{
(void)pFileContext;
OtaPalMainStatus_t mainErr = OtaPalSuccess;
OtaPalSubStatus_t subErr = 0;
FILE * pstPlatformImageState;
if( eState != OtaImageStateUnknown && eState <= OtaLastImageState )
{
pstPlatformImageState = fopen( "PlatformImageState.txt", "w+b" ); /*lint !e586
* C standard library call is being used for portability. */
if( pstPlatformImageState != NULL )
{
/* Write the image state to PlatformImageState.txt. */
if( 1 != fwrite( &eState, sizeof( OtaImageState_t ), 1, pstPlatformImageState ) ) /*lint !e586 !e9029
* C standard library call is being used for portability. */
{
LogError( ( "Unable to write to image state file.\r\n" ) );
mainErr = OtaPalBadImageState;
subErr = errno;
}
/* Close PlatformImageState.txt. */
if( 0 != fclose( pstPlatformImageState ) ) /*lint !e586 Allow call in this context. */
{
LogError( ( "Unable to close image state file.\r\n" ) );
mainErr = OtaPalBadImageState;
subErr = errno;
}
}
else
{
LogError( ( "Unable to open image state file.\r\n" ) );
mainErr = OtaPalBadImageState;
subErr = errno;
}
} /*lint !e481 Allow fopen and fclose calls in this context. */
else /* Image state invalid. */
{
LogError( ( "ERROR - Invalid image state provided.\r\n" ) );
mainErr = OtaPalBadImageState;
}
return OTA_PAL_COMBINE_ERR(mainErr,subErr);
}
/* Get the state of the currently running image.
*
* On Windows, this is simulated by looking for and reading the state from
* the PlatformImageState.txt file in the current working directory.
*
* We read this at OTA_Init time so we can tell if the MCU image is in self
* test mode. If it is, we expect a successful connection to the OTA services
* within a reasonable amount of time. If we don't satisfy that requirement,
* we assume there is something wrong with the firmware and reset the device,
* causing it to rollback to the previous code. On Windows, this is not
* fully simulated as there is no easy way to reset the simulated device.
*/
OtaPalImageState_t otaPal_GetPlatformImageState( OtaFileContext_t * const pFileContext )
{
(void)pFileContext;
FILE * pstPlatformImageState;
OtaImageState_t eSavedAgentState = OtaImageStateUnknown;
OtaPalImageState_t ePalState = OtaPalImageStateUnknown;
pstPlatformImageState = fopen( "PlatformImageState.txt", "r+b" ); /*lint !e586
* C standard library call is being used for portability. */
if( pstPlatformImageState != NULL )
{
if( 1 != fread( &eSavedAgentState, sizeof(OtaImageState_t), 1, pstPlatformImageState ) ) /*lint !e586 !e9029
* C standard library call is being used for portability. */
{
/* If an error occurred reading the file, mark the state as aborted. */
LogError( ( "Unable to read image state file.\r\n" ) );
ePalState = ( OtaPalImageStateInvalid | (errno & OTA_PAL_ERR_MASK) );
}
else
{
switch (eSavedAgentState)
{
case OtaImageStateTesting:
ePalState = OtaPalImageStatePendingCommit;
break;
case OtaImageStateAccepted:
ePalState = OtaPalImageStateValid;
break;
case OtaImageStateRejected:
case OtaImageStateAborted:
default:
ePalState = OtaPalImageStateInvalid;
break;
}
}
if( 0 != fclose( pstPlatformImageState ) ) /*lint !e586
* C standard library call is being used for portability. */
{
LogError( ( "Unable to close image state file.\r\n" ) );
ePalState = (OtaPalImageStateInvalid | ( errno & OTA_PAL_ERR_MASK ) );
}
}
else
{
/* If no image state file exists, assume a factory image. */
ePalState = OtaPalImageStateValid; /*lint !e64 Allow assignment. */
}
return ePalState; /*lint !e64 !e480 !e481 I/O calls and return type are used per design. */
}
/*-----------------------------------------------------------*/
/* Provide access to private members for testing. */
#ifdef FREERTOS_ENABLE_UNIT_TESTS
#include "aws_ota_pal_test_access_define.h"
#endif

View File

@ -0,0 +1,207 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file ota_pal.h
* @brief Function declarations for ota_ptal.c.
*/
#ifndef _OTA_PAL_H_
#define _OTA_PAL_H_
#include "ota.h"
//static const char signingcredentialSIGNING_CERTIFICATE_PEM[] = "Paste code signing certificate here.";
/**
* @brief Abort an OTA transfer.
*
* Aborts access to an existing open file represented by the OTA file context C. This is only valid
* for jobs that started successfully.
*
* @note The input OtaFileContext_t C is checked for NULL by the OTA agent before this
* function is called.
* This function may be called before the file is opened, so the file pointer C->fileHandle may be NULL
* when this function is called.
*
* @param[in] C OTA file context information.
*
* @return The OTA PAL layer error code combined with the MCU specific error code. See OTA Agent
* error codes information in ota.h.
*
* The file pointer will be set to NULL after this function returns.
* OTA_ERR_NONE is returned when aborting access to the open file was successful.
* OTA_ERR_FILE_ABORT is returned when aborting access to the open file context was unsuccessful.
*/
OtaPalStatus_t otaPal_Abort( OtaFileContext_t * const C );
/**
* @brief Create a new receive file for the data chunks as they come in.
*
* @note Opens the file indicated in the OTA file context in the MCU file system.
*
* @note The previous image may be present in the designated image download partition or file, so the partition or file
* must be completely erased or overwritten in this routine.
*
* @note The input OtaFileContext_t C is checked for NULL by the OTA agent before this
* function is called.
* The device file path is a required field in the OTA job document, so C->pFilePath is
* checked for NULL by the OTA agent before this function is called.
*
* @param[in] C OTA file context information.
*
* @return The OTA PAL layer error code combined with the MCU specific error code. See OTA Agent
* error codes information in ota.h.
*
* OTA_ERR_NONE is returned when file creation is successful.
* OTA_ERR_RX_FILE_TOO_LARGE is returned if the file to be created exceeds the device's non-volatile memory size constraints.
* OTA_ERR_BOOT_INFO_CREATE_FAILED is returned if the bootloader information file creation fails.
* OTA_ERR_RX_FILE_CREATE_FAILED is returned for other errors creating the file in the device's non-volatile memory.
*/
OtaPalStatus_t otaPal_CreateFileForRx( OtaFileContext_t * const C );
/* @brief Authenticate and close the underlying receive file in the specified OTA context.
*
* @note The input OtaFileContext_t C is checked for NULL by the OTA agent before this
* function is called. This function is called only at the end of block ingestion.
* prvPAL_CreateFileForRx() must succeed before this function is reached, so
* C->fileHandle(or C->pFile) is never NULL.
* The certificate path on the device is a required job document field in the OTA Agent,
* so C->pCertFilepath is never NULL.
* The file signature key is required job document field in the OTA Agent, so C->pSignature will
* never be NULL.
*
* If the signature verification fails, file close should still be attempted.
*
* @param[in] C OTA file context information.
*
* @return The OTA PAL layer error code combined with the MCU specific error code. See OTA Agent
* error codes information in ota.h.
*
* OTA_ERR_NONE is returned on success.
* OTA_ERR_SIGNATURE_CHECK_FAILED is returned when cryptographic signature verification fails.
* OTA_ERR_BAD_SIGNER_CERT is returned for errors in the certificate itself.
* OTA_ERR_FILE_CLOSE is returned when closing the file fails.
*/
OtaPalStatus_t otaPal_CloseFile( OtaFileContext_t * const C );
/**
* @brief Write a block of data to the specified file at the given offset.
*
* @note The input OtaFileContext_t C is checked for NULL by the OTA agent before this
* function is called.
* The file pointer/handle C->pFile, is checked for NULL by the OTA agent before this
* function is called.
* pacData is checked for NULL by the OTA agent before this function is called.
* ulBlockSize is validated for range by the OTA agent before this function is called.
* ulBlockIndex is validated by the OTA agent before this function is called.
*
* @param[in] C OTA file context information.
* @param[in] ulOffset Byte offset to write to from the beginning of the file.
* @param[in] pacData Pointer to the byte array of data to write.
* @param[in] ulBlockSize The number of bytes to write.
*
* @return The number of bytes written on a success, or a negative error code from the platform abstraction layer.
*/
int16_t otaPal_WriteBlock( OtaFileContext_t * const C,
uint32_t ulOffset,
uint8_t * const pcData,
uint32_t ulBlockSize );
/**
* @brief Activate the newest MCU image received via OTA.
*
* This function shall do whatever is necessary to activate the newest MCU
* firmware received via OTA. It is typically just a reset of the device.
*
* @note This function SHOULD not return. If it does, the platform does not support
* an automatic reset or an error occurred.
*
* @return The OTA PAL layer error code combined with the MCU specific error code. See OTA Agent
* error codes information in ota.h.
*/
OtaPalStatus_t otaPal_ActivateNewImage( OtaFileContext_t * const C );
/**
* @brief Reset the device.
*
* This function shall reset the MCU and cause a reboot of the system.
*
* @note This function SHOULD not return. If it does, the platform does not support
* an automatic reset or an error occurred.
*
* @return The OTA PAL layer error code combined with the MCU specific error code. See OTA Agent
* error codes information in ota.h.
*/
OtaPalStatus_t otaPal_ResetDevice( OtaFileContext_t * const C );
/**
* @brief Attempt to set the state of the OTA update image.
*
* Do whatever is required by the platform to Accept/Reject the OTA update image (or bundle).
* Refer to the PAL implementation to determine what happens on your platform.
*
* @param[in] eState The desired state of the OTA update image.
*
* @return The OtaErr_t error code combined with the MCU specific error code. See ota.h for
* OTA major error codes and your specific PAL implementation for the sub error code.
*
* Major error codes returned are:
*
* OTA_ERR_NONE on success.
* OTA_ERR_BAD_IMAGE_STATE: if you specify an invalid OtaImageState_t. No sub error code.
* OTA_ERR_ABORT_FAILED: failed to roll back the update image as requested by OtaImageStateAborted.
* OTA_ERR_REJECT_FAILED: failed to roll back the update image as requested by OtaImageStateRejected.
* OTA_ERR_COMMIT_FAILED: failed to make the update image permanent as requested by OtaImageStateAccepted.
*/
OtaPalStatus_t otaPal_SetPlatformImageState( OtaFileContext_t * const C,
OtaImageState_t eState );
/**
* @brief Get the state of the OTA update image.
*
* We read this at OTA_Init time and when the latest OTA job reports itself in self
* test. If the update image is in the "pending commit" state, we start a self test
* timer to assure that we can successfully connect to the OTA services and accept
* the OTA update image within a reasonable amount of time (user configurable). If
* we don't satisfy that requirement, we assume there is something wrong with the
* firmware and automatically reset the device, causing it to roll back to the
* previously known working code.
*
* If the update image state is not in "pending commit," the self test timer is
* not started.
*
* @return An OtaPalImageState_t. One of the following:
* OtaPalImageStatePendingCommit (the new firmware image is in the self test phase)
* OtaPalImageStateValid (the new firmware image is already committed)
* OtaPalImageStateInvalid (the new firmware image is invalid or non-existent)
*
* NOTE: OtaPalImageStateUnknown should NEVER be returned and indicates an implementation error.
*/
OtaPalImageState_t otaPal_GetPlatformImageState( OtaFileContext_t * const C );
#endif /* ifndef _OTA_PAL_H_ */

View File

@ -0,0 +1,170 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file subscription_manager.c
* @brief Functions for managing MQTT subscriptions.
*/
/* Standard includes. */
#include <string.h>
/* Subscription manager header include. */
#include "subscription_manager.h"
bool addSubscription( SubscriptionElement_t * pxSubscriptionList,
const char * pcTopicFilterString,
uint16_t usTopicFilterLength,
IncomingPubCallback_t pxIncomingPublishCallback,
void * pvIncomingPublishCallbackContext )
{
int32_t lIndex = 0;
size_t xAvailableIndex = SUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS;
bool xReturnStatus = false;
if( ( pxSubscriptionList == NULL ) ||
( pcTopicFilterString == NULL ) ||
( usTopicFilterLength == 0U ) ||
( pxIncomingPublishCallback == NULL ) )
{
LogError( ( "Invalid parameter. pxSubscriptionList=%p, pcTopicFilterString=%p,"
" usTopicFilterLength=%u, pxIncomingPublishCallback=%p.",
pxSubscriptionList,
pcTopicFilterString,
( unsigned int ) usTopicFilterLength,
pxIncomingPublishCallback ) );
}
else
{
/* Start at end of array, so that we will insert at the first available index.
* Scans backwards to find duplicates. */
for( lIndex = ( int32_t ) SUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS - 1; lIndex >= 0; lIndex-- )
{
if( pxSubscriptionList[ lIndex ].usFilterStringLength == 0 )
{
xAvailableIndex = lIndex;
}
else if( ( pxSubscriptionList[ lIndex ].usFilterStringLength == usTopicFilterLength ) &&
( strncmp( pcTopicFilterString, pxSubscriptionList[ lIndex ].pcSubscriptionFilterString, ( size_t ) usTopicFilterLength ) == 0 ) )
{
/* If a subscription already exists, don't do anything. */
if( ( pxSubscriptionList[ lIndex ].pxIncomingPublishCallback == pxIncomingPublishCallback ) &&
( pxSubscriptionList[ lIndex ].pvIncomingPublishCallbackContext == pvIncomingPublishCallbackContext ) )
{
LogWarn( ( "Subscription already exists.\n" ) );
xAvailableIndex = SUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS;
xReturnStatus = true;
break;
}
}
}
if( xAvailableIndex < SUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS )
{
pxSubscriptionList[ xAvailableIndex ].pcSubscriptionFilterString = pcTopicFilterString;
pxSubscriptionList[ xAvailableIndex ].usFilterStringLength = usTopicFilterLength;
pxSubscriptionList[ xAvailableIndex ].pxIncomingPublishCallback = pxIncomingPublishCallback;
pxSubscriptionList[ xAvailableIndex ].pvIncomingPublishCallbackContext = pvIncomingPublishCallbackContext;
xReturnStatus = true;
}
}
return xReturnStatus;
}
/*-----------------------------------------------------------*/
void removeSubscription( SubscriptionElement_t * pxSubscriptionList,
const char * pcTopicFilterString,
uint16_t usTopicFilterLength )
{
int32_t lIndex = 0;
if( ( pxSubscriptionList == NULL ) ||
( pcTopicFilterString == NULL ) ||
( usTopicFilterLength == 0U ) )
{
LogError( ( "Invalid parameter. pxSubscriptionList=%p, pcTopicFilterString=%p,"
" usTopicFilterLength=%u.",
pxSubscriptionList,
pcTopicFilterString,
( unsigned int ) usTopicFilterLength ) );
}
else
{
for( lIndex = 0; lIndex < SUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS; lIndex++ )
{
if( pxSubscriptionList[ lIndex ].usFilterStringLength == usTopicFilterLength )
{
if( strncmp( pxSubscriptionList[ lIndex ].pcSubscriptionFilterString, pcTopicFilterString, usTopicFilterLength ) == 0 )
{
memset( &( pxSubscriptionList[ lIndex ] ), 0x00, sizeof( SubscriptionElement_t ) );
}
}
}
}
}
/*-----------------------------------------------------------*/
bool handleIncomingPublishes( SubscriptionElement_t * pxSubscriptionList,
MQTTPublishInfo_t * pxPublishInfo )
{
int32_t lIndex = 0;
bool isMatched = false, publishHandled = false;
if( ( pxSubscriptionList == NULL ) ||
( pxPublishInfo == NULL ) )
{
LogError( ( "Invalid parameter. pxSubscriptionList=%p, pxPublishInfo=%p,",
pxSubscriptionList,
pxPublishInfo ) );
}
else
{
for( lIndex = 0; lIndex < SUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS; lIndex++ )
{
if( pxSubscriptionList[ lIndex ].usFilterStringLength > 0 )
{
MQTT_MatchTopic( pxPublishInfo->pTopicName,
pxPublishInfo->topicNameLength,
pxSubscriptionList[ lIndex ].pcSubscriptionFilterString,
pxSubscriptionList[ lIndex ].usFilterStringLength,
&isMatched );
if( isMatched == true )
{
pxSubscriptionList[ lIndex ].pxIncomingPublishCallback( pxSubscriptionList[ lIndex ].pvIncomingPublishCallbackContext,
pxPublishInfo );
publishHandled = true;
}
}
}
}
return publishHandled;
}

View File

@ -0,0 +1,150 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file subscription_manager.h
* @brief Functions for managing MQTT subscriptions.
*/
#ifndef SUBSCRIPTION_MANAGER_H
#define SUBSCRIPTION_MANAGER_H
/**************************************************/
/******* DO NOT CHANGE the following order ********/
/**************************************************/
/* Logging related header files are required to be included in the following order:
* 1. Include the header file "logging_levels.h".
* 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL.
* 3. Include the header file "logging_stack.h".
*/
/* Include header that defines log levels. */
#include "logging_levels.h"
/* Logging configuration for the Subscription Manager module. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "Subscription Manager"
#endif
#ifndef LIBRARY_LOG_LEVEL
#define LIBRARY_LOG_LEVEL LOG_ERROR
#endif
#include "logging_stack.h"
/* Demo config include. */
#include "demo_config.h"
/* core MQTT include. */
#include "core_mqtt.h"
/**
* @brief Maximum number of subscriptions maintained by the subscription manager
* simultaneously in a list.
*/
#ifndef SUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS
#define SUBSCRIPTION_MANAGER_MAX_SUBSCRIPTIONS 10U
#endif
/**
* @brief Callback function called when receiving a publish.
*
* @param[in] pvIncomingPublishCallbackContext The incoming publish callback context.
* @param[in] pxPublishInfo Deserialized publish information.
*/
typedef void (* IncomingPubCallback_t )( void * pvIncomingPublishCallbackContext,
MQTTPublishInfo_t * pxPublishInfo );
/**
* @brief An element in the list of subscriptions.
*
* This subscription manager implementation expects that the array of the
* subscription elements used for storing subscriptions to be initialized to 0.
*
* @note This implementation allows multiple tasks to subscribe to the same topic.
* In this case, another element is added to the subscription list, differing
* in the intended publish callback. Also note that the topic filters are not
* copied in the subscription manager and hence the topic filter strings need to
* stay in scope until unsubscribed.
*/
typedef struct subscriptionElement
{
IncomingPubCallback_t pxIncomingPublishCallback;
void * pvIncomingPublishCallbackContext;
uint16_t usFilterStringLength;
const char * pcSubscriptionFilterString;
} SubscriptionElement_t;
/**
* @brief Add a subscription to the subscription list.
*
* @note Multiple tasks can be subscribed to the same topic with different
* context-callback pairs. However, a single context-callback pair may only be
* associated to the same topic filter once.
*
* @param[in] pxSubscriptionList The pointer to the subscription list array.
* @param[in] pcTopicFilterString Topic filter string of subscription.
* @param[in] usTopicFilterLength Length of topic filter string.
* @param[in] pxIncomingPublishCallback Callback function for the subscription.
* @param[in] pvIncomingPublishCallbackContext Context for the subscription callback.
*
* @return `true` if subscription added or exists, `false` if insufficient memory.
*/
bool addSubscription( SubscriptionElement_t * pxSubscriptionList,
const char * pcTopicFilterString,
uint16_t usTopicFilterLength,
IncomingPubCallback_t pxIncomingPublishCallback,
void * pvIncomingPublishCallbackContext );
/**
* @brief Remove a subscription from the subscription list.
*
* @note If the topic filter exists multiple times in the subscription list,
* then every instance of the subscription will be removed.
*
* @param[in] pxSubscriptionList The pointer to the subscription list array.
* @param[in] pcTopicFilterString Topic filter of subscription.
* @param[in] usTopicFilterLength Length of topic filter.
*/
void removeSubscription( SubscriptionElement_t * pxSubscriptionList,
const char * pcTopicFilterString,
uint16_t usTopicFilterLength );
/**
* @brief Handle incoming publishes by invoking the callbacks registered
* for the incoming publish's topic filter.
*
* @param[in] pxSubscriptionList The pointer to the subscription list array.
* @param[in] pxPublishInfo Info of incoming publish.
*
* @return `true` if an application callback could be invoked;
* `false` otherwise.
*/
bool handleIncomingPublishes( SubscriptionElement_t * pxSubscriptionList,
MQTTPublishInfo_t * pxPublishInfo );
#endif /* SUBSCRIPTION_MANAGER_H */

View File

@ -0,0 +1,249 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{4be4e103-5bf4-4a85-9656-ec20852a2b8e}</ProjectGuid>
<RootNamespace>OtaOverHttpDemo</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<TargetName>RTOSDemo</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<TargetName>RTOSDemo</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<TargetName>RTOSDemo</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<TargetName>RTOSDemo</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>MQTT_AGENT_DO_NOT_USE_CUSTOM_CONFIG;WIN32;__little_endian__=1;_DEBUG;_CONSOLE;WIN32;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\Common\HTTP_Utils;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\Common\coreMQTT_Agent_Interface\include;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\ota\source\include;..\..\..\..\Source\AWS\ota\source\portable\os;..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\Common\Ota_PAL\Win32\Code_Signature_Verification;..\Common\Ota_PAL\Win32;..\Common\subscription-manager;.\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>MQTT_AGENT_DO_NOT_USE_CUSTOM_CONFIG;WIN32;__little_endian__=1;WIN32;NDEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\Common\HTTP_Utils;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\Common\coreMQTT_Agent_Interface\include;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\ota\source\include;..\..\..\..\Source\AWS\ota\source\portable\os;..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\Common\Ota_PAL\Win32\Code_Signature_Verification;..\Common\Ota_PAL\Win32;..\Common\subscription-manager;.\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>MQTT_AGENT_DO_NOT_USE_CUSTOM_CONFIG;WIN32;__little_endian__=1;_DEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\Common\HTTP_Utils;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\Common\coreMQTT_Agent_Interface\include;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\ota\source\include;..\..\..\..\Source\AWS\ota\source\portable\os;..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\Common\Ota_PAL\Win32\Code_Signature_Verification;..\Common\Ota_PAL\Win32;..\Common\subscription-manager;.\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>MQTT_AGENT_DO_NOT_USE_CUSTOM_CONFIG;WIN32;__little_endian__=1;NDEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\Common\HTTP_Utils;..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\Common\coreMQTT_Agent_Interface\include;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\ota\source\include;..\..\..\..\Source\AWS\ota\source\portable\os;..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\Common\Ota_PAL\Win32\Code_Signature_Verification;..\Common\Ota_PAL\Win32;..\Common\subscription-manager;.\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\coreHTTP\coreHTTP.vcxproj">
<Project>{ee39fa0f-cefb-4c29-a571-05a28fdd47fd}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj">
<Project>{c90e6cc5-818b-4c97-8876-0986d989387c}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj">
<Project>{72c209c4-49a4-4942-a201-44706c9d77ec}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj">
<Project>{be362ac0-b10b-4276-b84e-6304652ba228}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj">
<Project>{e1016f3e-94e9-4864-9fd8-1d7c1fefbfd7}</Project>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\core_mqtt_agent.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\core_mqtt_agent_command_functions.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_base64.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_cbor.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_http.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_interface.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_mqtt.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\portable\os\ota_os_freertos.c" />
<ClCompile Include="..\..\..\..\Source\coreJSON\source\core_json.c" />
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder_close_container_checked.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborerrorstrings.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser_dup_string.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborpretty.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborpretty_stdio.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborvalidation.c" />
<ClCompile Include="..\..\..\Common\coreMQTT_Agent_Interface\freertos_agent_message.c" />
<ClCompile Include="..\..\..\Common\coreMQTT_Agent_Interface\freertos_command_pool.c" />
<ClCompile Include="..\Common\HTTP_Utils\http_demo_utils.c" />
<ClCompile Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\code_signature_verification_mbedtls.c" />
<ClCompile Include="..\Common\Ota_PAL\Win32\ota_pal.c" />
<ClCompile Include="..\Common\subscription-manager\subscription_manager.c" />
<ClCompile Include="DemoTasks\OtaOverHttpDemoExample.c" />
<ClCompile Include="main.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent_command_functions.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent_message_interface.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_appversion32.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_base64_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_cbor_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_http_interface.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_http_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_interface_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_mqtt_interface.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_mqtt_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_os_interface.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_platform_interface.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\portable\os\ota_os_freertos.h" />
<ClInclude Include="..\..\..\..\Source\coreJSON\source\include\core_json.h" />
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cbor.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborinternal_p.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborjson.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\compilersupport_p.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\tinycbor-version.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\utf8_p.h" />
<ClInclude Include="..\..\..\Common\coreMQTT_Agent_Interface\include\freertos_agent_message.h" />
<ClInclude Include="..\..\..\Common\coreMQTT_Agent_Interface\include\freertos_command_pool.h" />
<ClInclude Include="..\Common\HTTP_Utils\http_demo_utils.h" />
<ClInclude Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\aws_ota_codesigner_certificate.h" />
<ClInclude Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\code_signature_verification.h" />
<ClInclude Include="..\Common\Ota_PAL\Win32\ota_pal.h" />
<ClInclude Include="..\Common\subscription-manager\subscription_manager.h" />
<ClInclude Include="core_mqtt_config.h" />
<ClInclude Include="demo_config.h" />
<ClInclude Include="ota_config.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,339 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="Additional Network Transport Files">
<UniqueIdentifier>{d8a6eab8-52e5-4e4f-a9b9-cd5d8eb3454a}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries">
<UniqueIdentifier>{18d8589f-6af4-4627-b7fe-e1c9bdfecdd8}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT OTA">
<UniqueIdentifier>{6eb6582b-1dce-411e-bc0b-841a09741615}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm">
<UniqueIdentifier>{3d266f56-5fd1-4585-9a72-3eef3ee1ee53}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreJSON">
<UniqueIdentifier>{96471440-eb47-4085-a08f-8576fa6fac34}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT">
<UniqueIdentifier>{4e394147-c8cd-4245-b188-0b4827b1875e}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT-Agent">
<UniqueIdentifier>{4e2b22e6-880f-40a0-8b4e-be5e8d3471b2}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\TinyCBOR">
<UniqueIdentifier>{228e794f-fa2d-44ec-ad49-95d6820434a2}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT OTA\portable">
<UniqueIdentifier>{71c883e5-7eb1-44fe-bbcb-5a2b6c3e4d15}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT OTA\include">
<UniqueIdentifier>{b3aeb9e5-1b4f-4652-b24a-49a8c406113e}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm\include">
<UniqueIdentifier>{163f3bc7-7054-4400-8c9e-7f8ac07307f8}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreJSON\include">
<UniqueIdentifier>{6db5c3a5-4750-40b1-9c8c-38e90fa37f9a}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\include">
<UniqueIdentifier>{2e0ccf6e-a4ca-4349-93ed-5eafa843095b}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\interface">
<UniqueIdentifier>{a8c75d87-1984-4285-af5c-15146e3dba37}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT-Agent\include">
<UniqueIdentifier>{5e99c65f-35d7-4c3d-9055-9c7759e6f26b}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\TinyCBOR\include">
<UniqueIdentifier>{d90df1a1-4234-4da5-b3c3-46aa7947a06d}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files">
<UniqueIdentifier>{b4d0329a-2859-4ba6-a690-ce91db59b325}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\OTA PAL">
<UniqueIdentifier>{86c10d39-5f4e-4818-aad7-c565dd268bef}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\OTA PAL\Code Signature Verification MbedTLS">
<UniqueIdentifier>{a563c8c2-aada-4f3e-b77a-43db3cf9e26e}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\OTA PAL\include">
<UniqueIdentifier>{b89e35af-5342-46c6-84f2-24aa5761e368}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\OTA PAL\Code Signature Verification MbedTLS\include">
<UniqueIdentifier>{ed32e5c5-0bcb-49b9-9328-7b01d3becdf3}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\coreMQTT Agent Interface">
<UniqueIdentifier>{d1acbc8c-cc4d-4c81-8ee0-a68922cc6f1a}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\coreMQTT Agent Interface\include">
<UniqueIdentifier>{9df90bb5-248f-42cb-8a1c-4b657078898e}</UniqueIdentifier>
</Filter>
<Filter Include="Config">
<UniqueIdentifier>{2638c698-6c61-4539-a1d6-778586efb3a4}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper">
<UniqueIdentifier>{db1fff46-e0ac-434a-afbd-fed44d1efcbb}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport">
<UniqueIdentifier>{0bac4135-5620-46bf-97bc-650637aa824b}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include">
<UniqueIdentifier>{8c7c47a6-bb49-46a0-b804-f569d3dca0f0}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\include">
<UniqueIdentifier>{d491829c-c97e-4f26-84f4-ebabe1cf94b7}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports">
<UniqueIdentifier>{1c33fa66-1e0e-45c6-98ad-29b3072f189e}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports\freertos_plus_tcp">
<UniqueIdentifier>{691f4cfe-af00-47b6-bc4b-f988da6bedc3}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="DemoTasks\OtaOverHttpDemoExample.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="main.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Common\subscription-manager\subscription_manager.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_base64.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_cbor.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_http.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_interface.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_mqtt.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\portable\os\ota_os_freertos.c">
<Filter>Additional Libraries\AWS IoT OTA\portable</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c">
<Filter>Additional Libraries\Backoff Algorithm</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\coreJSON\source\core_json.c">
<Filter>Additional Libraries\coreJSON</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\core_mqtt_agent.c">
<Filter>Additional Libraries\coreMQTT-Agent</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\core_mqtt_agent_command_functions.c">
<Filter>Additional Libraries\coreMQTT-Agent</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder_close_container_checked.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborerrorstrings.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser_dup_string.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborpretty.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborpretty_stdio.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborvalidation.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\Common\Ota_PAL\Win32\ota_pal.c">
<Filter>Port Files\OTA PAL</Filter>
</ClCompile>
<ClCompile Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\code_signature_verification_mbedtls.c">
<Filter>Port Files\OTA PAL\Code Signature Verification MbedTLS</Filter>
</ClCompile>
<ClCompile Include="..\..\..\Common\coreMQTT_Agent_Interface\freertos_agent_message.c">
<Filter>Port Files\coreMQTT Agent Interface</Filter>
</ClCompile>
<ClCompile Include="..\..\..\Common\coreMQTT_Agent_Interface\freertos_command_pool.c">
<Filter>Port Files\coreMQTT Agent Interface</Filter>
</ClCompile>
<ClCompile Include="..\Common\HTTP_Utils\http_demo_utils.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\ports\freertos_plus_tcp</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Common\subscription-manager\subscription_manager.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\portable\os\ota_os_freertos.h">
<Filter>Additional Libraries\AWS IoT OTA\portable</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_appversion32.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_base64_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_cbor_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_config_defaults.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_http_interface.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_http_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_interface_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_mqtt_interface.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_mqtt_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_os_interface.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_platform_interface.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h">
<Filter>Additional Libraries\Backoff Algorithm\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\coreJSON\source\include\core_json.h">
<Filter>Additional Libraries\coreJSON\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h">
<Filter>Additional Libraries\coreMQTT\interface</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent.h">
<Filter>Additional Libraries\coreMQTT-Agent\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent_command_functions.h">
<Filter>Additional Libraries\coreMQTT-Agent\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent_message_interface.h">
<Filter>Additional Libraries\coreMQTT-Agent\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cbor.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborinternal_p.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborjson.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\compilersupport_p.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\tinycbor-version.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\utf8_p.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\Common\Ota_PAL\Win32\ota_pal.h">
<Filter>Port Files\OTA PAL\include</Filter>
</ClInclude>
<ClInclude Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\code_signature_verification.h">
<Filter>Port Files\OTA PAL\Code Signature Verification MbedTLS\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\Common\coreMQTT_Agent_Interface\include\freertos_agent_message.h">
<Filter>Port Files\coreMQTT Agent Interface\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\Common\coreMQTT_Agent_Interface\include\freertos_command_pool.h">
<Filter>Port Files\coreMQTT Agent Interface\include</Filter>
</ClInclude>
<ClInclude Include="..\Common\HTTP_Utils\http_demo_utils.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\aws_ota_codesigner_certificate.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="core_mqtt_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="demo_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="ota_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\include</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,109 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef CORE_MQTT_CONFIG_H
#define CORE_MQTT_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 MQTT.
* 3. Include the header file "logging_stack.h", if logging is enabled for MQTT.
*/
#include "logging_levels.h"
/* Logging configuration for the MQTT library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "MQTT"
#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 ****************/
/**
* @brief The maximum number of MQTT PUBLISH messages that may be pending
* acknowledgement at any time.
*
* QoS 1 and 2 MQTT PUBLISHes require acknowledgment from the server before
* they can be completed. While they are awaiting the acknowledgment, the
* client must maintain information about their state. The value of this
* macro sets the limit on how many simultaneous PUBLISH states an MQTT
* context maintains.
*/
#define MQTT_STATE_ARRAY_MAX_COUNT 10U
/*********************** coreMQTT Agent Configurations **********************/
/**
* @brief The maximum number of pending acknowledgments to track for a single
* connection.
*
* @note The MQTT agent tracks MQTT commands (such as PUBLISH and SUBSCRIBE) th
* at are still waiting to be acknowledged. MQTT_AGENT_MAX_OUTSTANDING_ACKS set
* the maximum number of acknowledgments that can be outstanding at any one time.
* The higher this number is the greater the agent's RAM consumption will be.
*/
#define MQTT_AGENT_MAX_OUTSTANDING_ACKS ( 20U )
/**
* @brief Time in MS that the MQTT agent task will wait in the Blocked state (so
* not using any CPU time) for a command to arrive in its command queue before
* exiting the blocked state so it can call MQTT_ProcessLoop().
*
* @note It is important MQTT_ProcessLoop() is called often if there is known
* MQTT traffic, but calling it too often can take processing time away from
* lower priority tasks and waste CPU time and power.
*/
#define MQTT_AGENT_MAX_EVENT_QUEUE_WAIT_TIME ( 1000 )
/**
* @brief The number of command structures to allocate in the pool
* for the agent.
*/
#define MQTT_COMMAND_CONTEXTS_POOL_SIZE 10
#endif /* ifndef CORE_MQTT_CONFIG_H */

View File

@ -0,0 +1,326 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#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 "OTADemo"
#endif
#ifndef LIBRARY_LOG_LEVEL
#define LIBRARY_LOG_LEVEL LOG_DEBUG
#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 version for the firmware which is running. OTA agent uses this
* version number to perform anti-rollback validation. The firmware version for the
* download image should be higher than the current version, otherwise the new image is
* rejected in self test phase.
*/
#define APP_VERSION_MAJOR 0
#define APP_VERSION_MINOR 9
#define APP_VERSION_BUILD 2
/**
* @brief The MQTT client identifier used in this example. Each client identifier
* must be unique so edit as required to ensure no two clients connecting to the
* same broker use the same client identifier.
*
*!!! Please note a #defined constant is used for convenience of demonstration
*!!! only. Production devices can use something unique to the device that can
*!!! be read by software, such as a production serial number, instead of a
*!!! hard coded constant.
*
* #define democonfigCLIENT_IDENTIFIER "...insert here..."
*/
#define democonfigCLIENT_IDENTIFIER "...insert here..."
/**
* @brief Endpoint of the MQTT broker to connect to.
*
* This demo application can be run with any MQTT broker, although it is
* recommended to use one that supports mutual authentication. If mutual
* authentication is not used, then #democonfigUSE_TLS should be set to 0.
*
* For AWS IoT MQTT broker, this is the Thing's REST API Endpoint.
*
* @note Your AWS IoT Core endpoint can be found in the AWS IoT console under
* Settings/Custom Endpoint, or using the describe-endpoint REST API (with
* AWS CLI command line tool).
*
* #define democonfigMQTT_BROKER_ENDPOINT "...insert here..."
*/
#define democonfigMQTT_BROKER_ENDPOINT "...insert here..."
/**
* @brief The port to use for the demo.
*
* In general, port 8883 is for secured MQTT connections, and port 1883 if not
* using TLS.
*
* @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol
* name. Using ALPN with this demo would require additional changes, including
* setting the `pAlpnProtos` member of the `NetworkCredentials_t` struct before
* forming the TLS connection. When using port 8883, ALPN is not required.
*
* #define democonfigMQTT_BROKER_PORT ( insert here. )
*/
#define democonfigMQTT_BROKER_PORT ( 8883 )
/**
* @brief Server's root CA certificate.
*
* For AWS IoT MQTT broker, this certificate is used to identify the AWS IoT
* server and is publicly available. Refer to the AWS documentation available
* in the link below.
* https://docs.aws.amazon.com/iot/latest/developerguide/server-authentication.html#server-authentication-certs
*
* @note This certificate should be PEM-encoded.
*
* @note If you would like to setup an MQTT broker for running this demo,
* please see `mqtt_broker_setup.txt`.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigROOT_CA_PEM "...insert here..."
*/
/**
* @brief Client certificate.
*
* For AWS IoT MQTT broker, refer to the AWS documentation below for details
* regarding client authentication.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigCLIENT_CERTIFICATE_PEM "...insert here..."
*/
/**
* @brief Client's private key.
*
*!!! Please note pasting a key into the header file in this manner is for
*!!! convenience of demonstration only and should not be done in production.
*!!! Never paste a production private key here!. Production devices should
*!!! store keys securely, such as within a secure element. Additionally,
*!!! we provide the corePKCS library that further enhances security by
*!!! enabling securely stored keys to be used without exposing them to
*!!! software.
*
* For AWS IoT MQTT broker, refer to the AWS documentation below for details
* regarding clientauthentication.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
*
* @note This private key should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN RSA PRIVATE KEY-----\n"\
* "...base64 data...\n"\
* "-----END RSA PRIVATE KEY-----\n"
*
* #define democonfigCLIENT_PRIVATE_KEY_PEM "...insert here..."
*/
/*
* @brief Server's root CA certificate for TLS authentication with S3.
*
* The Amazon Root CA Certificate is defined below.
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
*/
#ifndef democonfigHTTPS_ROOT_CA_PEM
#define democonfigHTTPS_ROOT_CA_PEM \
"-----BEGIN CERTIFICATE-----\n" \
"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \
"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \
"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \
"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \
"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \
"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \
"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \
"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \
"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \
"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \
"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \
"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \
"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \
"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \
"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \
"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \
"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \
"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \
"-----END CERTIFICATE-----\n"
#endif /* ifndef democonfigHTTPS_ROOT_CA_PEM */
/**
* @brief AWS IoT Core server port number for HTTPS connections.
*
* For this demo, an X.509 certificate is used to verify the client.
*
* @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol
* name being x-amzn-http-ca. When using port 8443, ALPN is not required.
*/
#define democonfigHTTPS_PORT 443
/**
* @brief An option to disable Server Name Indication.
*
* @note When using a local Mosquitto server setup, SNI needs to be disabled
* for an MQTT broker that only has an IP address but no hostname. However,
* SNI should be enabled whenever possible.
*/
#define democonfigDISABLE_SNI ( pdFALSE )
/**
* @brief Configuration that indicates if the demo connection is made to the AWS IoT Core MQTT broker.
*
* If username/password based authentication is used, the demo will use appropriate TLS ALPN and
* SNI configurations as required for the Custom Authentication feature of AWS IoT.
* For more information, refer to the following documentation:
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-auth.html#custom-auth-mqtt
*
* #define democonfigUSE_AWS_IOT_CORE_BROKER ( 1 )
*/
#define democonfigUSE_AWS_IOT_CORE_BROKER ( 1 )
/**
* @brief The username value for authenticating client to the MQTT broker when
* username/password based client authentication is used.
*
* For AWS IoT MQTT broker, refer to the AWS IoT documentation below for
* details regarding client authentication with a username and password.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* #define democonfigCLIENT_USERNAME "...insert here..."
*/
/**
* @brief The password value for authenticating client to the MQTT broker when
* username/password based client authentication is used.
*
* For AWS IoT MQTT broker, refer to the AWS IoT documentation below for
* details regarding client authentication with a username and password.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* #define democonfigCLIENT_PASSWORD "...insert here..."
*/
/**
* @brief The name of the operating system that the application is running on.
* The current value is given as an example. Please update for your specific
* operating system.
*/
#define democonfigOS_NAME "FreeRTOS"
/**
* @brief The version of the operating system that the application is running
* on. The current value is given as an example. Please update for your specific
* operating system version.
*/
#define democonfigOS_VERSION tskKERNEL_VERSION_NUMBER
/**
* @brief The name of the hardware platform the application is running on. The
* current value is given as an example. Please update for your specific
* hardware platform.
*/
#define democonfigHARDWARE_PLATFORM_NAME "WinSim"
/**
* @brief The name of the MQTT library used and its version, following an "@"
* symbol.
*/
#define democonfigMQTT_LIB "core-mqtt@1.0.0"
/**
* @brief Whether to use mutual authentication. If this macro is not set to 1
* or not defined, then plaintext TCP will be used instead of TLS over TCP.
*/
#define democonfigUSE_TLS 1
/**
* @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 */

View File

@ -0,0 +1,83 @@
/*
* FreeRTOS V202212.01
* 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/coremqtt for configuration and usage instructions.
***/
/* Standard includes. */
#include <stdio.h>
#include <time.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Demo logging includes. */
#include "logging.h"
/* Demo Specific configs. */
#include "demo_config.h"
/*-----------------------------------------------------------*/
extern void vOtaDemoTask( void * pvParameters );
extern void vPlatformInitIpStack( void );
/*-----------------------------------------------------------*/
int main( void )
{
vPlatformInitLogging();
xTaskCreate( vOtaDemoTask, /* Function that implements the task. */
"OTA Demo Task", /* Text name for the task - only used for debugging. */
democonfigDEMO_STACKSIZE, /* Size of stack (in words, not bytes) to allocate for the task. */
NULL, /* Optional - task parameter - not used in this case. */
tskIDLE_PRIORITY + 1, /* Task priority, must be between 0 and configMAX_PRIORITIES - 1. */
NULL ); /* Optional - used to pass out a handle to the created task. */
/* Initialize the FreeRTOS+TCP Stack */
vPlatformInitIpStack();
/* 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.
*/
for( ; ; )
{
configASSERT( pdFALSE );
}
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,200 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file ota_config.h
* @brief OTA user configurable settings.
*/
#ifndef OTA_CONFIG_H_
#define OTA_CONFIG_H_
/**************************************************/
/******* DO NOT CHANGE the following order ********/
/**************************************************/
/* Logging related header files are required to be included in the following order:
* 1. Include the header file "logging_levels.h".
* 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL.
* 3. Include the header file "logging_stack.h".
*/
/* Include header that defines log levels. */
#include "logging_levels.h"
/* Configure name and log level for the OTA library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "OTA"
#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 Log base 2 of the size of the file data block message (excluding the header).
*
* 10 bits yields a data block size of 1KB.
*/
#define otaconfigLOG2_FILE_BLOCK_SIZE 11UL
/**
* @brief Size of the file data block message (excluding the header).
*
*/
#define otaconfigFILE_BLOCK_SIZE ( 1UL << otaconfigLOG2_FILE_BLOCK_SIZE )
/**
* @brief Milliseconds to wait for the self test phase to succeed before we force reset.
*/
#define otaconfigSELF_TEST_RESPONSE_WAIT_MS 16000U
/**
* @brief Milliseconds to wait before requesting data blocks from the OTA service if nothing is happening.
*
* The wait timer is reset whenever a data block is received from the OTA service so we will only send
* the request message after being idle for this amount of time.
*/
#define otaconfigFILE_REQUEST_WAIT_MS 10000U
/**
* @brief The maximum allowed length of the thing name used by the OTA agent.
*
* AWS IoT requires Thing names to be unique for each device that connects to the broker.
* Likewise, the OTA agent requires the developer to construct and pass in the Thing name when
* initializing the OTA agent. The agent uses this size to allocate static storage for the
* Thing name used in all OTA base topics. Namely $aws/things/<thingName>
*/
#define otaconfigMAX_THINGNAME_LEN 128U
/**
* @brief The maximum number of data blocks requested from OTA streaming service.
*
* This configuration parameter is sent with data requests and represents the maximum number of
* data blocks the service will send in response. The maximum limit for this must be calculated
* from the maximum data response limit (128 KB from service) divided by the block size.
* For example if block size is set as 1 KB then the maximum number of data blocks that we can
* request is 128/1 = 128 blocks. Configure this parameter to this maximum limit or lower based on
* how many data blocks response is expected for each data requests.
* Please note that this must be set larger than zero.
*
*/
#define otaconfigMAX_NUM_BLOCKS_REQUEST 4U
/**
* @brief The maximum number of requests allowed to send without a response before we abort.
*
* This configuration parameter sets the maximum number of times the requests are made over
* the selected communication channel before aborting and returning error.
*
*/
#define otaconfigMAX_NUM_REQUEST_MOMENTUM 32U
/**
* @brief The number of data buffers reserved by the OTA agent.
*
* This configurations parameter sets the maximum number of static data buffers used by
* the OTA agent for job and file data blocks received.
*/
#define otaconfigMAX_NUM_OTA_DATA_BUFFERS 5U
/**
* @brief How frequently the device will report its OTA progress to the cloud.
*
* Device will update the job status with the number of blocks it has received every certain
* number of blocks it receives. For example, 25 means device will update job status every 25 blocks
* it receives.
*/
#define otaconfigOTA_UPDATE_STATUS_FREQUENCY 25U
/**
* @brief Allow update to same or lower version.
*
* Set this to 1 to allow downgrade or same version update.This configurations parameter
* disables version check and allows update to a same or lower version.This is provided for
* testing purpose and it is recommended to always update to higher version and keep this
* configuration disabled.
*/
#define otaconfigAllowDowngrade 0U
/**
* @brief The protocol selected for OTA control operations.
*
* This configurations parameter sets the default protocol for all the OTA control
* operations like requesting OTA job, updating the job status etc.
*
* Note - Only MQTT is supported at this time for control operations.
*/
#define configENABLED_CONTROL_PROTOCOL ( OTA_CONTROL_OVER_MQTT )
/**
* @brief The protocol selected for OTA data operations.
*
* This configurations parameter sets the protocols selected for the data operations
* like requesting file blocks from the service.
*
* Note - Both MQTT and HTTP is supported for data transfer from service. This configuration parameter
* can be set to following -
* Enable data over MQTT - ( OTA_DATA_OVER_MQTT )
* Enable data over HTTP - ( OTA_DATA_OVER_HTTP)
*
* Note - Please check the OTA over MQTT demo which has the MQTT data transfer functionality and
* and this configuration is set to OTA_DATA_OVER_MQTT.
*/
#define configENABLED_DATA_PROTOCOLS ( OTA_DATA_OVER_HTTP )
/**
* @brief The preferred protocol selected for OTA data operations.
*
* Primary data protocol will be the protocol used for downloading file if more than
* one protocol is selected while creating OTA job. Default primary data protocol is MQTT
* and following update here to switch to HTTP as primary.
*
* Note - use OTA_DATA_OVER_HTTP for HTTP as primary data protocol.
*/
#define configOTA_PRIMARY_DATA_PROTOCOL ( OTA_DATA_OVER_HTTP )
#endif /* OTA_CONFIG_H_ */

View File

@ -0,0 +1,116 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31205.134
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Ota_Over_Http_Demo", "Ota_Over_Http_Demo.vcxproj", "{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Statically Linked Libraries", "Statically Linked Libraries", "{9799AFF4-25E2-43CD-8829-C066177E3748}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS+TCP", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj", "{C90E6CC5-818B-4C97-8876-0986D989387C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ww", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj", "{72C209C4-49A4-4942-A201-44706C9D77EC}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Logging", "..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj", "{BE362AC0-B10B-4276-B84E-6304652BA228}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MbedTLS", "..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj", "{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "coreHTTP", "..\..\..\..\VisualStudio_StaticProjects\coreHTTP\coreHTTP.vcxproj", "{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Win32 = Release|Win32
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Debug|Win32.ActiveCfg = Debug|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Debug|Win32.Build.0 = Debug|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Debug|x64.ActiveCfg = Debug|x64
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Debug|x64.Build.0 = Debug|x64
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Debug|x86.ActiveCfg = Debug|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Debug|x86.Build.0 = Debug|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Release|Win32.ActiveCfg = Release|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Release|Win32.Build.0 = Release|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Release|x64.ActiveCfg = Release|x64
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Release|x64.Build.0 = Release|x64
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Release|x86.ActiveCfg = Release|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Release|x86.Build.0 = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|Win32.ActiveCfg = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|Win32.Build.0 = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.ActiveCfg = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.Build.0 = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x86.ActiveCfg = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x86.Build.0 = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|Win32.ActiveCfg = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|Win32.Build.0 = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.ActiveCfg = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.Build.0 = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x86.ActiveCfg = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x86.Build.0 = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|Win32.ActiveCfg = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|Win32.Build.0 = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.ActiveCfg = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.Build.0 = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x86.ActiveCfg = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x86.Build.0 = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|Win32.ActiveCfg = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|Win32.Build.0 = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.ActiveCfg = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.Build.0 = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x86.ActiveCfg = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x86.Build.0 = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|Win32.ActiveCfg = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|Win32.Build.0 = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.ActiveCfg = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.Build.0 = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x86.ActiveCfg = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x86.Build.0 = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|Win32.ActiveCfg = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|Win32.Build.0 = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.ActiveCfg = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.Build.0 = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x86.ActiveCfg = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x86.Build.0 = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|Win32.ActiveCfg = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|Win32.Build.0 = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.ActiveCfg = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.Build.0 = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x86.ActiveCfg = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x86.Build.0 = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|Win32.ActiveCfg = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|Win32.Build.0 = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.ActiveCfg = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.Build.0 = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x86.ActiveCfg = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x86.Build.0 = Release|Win32
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Debug|Win32.ActiveCfg = Debug|Win32
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Debug|Win32.Build.0 = Debug|Win32
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Debug|x64.ActiveCfg = Debug|x64
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Debug|x64.Build.0 = Debug|x64
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Debug|x86.ActiveCfg = Debug|Win32
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Debug|x86.Build.0 = Debug|Win32
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Release|Win32.ActiveCfg = Release|Win32
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Release|Win32.Build.0 = Release|Win32
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Release|x64.ActiveCfg = Release|x64
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Release|x64.Build.0 = Release|x64
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Release|x86.ActiveCfg = Release|Win32
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C90E6CC5-818B-4C97-8876-0986D989387C} = {9799AFF4-25E2-43CD-8829-C066177E3748}
{72C209C4-49A4-4942-A201-44706C9D77EC} = {9799AFF4-25E2-43CD-8829-C066177E3748}
{BE362AC0-B10B-4276-B84E-6304652BA228} = {9799AFF4-25E2-43CD-8829-C066177E3748}
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7} = {9799AFF4-25E2-43CD-8829-C066177E3748}
{EE39FA0F-CEFB-4C29-A571-05A28FDD47FD} = {9799AFF4-25E2-43CD-8829-C066177E3748}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {03800DFF-BAFA-4654-8E51-C4E654A54416}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,245 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{4be4e103-5bf4-4a85-9656-ec20852a2b8e}</ProjectGuid>
<RootNamespace>OtaOverMqttDemo</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<ProjectName>Ota_Over_Mqtt_Demo</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<TargetName>RTOSDemo</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<TargetName>RTOSDemo</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<TargetName>RTOSDemo</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<TargetName>RTOSDemo</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>MQTT_AGENT_DO_NOT_USE_CUSTOM_CONFIG;WIN32;__little_endian__=1;_DEBUG;_CONSOLE;WIN32;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h"</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\Common\coreMQTT_Agent_Interface\include;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\ota\source\include;..\..\..\..\Source\AWS\ota\source\portable\os;..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\Common\Ota_PAL\Win32\Code_Signature_Verification;..\Common\Ota_PAL\Win32;..\Common\subscription-manager;.\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>MQTT_AGENT_DO_NOT_USE_CUSTOM_CONFIG;WIN32;__little_endian__=1;WIN32;NDEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h"</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\Common\coreMQTT_Agent_Interface\include;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\ota\source\include;..\..\..\..\Source\AWS\ota\source\portable\os;..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\Common\Ota_PAL\Win32\Code_Signature_Verification;..\Common\Ota_PAL\Win32;..\Common\subscription-manager;.\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>MQTT_AGENT_DO_NOT_USE_CUSTOM_CONFIG;WIN32;__little_endian__=1;_DEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h"</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\Common\coreMQTT_Agent_Interface\include;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\ota\source\include;..\..\..\..\Source\AWS\ota\source\portable\os;..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\Common\Ota_PAL\Win32\Code_Signature_Verification;..\Common\Ota_PAL\Win32;..\Common\subscription-manager;.\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>MQTT_AGENT_DO_NOT_USE_CUSTOM_CONFIG;WIN32;__little_endian__=1;NDEBUG;_CONSOLE;MBEDTLS_CONFIG_FILE="mbedtls_config_v3.2.1.h"</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include;..\..\..\..\Source\Application-Protocols\network_transport;..\..\..\Common\coreMQTT_Agent_Interface\include;..\..\..\..\ThirdParty\tinycbor\src;..\..\..\..\Source\Utilities\backoff_algorithm\source\include;..\..\..\..\Source\coreJSON\source\include;..\..\..\..\Source\AWS\ota\source\include;..\..\..\..\Source\AWS\ota\source\portable\os;..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include;..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface;..\..\..\..\Source\Application-Protocols\coreMQTT\source\include;..\Common\Ota_PAL\Win32\Code_Signature_Verification;..\Common\Ota_PAL\Win32;..\Common\subscription-manager;.\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj">
<Project>{c90e6cc5-818b-4c97-8876-0986d989387c}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj">
<Project>{72c209c4-49a4-4942-a201-44706c9d77ec}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj">
<Project>{be362ac0-b10b-4276-b84e-6304652ba228}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj">
<Project>{e1016f3e-94e9-4864-9fd8-1d7c1fefbfd7}</Project>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\core_mqtt_agent.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\core_mqtt_agent_command_functions.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c" />
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_base64.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_cbor.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_http.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_interface.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_mqtt.c" />
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\portable\os\ota_os_freertos.c" />
<ClCompile Include="..\..\..\..\Source\coreJSON\source\core_json.c" />
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder_close_container_checked.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborerrorstrings.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser_dup_string.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborpretty.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborpretty_stdio.c" />
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborvalidation.c" />
<ClCompile Include="..\..\..\Common\coreMQTT_Agent_Interface\freertos_agent_message.c" />
<ClCompile Include="..\..\..\Common\coreMQTT_Agent_Interface\freertos_command_pool.c" />
<ClCompile Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\code_signature_verification_mbedtls.c" />
<ClCompile Include="..\Common\Ota_PAL\Win32\ota_pal.c" />
<ClCompile Include="..\Common\subscription-manager\subscription_manager.c" />
<ClCompile Include="DemoTasks\OtaOverMqttDemoExample.c" />
<ClCompile Include="main.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent_command_functions.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent_message_interface.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h" />
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_appversion32.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_base64_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_cbor_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_config_defaults.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_http_interface.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_http_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_interface_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_mqtt_interface.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_mqtt_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_os_interface.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_platform_interface.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_private.h" />
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\portable\os\ota_os_freertos.h" />
<ClInclude Include="..\..\..\..\Source\coreJSON\source\include\core_json.h" />
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cbor.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborinternal_p.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborjson.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\compilersupport_p.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\tinycbor-version.h" />
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\utf8_p.h" />
<ClInclude Include="..\..\..\Common\coreMQTT_Agent_Interface\include\freertos_agent_message.h" />
<ClInclude Include="..\..\..\Common\coreMQTT_Agent_Interface\include\freertos_command_pool.h" />
<ClInclude Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\aws_ota_codesigner_certificate.h" />
<ClInclude Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\code_signature_verification.h" />
<ClInclude Include="..\Common\Ota_PAL\Win32\ota_pal.h" />
<ClInclude Include="..\Common\subscription-manager\subscription_manager.h" />
<ClInclude Include="core_mqtt_config.h" />
<ClInclude Include="demo_config.h" />
<ClInclude Include="ota_config.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,330 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="Additional Network Transport Files">
<UniqueIdentifier>{d8a6eab8-52e5-4e4f-a9b9-cd5d8eb3454a}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries">
<UniqueIdentifier>{18d8589f-6af4-4627-b7fe-e1c9bdfecdd8}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT OTA">
<UniqueIdentifier>{6eb6582b-1dce-411e-bc0b-841a09741615}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm">
<UniqueIdentifier>{3d266f56-5fd1-4585-9a72-3eef3ee1ee53}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreJSON">
<UniqueIdentifier>{96471440-eb47-4085-a08f-8576fa6fac34}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT">
<UniqueIdentifier>{4e394147-c8cd-4245-b188-0b4827b1875e}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT-Agent">
<UniqueIdentifier>{4e2b22e6-880f-40a0-8b4e-be5e8d3471b2}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\TinyCBOR">
<UniqueIdentifier>{228e794f-fa2d-44ec-ad49-95d6820434a2}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT OTA\portable">
<UniqueIdentifier>{71c883e5-7eb1-44fe-bbcb-5a2b6c3e4d15}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\AWS IoT OTA\include">
<UniqueIdentifier>{b3aeb9e5-1b4f-4652-b24a-49a8c406113e}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\Backoff Algorithm\include">
<UniqueIdentifier>{163f3bc7-7054-4400-8c9e-7f8ac07307f8}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreJSON\include">
<UniqueIdentifier>{6db5c3a5-4750-40b1-9c8c-38e90fa37f9a}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\include">
<UniqueIdentifier>{2e0ccf6e-a4ca-4349-93ed-5eafa843095b}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT\interface">
<UniqueIdentifier>{a8c75d87-1984-4285-af5c-15146e3dba37}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\coreMQTT-Agent\include">
<UniqueIdentifier>{5e99c65f-35d7-4c3d-9055-9c7759e6f26b}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Libraries\TinyCBOR\include">
<UniqueIdentifier>{d90df1a1-4234-4da5-b3c3-46aa7947a06d}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files">
<UniqueIdentifier>{b4d0329a-2859-4ba6-a690-ce91db59b325}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\OTA PAL">
<UniqueIdentifier>{86c10d39-5f4e-4818-aad7-c565dd268bef}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\OTA PAL\Code Signature Verification MbedTLS">
<UniqueIdentifier>{a563c8c2-aada-4f3e-b77a-43db3cf9e26e}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\OTA PAL\include">
<UniqueIdentifier>{b89e35af-5342-46c6-84f2-24aa5761e368}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\OTA PAL\Code Signature Verification MbedTLS\include">
<UniqueIdentifier>{ed32e5c5-0bcb-49b9-9328-7b01d3becdf3}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\coreMQTT Agent Interface">
<UniqueIdentifier>{d1acbc8c-cc4d-4c81-8ee0-a68922cc6f1a}</UniqueIdentifier>
</Filter>
<Filter Include="Port Files\coreMQTT Agent Interface\include">
<UniqueIdentifier>{9df90bb5-248f-42cb-8a1c-4b657078898e}</UniqueIdentifier>
</Filter>
<Filter Include="Config">
<UniqueIdentifier>{9d109ee1-e478-4150-98b3-e76597cecb83}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper">
<UniqueIdentifier>{146d613c-d6d6-428a-8506-82924c74a9c9}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport">
<UniqueIdentifier>{7e781ff5-e562-4412-b8e9-8b215c6d7c39}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include">
<UniqueIdentifier>{b44e49dc-4b85-41cc-a37a-22c6d33950f1}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\include">
<UniqueIdentifier>{041aed9a-2876-41f7-859d-e257a7faf509}</UniqueIdentifier>
</Filter>
<Filter Include="Additional Network Transport Files\TCP Sockets Wrapper\ports">
<UniqueIdentifier>{5fe3deb2-b82c-4366-98c5-51742c6c1228}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Common\subscription-manager\subscription_manager.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_base64.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_cbor.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_http.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_interface.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\ota_mqtt.c">
<Filter>Additional Libraries\AWS IoT OTA</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\AWS\ota\source\portable\os\ota_os_freertos.c">
<Filter>Additional Libraries\AWS IoT OTA\portable</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\backoff_algorithm.c">
<Filter>Additional Libraries\Backoff Algorithm</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\coreJSON\source\core_json.c">
<Filter>Additional Libraries\coreJSON</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_serializer.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\core_mqtt_state.c">
<Filter>Additional Libraries\coreMQTT</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\core_mqtt_agent.c">
<Filter>Additional Libraries\coreMQTT-Agent</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\core_mqtt_agent_command_functions.c">
<Filter>Additional Libraries\coreMQTT-Agent</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborencoder_close_container_checked.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborerrorstrings.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborparser_dup_string.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborpretty.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborpretty_stdio.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\ThirdParty\tinycbor\src\cborvalidation.c">
<Filter>Additional Libraries\TinyCBOR</Filter>
</ClCompile>
<ClCompile Include="..\Common\Ota_PAL\Win32\ota_pal.c">
<Filter>Port Files\OTA PAL</Filter>
</ClCompile>
<ClCompile Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\code_signature_verification_mbedtls.c">
<Filter>Port Files\OTA PAL\Code Signature Verification MbedTLS</Filter>
</ClCompile>
<ClCompile Include="..\..\..\Common\coreMQTT_Agent_Interface\freertos_agent_message.c">
<Filter>Port Files\coreMQTT Agent Interface</Filter>
</ClCompile>
<ClCompile Include="..\..\..\Common\coreMQTT_Agent_Interface\freertos_command_pool.c">
<Filter>Port Files\coreMQTT Agent Interface</Filter>
</ClCompile>
<ClCompile Include="DemoTasks\OtaOverMqttDemoExample.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport</Filter>
</ClCompile>
<ClCompile Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\ports\freertos_plus_tcp\tcp_sockets_wrapper.c">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\ports</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Common\subscription-manager\subscription_manager.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\portable\os\ota_os_freertos.h">
<Filter>Additional Libraries\AWS IoT OTA\portable</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_appversion32.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_base64_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_cbor_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_config_defaults.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_http_interface.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_http_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_interface_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_mqtt_interface.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_mqtt_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_os_interface.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_platform_interface.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\AWS\ota\source\include\ota_private.h">
<Filter>Additional Libraries\AWS IoT OTA\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Utilities\backoff_algorithm\source\include\backoff_algorithm.h">
<Filter>Additional Libraries\Backoff Algorithm\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\coreJSON\source\include\core_json.h">
<Filter>Additional Libraries\coreJSON\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\interface\transport_interface.h">
<Filter>Additional Libraries\coreMQTT\interface</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_config_defaults.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_serializer.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT\source\include\core_mqtt_state.h">
<Filter>Additional Libraries\coreMQTT\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent.h">
<Filter>Additional Libraries\coreMQTT-Agent\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent_command_functions.h">
<Filter>Additional Libraries\coreMQTT-Agent\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\coreMQTT-Agent\source\include\core_mqtt_agent_message_interface.h">
<Filter>Additional Libraries\coreMQTT-Agent\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cbor.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborinternal_p.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\cborjson.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\compilersupport_p.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\tinycbor-version.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\ThirdParty\tinycbor\src\utf8_p.h">
<Filter>Additional Libraries\TinyCBOR\include</Filter>
</ClInclude>
<ClInclude Include="..\Common\Ota_PAL\Win32\ota_pal.h">
<Filter>Port Files\OTA PAL\include</Filter>
</ClInclude>
<ClInclude Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\code_signature_verification.h">
<Filter>Port Files\OTA PAL\Code Signature Verification MbedTLS\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\Common\coreMQTT_Agent_Interface\include\freertos_agent_message.h">
<Filter>Port Files\coreMQTT Agent Interface\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\Common\coreMQTT_Agent_Interface\include\freertos_command_pool.h">
<Filter>Port Files\coreMQTT Agent Interface\include</Filter>
</ClInclude>
<ClInclude Include="..\Common\Ota_PAL\Win32\Code_Signature_Verification\aws_ota_codesigner_certificate.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="core_mqtt_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="demo_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="ota_config.h">
<Filter>Config</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\mbedtls_bio_tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\transport_mbedtls.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper + MbedTLS Transport\include</Filter>
</ClInclude>
<ClInclude Include="..\..\..\..\Source\Application-Protocols\network_transport\tcp_sockets_wrapper\include\tcp_sockets_wrapper.h">
<Filter>Additional Network Transport Files\TCP Sockets Wrapper\include</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,109 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#ifndef CORE_MQTT_CONFIG_H
#define CORE_MQTT_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 MQTT.
* 3. Include the header file "logging_stack.h", if logging is enabled for MQTT.
*/
#include "logging_levels.h"
/* Logging configuration for the MQTT library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "MQTT"
#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 ****************/
/**
* @brief The maximum number of MQTT PUBLISH messages that may be pending
* acknowledgement at any time.
*
* QoS 1 and 2 MQTT PUBLISHes require acknowledgment from the server before
* they can be completed. While they are awaiting the acknowledgment, the
* client must maintain information about their state. The value of this
* macro sets the limit on how many simultaneous PUBLISH states an MQTT
* context maintains.
*/
#define MQTT_STATE_ARRAY_MAX_COUNT 10U
/*********************** coreMQTT Agent Configurations **********************/
/**
* @brief The maximum number of pending acknowledgments to track for a single
* connection.
*
* @note The MQTT agent tracks MQTT commands (such as PUBLISH and SUBSCRIBE) th
* at are still waiting to be acknowledged. MQTT_AGENT_MAX_OUTSTANDING_ACKS set
* the maximum number of acknowledgments that can be outstanding at any one time.
* The higher this number is the greater the agent's RAM consumption will be.
*/
#define MQTT_AGENT_MAX_OUTSTANDING_ACKS ( 20U )
/**
* @brief Time in MS that the MQTT agent task will wait in the Blocked state (so
* not using any CPU time) for a command to arrive in its command queue before
* exiting the blocked state so it can call MQTT_ProcessLoop().
*
* @note It is important MQTT_ProcessLoop() is called often if there is known
* MQTT traffic, but calling it too often can take processing time away from
* lower priority tasks and waste CPU time and power.
*/
#define MQTT_AGENT_MAX_EVENT_QUEUE_WAIT_TIME ( 1000 )
/**
* @brief The number of command structures to allocate in the pool
* for the agent.
*/
#define MQTT_COMMAND_CONTEXTS_POOL_SIZE 10
#endif /* ifndef CORE_MQTT_CONFIG_H */

View File

@ -0,0 +1,276 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
#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 "OTADemo"
#endif
#ifndef LIBRARY_LOG_LEVEL
#define LIBRARY_LOG_LEVEL LOG_DEBUG
#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 version for the firmware which is running. OTA agent uses this
* version number to perform anti-rollback validation. The firmware version for the
* download image should be higher than the current version, otherwise the new image is
* rejected in self test phase.
*/
#define APP_VERSION_MAJOR 0
#define APP_VERSION_MINOR 9
#define APP_VERSION_BUILD 2
/**
* @brief The MQTT client identifier used in this example. Each client identifier
* must be unique so edit as required to ensure no two clients connecting to the
* same broker use the same client identifier.
*
*!!! Please note a #defined constant is used for convenience of demonstration
*!!! only. Production devices can use something unique to the device that can
*!!! be read by software, such as a production serial number, instead of a
*!!! hard coded constant.
*
* #define democonfigCLIENT_IDENTIFIER "...insert here..."
*/
#define democonfigCLIENT_IDENTIFIER "...insert here..."
/**
* @brief Endpoint of the MQTT broker to connect to.
*
* This demo application can be run with any MQTT broker, although it is
* recommended to use one that supports mutual authentication. If mutual
* authentication is not used, then #democonfigUSE_TLS should be set to 0.
*
* For AWS IoT MQTT broker, this is the Thing's REST API Endpoint.
*
* @note Your AWS IoT Core endpoint can be found in the AWS IoT console under
* Settings/Custom Endpoint, or using the describe-endpoint REST API (with
* AWS CLI command line tool).
*
* #define democonfigMQTT_BROKER_ENDPOINT "...insert here..."
*/
#define democonfigMQTT_BROKER_ENDPOINT "...insert here..."
/**
* @brief The port to use for the demo.
*
* In general, port 8883 is for secured MQTT connections, and port 1883 if not
* using TLS.
*
* @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol
* name. Using ALPN with this demo would require additional changes, including
* setting the `pAlpnProtos` member of the `NetworkCredentials_t` struct before
* forming the TLS connection. When using port 8883, ALPN is not required.
*
* #define democonfigMQTT_BROKER_PORT ( insert here. )
*/
#define democonfigMQTT_BROKER_PORT ( 8883 )
/**
* @brief Server's root CA certificate.
*
* For AWS IoT MQTT broker, this certificate is used to identify the AWS IoT
* server and is publicly available. Refer to the AWS documentation available
* in the link below.
* https://docs.aws.amazon.com/iot/latest/developerguide/server-authentication.html#server-authentication-certs
*
* @note This certificate should be PEM-encoded.
*
* @note If you would like to setup an MQTT broker for running this demo,
* please see `mqtt_broker_setup.txt`.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigROOT_CA_PEM "...insert here..."
*/
/**
* @brief Client certificate.
*
* For AWS IoT MQTT broker, refer to the AWS documentation below for details
* regarding client authentication.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
*
* @note This certificate should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN CERTIFICATE-----\n"\
* "...base64 data...\n"\
* "-----END CERTIFICATE-----\n"
*
* #define democonfigCLIENT_CERTIFICATE_PEM "...insert here..."
*/
/**
* @brief Client's private key.
*
*!!! Please note pasting a key into the header file in this manner is for
*!!! convenience of demonstration only and should not be done in production.
*!!! Never paste a production private key here!. Production devices should
*!!! store keys securely, such as within a secure element. Additionally,
*!!! we provide the corePKCS library that further enhances security by
*!!! enabling securely stored keys to be used without exposing them to
*!!! software.
*
* For AWS IoT MQTT broker, refer to the AWS documentation below for details
* regarding clientauthentication.
* https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html
*
* @note This private key should be PEM-encoded.
*
* Must include the PEM header and footer:
* "-----BEGIN RSA PRIVATE KEY-----\n"\
* "...base64 data...\n"\
* "-----END RSA PRIVATE KEY-----\n"
*
* #define democonfigCLIENT_PRIVATE_KEY_PEM "...insert here..."
*/
/**
* @brief An option to disable Server Name Indication.
*
* @note When using a local Mosquitto server setup, SNI needs to be disabled
* for an MQTT broker that only has an IP address but no hostname. However,
* SNI should be enabled whenever possible.
*/
#define democonfigDISABLE_SNI ( pdFALSE )
/**
* @brief Configuration that indicates if the demo connection is made to the AWS IoT Core MQTT broker.
*
* If username/password based authentication is used, the demo will use appropriate TLS ALPN and
* SNI configurations as required for the Custom Authentication feature of AWS IoT.
* For more information, refer to the following documentation:
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-auth.html#custom-auth-mqtt
*
* #define democonfigUSE_AWS_IOT_CORE_BROKER ( 1 )
*/
#define democonfigUSE_AWS_IOT_CORE_BROKER ( 1 )
/**
* @brief The username value for authenticating client to the MQTT broker when
* username/password based client authentication is used.
*
* For AWS IoT MQTT broker, refer to the AWS IoT documentation below for
* details regarding client authentication with a username and password.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* #define democonfigCLIENT_USERNAME "...insert here..."
*/
/**
* @brief The password value for authenticating client to the MQTT broker when
* username/password based client authentication is used.
*
* For AWS IoT MQTT broker, refer to the AWS IoT documentation below for
* details regarding client authentication with a username and password.
* https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html
* An authorizer setup needs to be done, as mentioned in the above link, to use
* username/password based client authentication.
*
* #define democonfigCLIENT_PASSWORD "...insert here..."
*/
/**
* @brief The name of the operating system that the application is running on.
* The current value is given as an example. Please update for your specific
* operating system.
*/
#define democonfigOS_NAME "FreeRTOS"
/**
* @brief The version of the operating system that the application is running
* on. The current value is given as an example. Please update for your specific
* operating system version.
*/
#define democonfigOS_VERSION tskKERNEL_VERSION_NUMBER
/**
* @brief The name of the hardware platform the application is running on. The
* current value is given as an example. Please update for your specific
* hardware platform.
*/
#define democonfigHARDWARE_PLATFORM_NAME "WinSim"
/**
* @brief The name of the MQTT library used and its version, following an "@"
* symbol.
*/
#define democonfigMQTT_LIB "core-mqtt@1.0.0"
/**
* @brief Whether to use mutual authentication. If this macro is not set to 1
* or not defined, then plaintext TCP will be used instead of TLS over TCP.
*/
#define democonfigUSE_TLS 1
/**
* @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 */

View File

@ -0,0 +1,83 @@
/*
* FreeRTOS V202212.01
* 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/coremqtt for configuration and usage instructions.
***/
/* Standard includes. */
#include <stdio.h>
#include <time.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Demo logging includes. */
#include "logging.h"
/* Demo Specific configs. */
#include "demo_config.h"
/*-----------------------------------------------------------*/
extern void vOtaDemoTask( void * pvParameters );
extern void vPlatformInitIpStack( void );
/*-----------------------------------------------------------*/
int main( void )
{
vPlatformInitLogging();
xTaskCreate( vOtaDemoTask, /* Function that implements the task. */
"OTA Demo Task", /* Text name for the task - only used for debugging. */
democonfigDEMO_STACKSIZE, /* Size of stack (in words, not bytes) to allocate for the task. */
NULL, /* Optional - task parameter - not used in this case. */
tskIDLE_PRIORITY + 1, /* Task priority, must be between 0 and configMAX_PRIORITIES - 1. */
NULL ); /* Optional - used to pass out a handle to the created task. */
/* Initialize the FreeRTOS+TCP Stack */
vPlatformInitIpStack();
/* 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.
*/
for( ; ; )
{
configASSERT( pdFALSE );
}
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,200 @@
/*
* FreeRTOS V202212.01
* 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
*
*/
/**
* @file ota_config.h
* @brief OTA user configurable settings.
*/
#ifndef OTA_CONFIG_H_
#define OTA_CONFIG_H_
/**************************************************/
/******* DO NOT CHANGE the following order ********/
/**************************************************/
/* Logging related header files are required to be included in the following order:
* 1. Include the header file "logging_levels.h".
* 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL.
* 3. Include the header file "logging_stack.h".
*/
/* Include header that defines log levels. */
#include "logging_levels.h"
/* Configure name and log level for the OTA library. */
#ifndef LIBRARY_LOG_NAME
#define LIBRARY_LOG_NAME "OTA"
#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 Log base 2 of the size of the file data block message (excluding the header).
*
* 10 bits yields a data block size of 1KB.
*/
#define otaconfigLOG2_FILE_BLOCK_SIZE 11UL
/**
* @brief Size of the file data block message (excluding the header).
*
*/
#define otaconfigFILE_BLOCK_SIZE ( 1UL << otaconfigLOG2_FILE_BLOCK_SIZE )
/**
* @brief Milliseconds to wait for the self test phase to succeed before we force reset.
*/
#define otaconfigSELF_TEST_RESPONSE_WAIT_MS 16000U
/**
* @brief Milliseconds to wait before requesting data blocks from the OTA service if nothing is happening.
*
* The wait timer is reset whenever a data block is received from the OTA service so we will only send
* the request message after being idle for this amount of time.
*/
#define otaconfigFILE_REQUEST_WAIT_MS 10000U
/**
* @brief The maximum allowed length of the thing name used by the OTA agent.
*
* AWS IoT requires Thing names to be unique for each device that connects to the broker.
* Likewise, the OTA agent requires the developer to construct and pass in the Thing name when
* initializing the OTA agent. The agent uses this size to allocate static storage for the
* Thing name used in all OTA base topics. Namely $aws/things/<thingName>
*/
#define otaconfigMAX_THINGNAME_LEN 128U
/**
* @brief The maximum number of data blocks requested from OTA streaming service.
*
* This configuration parameter is sent with data requests and represents the maximum number of
* data blocks the service will send in response. The maximum limit for this must be calculated
* from the maximum data response limit (128 KB from service) divided by the block size.
* For example if block size is set as 1 KB then the maximum number of data blocks that we can
* request is 128/1 = 128 blocks. Configure this parameter to this maximum limit or lower based on
* how many data blocks response is expected for each data requests.
* Please note that this must be set larger than zero.
*
*/
#define otaconfigMAX_NUM_BLOCKS_REQUEST 4U
/**
* @brief The maximum number of requests allowed to send without a response before we abort.
*
* This configuration parameter sets the maximum number of times the requests are made over
* the selected communication channel before aborting and returning error.
*
*/
#define otaconfigMAX_NUM_REQUEST_MOMENTUM 32U
/**
* @brief The number of data buffers reserved by the OTA agent.
*
* This configurations parameter sets the maximum number of static data buffers used by
* the OTA agent for job and file data blocks received.
*/
#define otaconfigMAX_NUM_OTA_DATA_BUFFERS 5U
/**
* @brief How frequently the device will report its OTA progress to the cloud.
*
* Device will update the job status with the number of blocks it has received every certain
* number of blocks it receives. For example, 25 means device will update job status every 25 blocks
* it receives.
*/
#define otaconfigOTA_UPDATE_STATUS_FREQUENCY 25U
/**
* @brief Allow update to same or lower version.
*
* Set this to 1 to allow downgrade or same version update.This configurations parameter
* disables version check and allows update to a same or lower version.This is provided for
* testing purpose and it is recommended to always update to higher version and keep this
* configuration disabled.
*/
#define otaconfigAllowDowngrade 0U
/**
* @brief The protocol selected for OTA control operations.
*
* This configurations parameter sets the default protocol for all the OTA control
* operations like requesting OTA job, updating the job status etc.
*
* Note - Only MQTT is supported at this time for control operations.
*/
#define configENABLED_CONTROL_PROTOCOL ( OTA_CONTROL_OVER_MQTT )
/**
* @brief The protocol selected for OTA data operations.
*
* This configurations parameter sets the protocols selected for the data operations
* like requesting file blocks from the service.
*
* Note - Both MQTT and HTTP is supported for data transfer from service. This configuration parameter
* can be set to following -
* Enable data over MQTT - ( OTA_DATA_OVER_MQTT )
* Enable data over HTTP - ( OTA_DATA_OVER_HTTP)
*
* Note - Please check the OTA over HTTP demo which has the HTTP data transfer functionality and
* and this configuration is set to OTA_DATA_OVER_HTTP.
*/
#define configENABLED_DATA_PROTOCOLS ( OTA_DATA_OVER_MQTT )
/**
* @brief The preferred protocol selected for OTA data operations.
*
* Primary data protocol will be the protocol used for downloading file if more than
* one protocol is selected while creating OTA job. Default primary data protocol is MQTT
* and following update here to switch to HTTP as primary.
*
* Note - use OTA_DATA_OVER_HTTP for HTTP as primary data protocol.
*/
#define configOTA_PRIMARY_DATA_PROTOCOL ( OTA_DATA_OVER_MQTT )
#endif /* OTA_CONFIG_H_ */

View File

@ -0,0 +1,79 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31205.134
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Statically Linked Libraries", "Statically Linked Libraries", "{9799AFF4-25E2-43CD-8829-C066177E3748}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS+TCP", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS+TCP\FreeRTOS+TCP.vcxproj", "{C90E6CC5-818B-4C97-8876-0986D989387C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeRTOS-Kernel", "..\..\..\..\VisualStudio_StaticProjects\FreeRTOS-Kernel\FreeRTOS-Kernel.vcxproj", "{72C209C4-49A4-4942-A201-44706C9D77EC}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Logging", "..\..\..\..\VisualStudio_StaticProjects\Logging\Logging.vcxproj", "{BE362AC0-B10B-4276-B84E-6304652BA228}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MbedTLS", "..\..\..\..\VisualStudio_StaticProjects\MbedTLS\MbedTLS.vcxproj", "{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Ota_Over_Mqtt_Demo", "Ota_Over_Mqtt_Demo.vcxproj", "{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.ActiveCfg = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x64.Build.0 = Debug|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x86.ActiveCfg = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Debug|x86.Build.0 = Debug|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.ActiveCfg = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x64.Build.0 = Release|x64
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x86.ActiveCfg = Release|Win32
{C90E6CC5-818B-4C97-8876-0986D989387C}.Release|x86.Build.0 = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.ActiveCfg = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x64.Build.0 = Debug|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x86.ActiveCfg = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Debug|x86.Build.0 = Debug|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.ActiveCfg = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x64.Build.0 = Release|x64
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x86.ActiveCfg = Release|Win32
{72C209C4-49A4-4942-A201-44706C9D77EC}.Release|x86.Build.0 = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.ActiveCfg = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x64.Build.0 = Debug|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x86.ActiveCfg = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Debug|x86.Build.0 = Debug|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.ActiveCfg = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x64.Build.0 = Release|x64
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x86.ActiveCfg = Release|Win32
{BE362AC0-B10B-4276-B84E-6304652BA228}.Release|x86.Build.0 = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.ActiveCfg = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x64.Build.0 = Debug|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x86.ActiveCfg = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Debug|x86.Build.0 = Debug|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.ActiveCfg = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x64.Build.0 = Release|x64
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x86.ActiveCfg = Release|Win32
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7}.Release|x86.Build.0 = Release|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Debug|x64.ActiveCfg = Debug|x64
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Debug|x64.Build.0 = Debug|x64
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Debug|x86.ActiveCfg = Debug|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Debug|x86.Build.0 = Debug|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Release|x64.ActiveCfg = Release|x64
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Release|x64.Build.0 = Release|x64
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Release|x86.ActiveCfg = Release|Win32
{4BE4E103-5BF4-4A85-9656-EC20852A2B8E}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C90E6CC5-818B-4C97-8876-0986D989387C} = {9799AFF4-25E2-43CD-8829-C066177E3748}
{72C209C4-49A4-4942-A201-44706C9D77EC} = {9799AFF4-25E2-43CD-8829-C066177E3748}
{BE362AC0-B10B-4276-B84E-6304652BA228} = {9799AFF4-25E2-43CD-8829-C066177E3748}
{E1016F3E-94E9-4864-9FD8-1D7C1FEFBFD7} = {9799AFF4-25E2-43CD-8829-C066177E3748}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {03800DFF-BAFA-4654-8E51-C4E654A54416}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,5 @@
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
[InternetShortcut]
URL=http://www.freertos.org/labs
IDList=

View File

@ -0,0 +1,353 @@
/*
* FreeRTOS+TCP V2.0.3
* Copyright (C) 2017 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://aws.amazon.com/freertos
* https://www.FreeRTOS.org
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_TCP_server.h"
#include "FreeRTOS_server_private.h"
/* Remove the entire file if TCP is not being used. */
#if( ipconfigUSE_TCP == 1 ) && ( ( ipconfigUSE_HTTP == 1 ) || ( ipconfigUSE_FTP == 1 ) )
#if !defined( ARRAY_SIZE )
#define ARRAY_SIZE(x) ( BaseType_t ) (sizeof( x ) / sizeof( x )[ 0 ] )
#endif
static void prvReceiveNewClient( TCPServer_t *pxServer, BaseType_t xIndex, Socket_t xNexSocket );
static char *strnew( const char *pcString );
/* Remove slashes at the end of a path. */
static void prvRemoveSlash( char *pcDir );
TCPServer_t *FreeRTOS_CreateTCPServer( const struct xSERVER_CONFIG *pxConfigs, BaseType_t xCount )
{
TCPServer_t *pxServer;
SocketSet_t xSocketSet;
/* Create a new server.
xPort / xPortAlt : Make the service available on 1 or 2 public port numbers. */
xSocketSet = FreeRTOS_CreateSocketSet();
if( xSocketSet != NULL )
{
BaseType_t xSize;
xSize = sizeof( *pxServer ) - sizeof( pxServer->xServers ) + xCount * sizeof( pxServer->xServers[ 0 ] );
pxServer = ( TCPServer_t * ) pvPortMallocLarge( xSize );
if( pxServer != NULL )
{
struct freertos_sockaddr xAddress;
BaseType_t xNoTimeout = 0;
BaseType_t xIndex;
memset( pxServer, '\0', xSize );
pxServer->xServerCount = xCount;
pxServer->xSocketSet = xSocketSet;
for( xIndex = 0; xIndex < xCount; xIndex++ )
{
BaseType_t xPortNumber = pxConfigs[ xIndex ].xPortNumber;
if( xPortNumber > 0 )
{
Socket_t xSocket;
xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP );
FreeRTOS_printf( ( "TCP socket on port %d\n", ( int )xPortNumber ) );
if( xSocket != FREERTOS_INVALID_SOCKET )
{
xAddress.sin_addr = FreeRTOS_GetIPAddress(); // Single NIC, currently not used
xAddress.sin_port = FreeRTOS_htons( xPortNumber );
FreeRTOS_bind( xSocket, &xAddress, sizeof( xAddress ) );
FreeRTOS_listen( xSocket, pxConfigs[ xIndex ].xBackLog );
FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, ( void * ) &xNoTimeout, sizeof( BaseType_t ) );
FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDTIMEO, ( void * ) &xNoTimeout, sizeof( BaseType_t ) );
#if( ipconfigHTTP_RX_BUFSIZE > 0 )
{
if( pxConfigs[ xIndex ].eType == eSERVER_HTTP )
{
WinProperties_t xWinProps;
memset( &xWinProps, '\0', sizeof( xWinProps ) );
/* The parent socket itself won't get connected. The properties below
will be inherited by each new child socket. */
xWinProps.lTxBufSize = ipconfigHTTP_TX_BUFSIZE;
xWinProps.lTxWinSize = ipconfigHTTP_TX_WINSIZE;
xWinProps.lRxBufSize = ipconfigHTTP_RX_BUFSIZE;
xWinProps.lRxWinSize = ipconfigHTTP_RX_WINSIZE;
/* Set the window and buffer sizes. */
FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_WIN_PROPERTIES, ( void * ) &xWinProps, sizeof( xWinProps ) );
}
}
#endif
FreeRTOS_FD_SET( xSocket, xSocketSet, eSELECT_READ|eSELECT_EXCEPT );
pxServer->xServers[ xIndex ].xSocket = xSocket;
pxServer->xServers[ xIndex ].eType = pxConfigs[ xIndex ].eType;
pxServer->xServers[ xIndex ].pcRootDir = strnew( pxConfigs[ xIndex ].pcRootDir );
prvRemoveSlash( ( char * ) pxServer->xServers[ xIndex ].pcRootDir );
}
}
}
}
else
{
/* Could not allocate the server, delete the socket set */
FreeRTOS_DeleteSocketSet( xSocketSet );
}
}
else
{
/* Could not create a socket set, return NULL */
pxServer = NULL;
}
return pxServer;
}
/*-----------------------------------------------------------*/
static void prvReceiveNewClient( TCPServer_t *pxServer, BaseType_t xIndex, Socket_t xNexSocket )
{
TCPClient_t *pxClient = NULL;
BaseType_t xSize = 0;
FTCPWorkFunction fWorkFunc = NULL;
FTCPDeleteFunction fDeleteFunc = NULL;
const char *pcType = "Unknown";
/*_RB_ Can the work and delete functions be part of the xSERVER_CONFIG structure
becomes generic, with no pre-processing required? */
#if( ipconfigUSE_HTTP != 0 )
{
if( pxServer->xServers[ xIndex ].eType == eSERVER_HTTP )
{
xSize = sizeof( HTTPClient_t );
fWorkFunc = xHTTPClientWork;
fDeleteFunc = vHTTPClientDelete;
pcType = "HTTP";
}
}
#endif /* ipconfigUSE_HTTP != 0 */
#if( ipconfigUSE_FTP != 0 )
{
if( pxServer->xServers[ xIndex ].eType == eSERVER_FTP )
{
xSize = sizeof( FTPClient_t );
fWorkFunc = xFTPClientWork;
fDeleteFunc = vFTPClientDelete;
pcType = "FTP";
}
}
#endif /* ipconfigUSE_FTP != 0 */
/* Malloc enough space for a new HTTP-client */
if( xSize )
{
pxClient = ( TCPClient_t* ) pvPortMallocLarge( xSize );
}
if( pxClient != NULL )
{
memset( pxClient, '\0', xSize );
/* Put the new client in front of the list. */
pxClient->eType = pxServer->xServers[ xIndex ].eType;
pxClient->pcRootDir = pxServer->xServers[ xIndex ].pcRootDir;
pxClient->pxParent = pxServer;
pxClient->xSocket = xNexSocket;
pxClient->pxNextClient = pxServer->pxClients;
pxClient->fWorkFunction = fWorkFunc;
pxClient->fDeleteFunction = fDeleteFunc;
pxServer->pxClients = pxClient;
FreeRTOS_FD_SET( xNexSocket, pxServer->xSocketSet, eSELECT_READ|eSELECT_EXCEPT );
}
else
{
pcType = "closed";
FreeRTOS_closesocket( xNexSocket );
}
{
struct freertos_sockaddr xRemoteAddress;
FreeRTOS_GetRemoteAddress( pxClient->xSocket, &xRemoteAddress );
FreeRTOS_printf( ( "TPC-server: new %s client %xip\n", pcType, (unsigned)FreeRTOS_ntohl( xRemoteAddress.sin_addr ) ) );
}
/* Remove compiler warnings in case FreeRTOS_printf() is not used. */
( void ) pcType;
}
/*-----------------------------------------------------------*/
void FreeRTOS_TCPServerWork( TCPServer_t *pxServer, TickType_t xBlockingTime )
{
TCPClient_t **ppxClient;
BaseType_t xIndex;
BaseType_t xRc;
/* Let the server do one working cycle */
xRc = FreeRTOS_select( pxServer->xSocketSet, xBlockingTime );
if( xRc != 0 )
{
for( xIndex = 0; xIndex < pxServer->xServerCount; xIndex++ )
{
struct freertos_sockaddr xAddress;
Socket_t xNexSocket;
socklen_t xSocketLength;
if( pxServer->xServers[ xIndex ].xSocket == FREERTOS_NO_SOCKET )
{
continue;
}
xSocketLength = sizeof( xAddress );
xNexSocket = FreeRTOS_accept( pxServer->xServers[ xIndex ].xSocket, &xAddress, &xSocketLength);
if( ( xNexSocket != FREERTOS_NO_SOCKET ) && ( xNexSocket != FREERTOS_INVALID_SOCKET ) )
{
prvReceiveNewClient( pxServer, xIndex, xNexSocket );
}
}
}
ppxClient = &pxServer->pxClients;
while( ( * ppxClient ) != NULL )
{
TCPClient_t *pxThis = *ppxClient;
/* Almost C++ */
xRc = pxThis->fWorkFunction( pxThis );
if (xRc < 0 )
{
*ppxClient = pxThis->pxNextClient;
/* Close handles, resources */
pxThis->fDeleteFunction( pxThis );
/* Free the space */
vPortFreeLarge( pxThis );
}
else
{
ppxClient = &( pxThis->pxNextClient );
}
}
}
/*-----------------------------------------------------------*/
static char *strnew( const char *pcString )
{
BaseType_t xLength;
char *pxBuffer;
xLength = strlen( pcString ) + 1;
pxBuffer = ( char * ) pvPortMalloc( xLength );
if( pxBuffer != NULL )
{
memcpy( pxBuffer, pcString, xLength );
}
return pxBuffer;
}
/*-----------------------------------------------------------*/
static void prvRemoveSlash( char *pcDir )
{
BaseType_t xLength = strlen( pcDir );
while( ( xLength > 0 ) && ( pcDir[ xLength - 1 ] == '/' ) )
{
pcDir[ --xLength ] = '\0';
}
}
/*-----------------------------------------------------------*/
#if( ipconfigSUPPORT_SIGNALS != 0 )
/* FreeRTOS_TCPServerWork() calls select().
The two functions below provide a possibility to interrupt
the call to select(). After the interruption, resume
by calling FreeRTOS_TCPServerWork() again. */
BaseType_t FreeRTOS_TCPServerSignal( TCPServer_t *pxServer )
{
BaseType_t xIndex;
BaseType_t xResult = pdFALSE;
for( xIndex = 0; xIndex < pxServer->xServerCount; xIndex++ )
{
if( pxServer->xServers[ xIndex ].xSocket != FREERTOS_NO_SOCKET )
{
FreeRTOS_SignalSocket( pxServer->xServers[ xIndex ].xSocket );
xResult = pdTRUE;
break;
}
}
return xResult;
}
#endif /* ipconfigSUPPORT_SIGNALS */
/*-----------------------------------------------------------*/
#if( ipconfigSUPPORT_SIGNALS != 0 )
/* Same as above: this function may be called from an ISR,
for instance a GPIO interrupt. */
BaseType_t FreeRTOS_TCPServerSignalFromISR( TCPServer_t *pxServer, BaseType_t *pxHigherPriorityTaskWoken )
{
BaseType_t xIndex;
BaseType_t xResult = pdFALSE;
for( xIndex = 0; xIndex < pxServer->xServerCount; xIndex++ )
{
if( pxServer->xServers[ xIndex ].xSocket != FREERTOS_NO_SOCKET )
{
FreeRTOS_SignalSocketFromISR( pxServer->xServers[ xIndex ].xSocket, pxHigherPriorityTaskWoken );
xResult = pdTRUE;
break;
}
}
return xResult;
}
#endif /* ipconfigSUPPORT_SIGNALS */
/*-----------------------------------------------------------*/
#endif /* ( ipconfigUSE_TCP == 1 ) && ( ( ipconfigUSE_HTTP == 1 ) || ( ipconfigUSE_FTP == 1 ) ) */

View File

@ -0,0 +1,74 @@
/*
* FreeRTOS+TCP V2.0.3
* Copyright (C) 2017 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://aws.amazon.com/freertos
* https://www.FreeRTOS.org
*/
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_FTP_commands.h"
const FTPCommand_t xFTPCommands[ FTP_CMD_COUNT ] =
{
/* cmdLen cmdName[7] cmdType checkLogin checkNullArg */
{ 4, "USER", ECMD_USER, pdFALSE, pdFALSE },
{ 4, "PASS", ECMD_PASS, pdFALSE, pdFALSE },
{ 4, "ACCT", ECMD_ACCT, pdTRUE, pdFALSE },
{ 3, "CWD", ECMD_CWD, pdTRUE, pdTRUE },
{ 4, "CDUP", ECMD_CDUP, pdTRUE, pdFALSE },
{ 4, "SMNT", ECMD_SMNT, pdTRUE, pdFALSE },
{ 4, "QUIT", ECMD_QUIT, pdTRUE, pdFALSE },
{ 4, "REIN", ECMD_REIN, pdTRUE, pdFALSE },
{ 4, "PORT", ECMD_PORT, pdTRUE, pdFALSE },
{ 4, "PASV", ECMD_PASV, pdTRUE, pdFALSE },
{ 4, "TYPE", ECMD_TYPE, pdTRUE, pdFALSE },
{ 4, "STRU", ECMD_STRU, pdTRUE, pdFALSE },
{ 4, "MODE", ECMD_MODE, pdTRUE, pdFALSE },
{ 4, "RETR", ECMD_RETR, pdTRUE, pdTRUE },
{ 4, "STOR", ECMD_STOR, pdTRUE, pdTRUE },
{ 4, "STOU", ECMD_STOU, pdTRUE, pdFALSE },
{ 4, "APPE", ECMD_APPE, pdTRUE, pdFALSE },
{ 4, "ALLO", ECMD_ALLO, pdTRUE, pdFALSE },
{ 4, "REST", ECMD_REST, pdTRUE, pdFALSE },
{ 4, "RNFR", ECMD_RNFR, pdTRUE, pdTRUE },
{ 4, "RNTO", ECMD_RNTO, pdTRUE, pdTRUE },
{ 4, "ABOR", ECMD_ABOR, pdTRUE, pdFALSE },
{ 4, "SIZE", ECMD_SIZE, pdTRUE, pdTRUE },
{ 4, "MDTM", ECMD_MDTM, pdTRUE, pdTRUE },
{ 4, "DELE", ECMD_DELE, pdTRUE, pdTRUE },
{ 3, "RMD", ECMD_RMD, pdTRUE, pdTRUE },
{ 3, "MKD", ECMD_MKD, pdTRUE, pdTRUE },
{ 3, "PWD", ECMD_PWD, pdTRUE, pdFALSE },
{ 4, "LIST", ECMD_LIST, pdTRUE, pdFALSE },
{ 4, "NLST", ECMD_NLST, pdTRUE, pdFALSE },
{ 4, "SITE", ECMD_SITE, pdTRUE, pdFALSE },
{ 4, "SYST", ECMD_SYST, pdFALSE, pdFALSE },
{ 4, "FEAT", ECMD_FEAT, pdFALSE, pdFALSE },
{ 4, "STAT", ECMD_STAT, pdTRUE, pdFALSE },
{ 4, "HELP", ECMD_HELP, pdFALSE, pdFALSE },
{ 4, "NOOP", ECMD_NOOP, pdFALSE, pdFALSE },
{ 4, "EMPT", ECMD_EMPTY, pdFALSE, pdFALSE },
{ 4, "CLOS", ECMD_CLOSE, pdTRUE, pdFALSE },
{ 4, "UNKN", ECMD_UNKNOWN, pdFALSE, pdFALSE },
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
The protocols implemented in this directory are intended to be demo quality
examples only. They are not intended for inclusion in production devices.

View File

@ -0,0 +1,76 @@
/*
*!
*! The protocols implemented in this file are intended to be demo quality only,
*! and not for production devices.
*!
*
* FreeRTOS+TCP V2.0.3
* Copyright (C) 2017 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://aws.amazon.com/freertos
* https://www.FreeRTOS.org
*/
/* Standard includes. */
#include <stdio.h>
#include <stdlib.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "FreeRTOS_HTTP_commands.h"
const struct xWEB_COMMAND xWebCommands[ WEB_CMD_COUNT ] =
{
{ 3, "GET", ECMD_GET },
{ 4, "HEAD", ECMD_HEAD },
{ 4, "POST", ECMD_POST },
{ 3, "PUT", ECMD_PUT },
{ 6, "DELETE", ECMD_DELETE },
{ 5, "TRACE", ECMD_TRACE },
{ 7, "OPTIONS", ECMD_OPTIONS },
{ 7, "CONNECT", ECMD_CONNECT },
{ 5, "PATCH", ECMD_PATCH },
{ 4, "UNKN", ECMD_UNK },
};
const char *webCodename (int aCode)
{
switch (aCode) {
case WEB_REPLY_OK: // = 200,
return "OK";
case WEB_NO_CONTENT: // 204
return "No content";
case WEB_BAD_REQUEST: // = 400,
return "Bad request";
case WEB_UNAUTHORIZED: // = 401,
return "Authorization Required";
case WEB_NOT_FOUND: // = 404,
return "Not Found";
case WEB_GONE: // = 410,
return "Done";
case WEB_PRECONDITION_FAILED: // = 412,
return "Precondition Failed";
case WEB_INTERNAL_SERVER_ERROR: // = 500,
return "Internal Server Error";
}
return "Unknown";
}

View File

@ -0,0 +1,433 @@
/*
*!
*! The protocols implemented in this file are intended to be demo quality only,
*! and not for production devices.
*!
*
* FreeRTOS+TCP V2.0.3
* Copyright (C) 2017 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://aws.amazon.com/freertos
* https://www.FreeRTOS.org
*/
/* Standard includes. */
#include <stdio.h>
#include <stdlib.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
/* FreeRTOS Protocol includes. */
#include "FreeRTOS_HTTP_commands.h"
#include "FreeRTOS_TCP_server.h"
#include "FreeRTOS_server_private.h"
/* Remove the whole file if HTTP is not supported. */
#if( ipconfigUSE_HTTP == 1 )
/* FreeRTOS+FAT includes. */
#include "ff_stdio.h"
#ifndef HTTP_SERVER_BACKLOG
#define HTTP_SERVER_BACKLOG ( 12 )
#endif
#ifndef USE_HTML_CHUNKS
#define USE_HTML_CHUNKS ( 0 )
#endif
#if !defined( ARRAY_SIZE )
#define ARRAY_SIZE(x) ( BaseType_t ) (sizeof( x ) / sizeof( x )[ 0 ] )
#endif
/* Some defines to make the code more readbale */
#define pcCOMMAND_BUFFER pxClient->pxParent->pcCommandBuffer
#define pcNEW_DIR pxClient->pxParent->pcNewDir
#define pcFILE_BUFFER pxClient->pxParent->pcFileBuffer
#ifndef ipconfigHTTP_REQUEST_CHARACTER
#define ipconfigHTTP_REQUEST_CHARACTER '?'
#endif
/*_RB_ Need comment block, although fairly self evident. */
static void prvFileClose( HTTPClient_t *pxClient );
static BaseType_t prvProcessCmd( HTTPClient_t *pxClient, BaseType_t xIndex );
static const char *pcGetContentsType( const char *apFname );
static BaseType_t prvOpenURL( HTTPClient_t *pxClient );
static BaseType_t prvSendFile( HTTPClient_t *pxClient );
static BaseType_t prvSendReply( HTTPClient_t *pxClient, BaseType_t xCode );
static const char pcEmptyString[1] = { '\0' };
typedef struct xTYPE_COUPLE
{
const char *pcExtension;
const char *pcType;
} TypeCouple_t;
static TypeCouple_t pxTypeCouples[ ] =
{
{ "html", "text/html" },
{ "css", "text/css" },
{ "js", "text/javascript" },
{ "png", "image/png" },
{ "jpg", "image/jpeg" },
{ "gif", "image/gif" },
{ "txt", "text/plain" },
{ "mp3", "audio/mpeg3" },
{ "wav", "audio/wav" },
{ "flac", "audio/ogg" },
{ "pdf", "application/pdf" },
{ "ttf", "application/x-font-ttf" },
{ "ttc", "application/x-font-ttf" }
};
void vHTTPClientDelete( TCPClient_t *pxTCPClient )
{
HTTPClient_t *pxClient = ( HTTPClient_t * ) pxTCPClient;
/* This HTTP client stops, close / release all resources. */
if( pxClient->xSocket != FREERTOS_NO_SOCKET )
{
FreeRTOS_FD_CLR( pxClient->xSocket, pxClient->pxParent->xSocketSet, eSELECT_ALL );
FreeRTOS_closesocket( pxClient->xSocket );
pxClient->xSocket = FREERTOS_NO_SOCKET;
}
prvFileClose( pxClient );
}
/*-----------------------------------------------------------*/
static void prvFileClose( HTTPClient_t *pxClient )
{
if( pxClient->pxFileHandle != NULL )
{
FreeRTOS_printf( ( "Closing file: %s\n", pxClient->pcCurrentFilename ) );
ff_fclose( pxClient->pxFileHandle );
pxClient->pxFileHandle = NULL;
}
}
/*-----------------------------------------------------------*/
static BaseType_t prvSendReply( HTTPClient_t *pxClient, BaseType_t xCode )
{
struct xTCP_SERVER *pxParent = pxClient->pxParent;
BaseType_t xRc;
/* A normal command reply on the main socket (port 21). */
char *pcBuffer = pxParent->pcFileBuffer;
xRc = snprintf( pcBuffer, sizeof( pxParent->pcFileBuffer ),
"HTTP/1.1 %d %s\r\n"
#if USE_HTML_CHUNKS
"Transfer-Encoding: chunked\r\n"
#endif
"Content-Type: %s\r\n"
"Connection: keep-alive\r\n"
"%s\r\n",
( int ) xCode,
webCodename (xCode),
pxParent->pcContentsType[0] ? pxParent->pcContentsType : "text/html",
pxParent->pcExtraContents );
pxParent->pcContentsType[0] = '\0';
pxParent->pcExtraContents[0] = '\0';
xRc = FreeRTOS_send( pxClient->xSocket, ( const void * ) pcBuffer, xRc, 0 );
pxClient->bits.bReplySent = pdTRUE_UNSIGNED;
return xRc;
}
/*-----------------------------------------------------------*/
static BaseType_t prvSendFile( HTTPClient_t *pxClient )
{
size_t uxSpace;
size_t uxCount;
BaseType_t xRc = 0;
if( pxClient->bits.bReplySent == pdFALSE_UNSIGNED )
{
pxClient->bits.bReplySent = pdTRUE_UNSIGNED;
strcpy( pxClient->pxParent->pcContentsType, pcGetContentsType( pxClient->pcCurrentFilename ) );
snprintf( pxClient->pxParent->pcExtraContents, sizeof( pxClient->pxParent->pcExtraContents ),
"Content-Length: %d\r\n", ( int ) pxClient->uxBytesLeft );
/* "Requested file action OK". */
xRc = prvSendReply( pxClient, WEB_REPLY_OK );
}
if( xRc >= 0 ) do
{
uxSpace = FreeRTOS_tx_space( pxClient->xSocket );
if( pxClient->uxBytesLeft < uxSpace )
{
uxCount = pxClient->uxBytesLeft;
}
else
{
uxCount = uxSpace;
}
if( uxCount > 0u )
{
if( uxCount > sizeof( pxClient->pxParent->pcFileBuffer ) )
{
uxCount = sizeof( pxClient->pxParent->pcFileBuffer );
}
ff_fread( pxClient->pxParent->pcFileBuffer, 1, uxCount, pxClient->pxFileHandle );
pxClient->uxBytesLeft -= uxCount;
xRc = FreeRTOS_send( pxClient->xSocket, pxClient->pxParent->pcFileBuffer, uxCount, 0 );
if( xRc < 0 )
{
break;
}
}
} while( uxCount > 0u );
if( pxClient->uxBytesLeft == 0u )
{
/* Writing is ready, no need for further 'eSELECT_WRITE' events. */
FreeRTOS_FD_CLR( pxClient->xSocket, pxClient->pxParent->xSocketSet, eSELECT_WRITE );
prvFileClose( pxClient );
}
else
{
/* Wake up the TCP task as soon as this socket may be written to. */
FreeRTOS_FD_SET( pxClient->xSocket, pxClient->pxParent->xSocketSet, eSELECT_WRITE );
}
return xRc;
}
/*-----------------------------------------------------------*/
static BaseType_t prvOpenURL( HTTPClient_t *pxClient )
{
BaseType_t xRc;
char pcSlash[ 2 ];
pxClient->bits.ulFlags = 0;
#if( ipconfigHTTP_HAS_HANDLE_REQUEST_HOOK != 0 )
{
if( strchr( pxClient->pcUrlData, ipconfigHTTP_REQUEST_CHARACTER ) != NULL )
{
size_t xResult;
xResult = uxApplicationHTTPHandleRequestHook( pxClient->pcUrlData, pxClient->pcCurrentFilename, sizeof( pxClient->pcCurrentFilename ) );
if( xResult > 0 )
{
strcpy( pxClient->pxParent->pcContentsType, "text/html" );
snprintf( pxClient->pxParent->pcExtraContents, sizeof( pxClient->pxParent->pcExtraContents ),
"Content-Length: %d\r\n", ( int ) xResult );
xRc = prvSendReply( pxClient, WEB_REPLY_OK ); /* "Requested file action OK" */
if( xRc > 0 )
{
xRc = FreeRTOS_send( pxClient->xSocket, pxClient->pcCurrentFilename, xResult, 0 );
}
/* Although against the coding standard of FreeRTOS, a return is
done here to simplify this conditional code. */
return xRc;
}
}
}
#endif /* ipconfigHTTP_HAS_HANDLE_REQUEST_HOOK */
if( pxClient->pcUrlData[ 0 ] != '/' )
{
/* Insert a slash before the file name. */
pcSlash[ 0 ] = '/';
pcSlash[ 1 ] = '\0';
}
else
{
/* The browser provided a starting '/' already. */
pcSlash[ 0 ] = '\0';
}
snprintf( pxClient->pcCurrentFilename, sizeof( pxClient->pcCurrentFilename ), "%s%s%s",
pxClient->pcRootDir,
pcSlash,
pxClient->pcUrlData);
pxClient->pxFileHandle = ff_fopen( pxClient->pcCurrentFilename, "rb" );
FreeRTOS_printf( ( "Open file '%s': %s\n", pxClient->pcCurrentFilename,
pxClient->pxFileHandle != NULL ? "Ok" : strerror( stdioGET_ERRNO() ) ) );
if( pxClient->pxFileHandle == NULL )
{
/* "404 File not found". */
xRc = prvSendReply( pxClient, WEB_NOT_FOUND );
}
else
{
pxClient->uxBytesLeft = ( size_t ) pxClient->pxFileHandle->ulFileSize;
xRc = prvSendFile( pxClient );
}
return xRc;
}
/*-----------------------------------------------------------*/
static BaseType_t prvProcessCmd( HTTPClient_t *pxClient, BaseType_t xIndex )
{
BaseType_t xResult = 0;
/* A new command has been received. Process it. */
switch( xIndex )
{
case ECMD_GET:
xResult = prvOpenURL( pxClient );
break;
case ECMD_HEAD:
case ECMD_POST:
case ECMD_PUT:
case ECMD_DELETE:
case ECMD_TRACE:
case ECMD_OPTIONS:
case ECMD_CONNECT:
case ECMD_PATCH:
case ECMD_UNK:
{
FreeRTOS_printf( ( "prvProcessCmd: Not implemented: %s\n",
xWebCommands[xIndex].pcCommandName ) );
}
break;
}
return xResult;
}
/*-----------------------------------------------------------*/
BaseType_t xHTTPClientWork( TCPClient_t *pxTCPClient )
{
BaseType_t xRc;
HTTPClient_t *pxClient = ( HTTPClient_t * ) pxTCPClient;
if( pxClient->pxFileHandle != NULL )
{
prvSendFile( pxClient );
}
xRc = FreeRTOS_recv( pxClient->xSocket, ( void * )pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), 0 );
if( xRc > 0 )
{
BaseType_t xIndex;
const char *pcEndOfCmd;
const struct xWEB_COMMAND *curCmd;
char *pcBuffer = pcCOMMAND_BUFFER;
if( xRc < ( BaseType_t ) sizeof( pcCOMMAND_BUFFER ) )
{
pcBuffer[ xRc ] = '\0';
}
while( xRc && ( pcBuffer[ xRc - 1 ] == 13 || pcBuffer[ xRc - 1 ] == 10 ) )
{
pcBuffer[ --xRc ] = '\0';
}
pcEndOfCmd = pcBuffer + xRc;
curCmd = xWebCommands;
/* Pointing to "/index.html HTTP/1.1". */
pxClient->pcUrlData = pcBuffer;
/* Pointing to "HTTP/1.1". */
pxClient->pcRestData = pcEmptyString;
/* Last entry is "ECMD_UNK". */
for( xIndex = 0; xIndex < WEB_CMD_COUNT - 1; xIndex++, curCmd++ )
{
BaseType_t xLength;
xLength = curCmd->xCommandLength;
if( ( xRc >= xLength ) && ( memcmp( curCmd->pcCommandName, pcBuffer, xLength ) == 0 ) )
{
char *pcLastPtr;
pxClient->pcUrlData += xLength + 1;
for( pcLastPtr = (char *)pxClient->pcUrlData; pcLastPtr < pcEndOfCmd; pcLastPtr++ )
{
char ch = *pcLastPtr;
if( ( ch == '\0' ) || ( strchr( "\n\r \t", ch ) != NULL ) )
{
*pcLastPtr = '\0';
pxClient->pcRestData = pcLastPtr + 1;
break;
}
}
break;
}
}
if( xIndex < ( WEB_CMD_COUNT - 1 ) )
{
xRc = prvProcessCmd( pxClient, xIndex );
}
}
else if( xRc < 0 )
{
/* The connection will be closed and the client will be deleted. */
FreeRTOS_printf( ( "xHTTPClientWork: rc = %ld\n", xRc ) );
}
return xRc;
}
/*-----------------------------------------------------------*/
static const char *pcGetContentsType (const char *apFname)
{
const char *slash = NULL;
const char *dot = NULL;
const char *ptr;
const char *pcResult = "text/html";
BaseType_t x;
for( ptr = apFname; *ptr; ptr++ )
{
if (*ptr == '.') dot = ptr;
if (*ptr == '/') slash = ptr;
}
if( dot > slash )
{
dot++;
for( x = 0; x < ARRAY_SIZE( pxTypeCouples ); x++ )
{
if( strcasecmp( dot, pxTypeCouples[ x ].pcExtension ) == 0 )
{
pcResult = pxTypeCouples[ x ].pcType;
break;
}
}
}
return pcResult;
}
#endif /* ipconfigUSE_HTTP */

View File

@ -0,0 +1,2 @@
The protocols implemented in this directory are intended to be demo quality
examples only. They are not intended for inclusion in production devices.

View File

@ -0,0 +1,445 @@
/*
*!
*! The protocols implemented in this file are intended to be demo quality only,
*! and not for production devices.
*!
*
* FreeRTOS+TCP V2.0.3
* Copyright (C) 2017 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://aws.amazon.com/freertos
* https://www.FreeRTOS.org
*/
/*
* NTPDemo.c
*
* An example of how to lookup a domain using DNS
* And also how to send and receive UDP messages to get the NTP time
*
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_DNS.h"
#include "FreeRTOS_Stream_Buffer.h"
/* Use the date & time functions from +FAT. */
#include "ff_time.h"
#include "NTPDemo.h"
#include "ntpClient.h"
#include "date_and_time.h"
enum EStatus {
EStatusLookup,
EStatusAsking,
EStatusPause,
EStatusFailed,
};
static struct SNtpPacket xNTPPacket;
#if( ipconfigUSE_CALLBACKS == 0 )
static char cRecvBuffer[ sizeof( struct SNtpPacket ) + 64 ];
#endif
static enum EStatus xStatus = EStatusLookup;
static const char *pcTimeServers[] = {
"0.asia.pool.ntp.org",
"0.europe.pool.ntp.org",
"0.id.pool.ntp.org",
"0.south-america.pool.ntp.org",
"0.oceania.pool.ntp.org",
"0.north-america.pool.ntp.org"
};
static SemaphoreHandle_t xNTPWakeupSem = NULL;
static uint32_t ulIPAddressFound;
static Socket_t xUDPSocket = NULL;
static TaskHandle_t xNTPTaskhandle = NULL;
static TickType_t uxSendTime;
static void prvNTPTask( void *pvParameters );
static void vSignalTask( void )
{
#if( ipconfigUSE_CALLBACKS == 0 )
if( xUDPSocket != NULL )
{
/* Send a signal to the socket so that the
FreeRTOS_recvfrom will get interrupted. */
FreeRTOS_SignalSocket( xUDPSocket );
}
else
#endif
if( xNTPWakeupSem != NULL )
{
xSemaphoreGive( xNTPWakeupSem );
}
}
void vStartNTPTask( uint16_t usTaskStackSize, UBaseType_t uxTaskPriority )
{
/* The only public function in this module: start a task to contact
some NTP server. */
if( xNTPTaskhandle != NULL )
{
switch( xStatus )
{
case EStatusPause:
xStatus = EStatusAsking;
vSignalTask();
break;
case EStatusLookup:
FreeRTOS_printf( ( "NTP looking up server\n" ) );
break;
case EStatusAsking:
FreeRTOS_printf( ( "NTP still asking\n" ) );
break;
case EStatusFailed:
FreeRTOS_printf( ( "NTP failed somehow\n" ) );
ulIPAddressFound = 0ul;
xStatus = EStatusLookup;
vSignalTask();
break;
}
}
else
{
xUDPSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );
if( xUDPSocket != FREERTOS_INVALID_SOCKET )
{
struct freertos_sockaddr xAddress;
#if( ipconfigUSE_CALLBACKS != 0 )
BaseType_t xReceiveTimeOut = pdMS_TO_TICKS( 0 );
#else
BaseType_t xReceiveTimeOut = pdMS_TO_TICKS( 5000 );
#endif
xAddress.sin_addr = 0ul;
xAddress.sin_port = FreeRTOS_htons( NTP_PORT );
FreeRTOS_bind( xUDPSocket, &xAddress, sizeof( xAddress ) );
FreeRTOS_setsockopt( xUDPSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );
xTaskCreate( prvNTPTask, /* The function that implements the task. */
( const char * ) "NTP client", /* Just a text name for the task to aid debugging. */
usTaskStackSize, /* The stack size is defined in FreeRTOSIPConfig.h. */
NULL, /* The task parameter, not used in this case. */
uxTaskPriority, /* The priority assigned to the task is defined in FreeRTOSConfig.h. */
&xNTPTaskhandle ); /* The task handle. */
}
else
{
FreeRTOS_printf( ( "Creating socket failed\n" ) );
}
}
}
/*-----------------------------------------------------------*/
static void vDNS_callback( const char *pcName, void *pvSearchID, uint32_t ulIPAddress )
{
char pcBuf[16];
/* The DNS lookup has a result, or it has reached the time-out. */
FreeRTOS_inet_ntoa( ulIPAddress, pcBuf );
FreeRTOS_printf( ( "IP address of %s found: %s\n", pcName, pcBuf ) );
if( ulIPAddressFound == 0ul )
{
ulIPAddressFound = ulIPAddress;
}
/* For testing: in case DNS doen't respond, still try some NTP server
with a known IP-address. */
if( ulIPAddressFound == 0ul )
{
ulIPAddressFound = FreeRTOS_inet_addr_quick( 184, 105, 182, 7 );
/* ulIPAddressFound = FreeRTOS_inet_addr_quick( 103, 242, 70, 4 ); */
}
xStatus = EStatusAsking;
vSignalTask();
}
/*-----------------------------------------------------------*/
static void prvSwapFields( struct SNtpPacket *pxPacket)
{
/* NTP messages are big-endian */
pxPacket->rootDelay = FreeRTOS_htonl( pxPacket->rootDelay );
pxPacket->rootDispersion = FreeRTOS_htonl( pxPacket->rootDispersion );
pxPacket->referenceTimestamp.seconds = FreeRTOS_htonl( pxPacket->referenceTimestamp.seconds );
pxPacket->referenceTimestamp.fraction = FreeRTOS_htonl( pxPacket->referenceTimestamp.fraction );
pxPacket->originateTimestamp.seconds = FreeRTOS_htonl( pxPacket->originateTimestamp.seconds );
pxPacket->originateTimestamp.fraction = FreeRTOS_htonl( pxPacket->originateTimestamp.fraction );
pxPacket->receiveTimestamp.seconds = FreeRTOS_htonl( pxPacket->receiveTimestamp.seconds );
pxPacket->receiveTimestamp.fraction = FreeRTOS_htonl( pxPacket->receiveTimestamp.fraction );
pxPacket->transmitTimestamp.seconds = FreeRTOS_htonl( pxPacket->transmitTimestamp.seconds );
pxPacket->transmitTimestamp.fraction = FreeRTOS_htonl( pxPacket->transmitTimestamp.fraction );
}
/*-----------------------------------------------------------*/
static void prvNTPPacketInit( )
{
memset (&xNTPPacket, '\0', sizeof( xNTPPacket ) );
xNTPPacket.flags = 0xDB; /* value 0xDB : mode 3 (client), version 3, leap indicator unknown 3 */
xNTPPacket.poll = 10; /* 10 means 1 << 10 = 1024 seconds */
xNTPPacket.precision = 0xFA; /* = 250 = 0.015625 seconds */
xNTPPacket.rootDelay = 0x5D2E; /* 0x5D2E = 23854 or (23854/65535)= 0.3640 sec */
xNTPPacket.rootDispersion = 0x0008CAC8; /* 0x0008CAC8 = 8.7912 seconds */
/* use the recorded NTP time */
time_t uxSecs = FreeRTOS_time( NULL );/* apTime may be NULL, returns seconds */
xNTPPacket.referenceTimestamp.seconds = uxSecs; /* Current time */
xNTPPacket.transmitTimestamp.seconds = uxSecs + 3;
/* Transform the contents of the fields from native to big endian. */
prvSwapFields( &xNTPPacket );
}
/*-----------------------------------------------------------*/
static void prvReadTime( struct SNtpPacket * pxPacket )
{
FF_TimeStruct_t xTimeStruct;
time_t uxPreviousSeconds;
time_t uxPreviousMS;
time_t uxCurrentSeconds;
time_t uxCurrentMS;
const char *pcTimeUnit;
int32_t ilDiff;
TickType_t uxTravelTime;
uxTravelTime = xTaskGetTickCount() - uxSendTime;
/* Transform the contents of the fields from big to native endian. */
prvSwapFields( pxPacket );
uxCurrentSeconds = pxPacket->receiveTimestamp.seconds - TIME1970;
uxCurrentMS = pxPacket->receiveTimestamp.fraction / 4294967;
uxCurrentSeconds += uxCurrentMS / 1000;
uxCurrentMS = uxCurrentMS % 1000;
// Get the last time recorded
uxPreviousSeconds = FreeRTOS_get_secs_msec( &uxPreviousMS );
// Set the new time with precision in msec. */
FreeRTOS_set_secs_msec( &uxCurrentSeconds, &uxCurrentMS );
if( uxCurrentSeconds >= uxPreviousSeconds )
{
ilDiff = ( int32_t ) ( uxCurrentSeconds - uxPreviousSeconds );
}
else
{
ilDiff = 0 - ( int32_t ) ( uxPreviousSeconds - uxCurrentSeconds );
}
if( ( ilDiff < -5 ) || ( ilDiff > 5 ) )
{
/* More than 5 seconds difference. */
pcTimeUnit = "sec";
}
else
{
/* Less than or equal to 5 second difference. */
pcTimeUnit = "ms";
uint32_t ulLowest = ( uxCurrentSeconds <= uxPreviousSeconds ) ? uxCurrentSeconds : uxPreviousSeconds;
int32_t iCurMS = 1000 * ( uxCurrentSeconds - ulLowest ) + uxCurrentMS;
int32_t iPrevMS = 1000 * ( uxPreviousSeconds - ulLowest ) + uxPreviousMS;
ilDiff = iCurMS - iPrevMS;
}
uxCurrentSeconds -= iTimeZone;
FreeRTOS_gmtime_r( &uxCurrentSeconds, &xTimeStruct );
/*
378.067 [NTP client] NTP time: 9/11/2015 16:11:19.559 Diff -20 ms (289 ms)
379.441 [NTP client] NTP time: 9/11/2015 16:11:20.933 Diff 0 ms (263 ms)
*/
FreeRTOS_printf( ("NTP time: %d/%d/%02d %2d:%02d:%02d.%03u Diff %d %s (%lu ms)\n",
xTimeStruct.tm_mday,
xTimeStruct.tm_mon + 1,
xTimeStruct.tm_year + 1900,
xTimeStruct.tm_hour,
xTimeStruct.tm_min,
xTimeStruct.tm_sec,
( unsigned )uxCurrentMS,
( unsigned )ilDiff,
pcTimeUnit,
uxTravelTime ) );
/* Remove compiler warnings in case FreeRTOS_printf() is not used. */
( void ) pcTimeUnit;
( void ) uxTravelTime;
}
/*-----------------------------------------------------------*/
#if( ipconfigUSE_CALLBACKS != 0 )
static BaseType_t xOnUDPReceive( Socket_t xSocket, void * pvData, size_t xLength,
const struct freertos_sockaddr *pxFrom, const struct freertos_sockaddr *pxDest )
{
if( xLength >= sizeof( xNTPPacket ) )
{
prvReadTime( ( struct SNtpPacket *)pvData );
if( xStatus != EStatusPause )
{
xStatus = EStatusPause;
}
}
vSignalTask();
/* Tell the driver not to store the RX data */
return 1;
}
/*-----------------------------------------------------------*/
#endif /* ipconfigUSE_CALLBACKS != 0 */
static void prvNTPTask( void *pvParameters )
{
BaseType_t xServerIndex = 3;
struct freertos_sockaddr xAddress;
#if( ipconfigUSE_CALLBACKS != 0 )
F_TCP_UDP_Handler_t xHandler;
#endif /* ipconfigUSE_CALLBACKS != 0 */
xStatus = EStatusLookup;
#if( ipconfigSOCKET_HAS_USER_SEMAPHORE != 0 ) || ( ipconfigUSE_CALLBACKS != 0 )
{
xNTPWakeupSem = xSemaphoreCreateBinary();
}
#endif
#if( ipconfigUSE_CALLBACKS != 0 )
{
memset( &xHandler, '\0', sizeof( xHandler ) );
xHandler.pxOnUDPReceive = xOnUDPReceive;
FreeRTOS_setsockopt( xUDPSocket, 0, FREERTOS_SO_UDP_RECV_HANDLER, ( void * ) &xHandler, sizeof( xHandler ) );
}
#endif
#if( ipconfigSOCKET_HAS_USER_SEMAPHORE != 0 )
{
FreeRTOS_setsockopt( xUDPSocket, 0, FREERTOS_SO_SET_SEMAPHORE, ( void * ) &xNTPWakeupSem, sizeof( xNTPWakeupSem ) );
}
#endif
for( ; ; )
{
switch( xStatus )
{
case EStatusLookup:
if( ( ulIPAddressFound == 0ul ) || ( ulIPAddressFound == ~0ul ) )
{
if( ++xServerIndex == sizeof( pcTimeServers ) / sizeof( pcTimeServers[ 0 ] ) )
{
xServerIndex = 0;
}
FreeRTOS_printf( ( "Looking up server '%s'\n", pcTimeServers[ xServerIndex ] ) );
FreeRTOS_gethostbyname_a( pcTimeServers[ xServerIndex ], vDNS_callback, (void *)NULL, 1200 );
}
else
{
xStatus = EStatusAsking;
}
break;
case EStatusAsking:
{
char pcBuf[16];
prvNTPPacketInit( );
xAddress.sin_addr = ulIPAddressFound;
xAddress.sin_port = FreeRTOS_htons( NTP_PORT );
FreeRTOS_inet_ntoa( xAddress.sin_addr, pcBuf );
FreeRTOS_printf( ( "Sending UDP message to %s:%u\n",
pcBuf,
FreeRTOS_ntohs( xAddress.sin_port ) ) );
uxSendTime = xTaskGetTickCount( );
FreeRTOS_sendto( xUDPSocket, ( void * )&xNTPPacket, sizeof( xNTPPacket ), 0, &xAddress, sizeof( xAddress ) );
}
break;
case EStatusPause:
break;
case EStatusFailed:
break;
}
#if( ipconfigUSE_CALLBACKS != 0 )
{
xSemaphoreTake( xNTPWakeupSem, 5000 );
}
#else
{
uint32_t xAddressSize;
BaseType_t xReturned;
xAddressSize = sizeof( xAddress );
xReturned = FreeRTOS_recvfrom( xUDPSocket, ( void * ) cRecvBuffer, sizeof( cRecvBuffer ), 0, &xAddress, &xAddressSize );
switch( xReturned )
{
case 0:
case -pdFREERTOS_ERRNO_EAGAIN:
case -pdFREERTOS_ERRNO_EINTR:
break;
default:
if( xReturned < sizeof( xNTPPacket ) )
{
FreeRTOS_printf( ( "FreeRTOS_recvfrom: returns %ld\n", xReturned ) );
}
else
{
prvReadTime( ( struct SNtpPacket *)cRecvBuffer );
if( xStatus != EStatusPause )
{
xStatus = EStatusPause;
}
}
break;
}
}
#endif
}
}
/*-----------------------------------------------------------*/

View File

@ -0,0 +1,5 @@
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
[InternetShortcut]
URL=https://www.freertos.org/coresntp/index.html
IDList=

View File

@ -0,0 +1,5 @@
FreeRTOS 2020107.00 adds a new SNTPv4 client library, [FreeRTOS/coreSNTP](https://github.com/FreeRTOS/coreSNTP),
and an [accompanying demo](..\..\..\coreSNTP_Windows_Simulator) to showcase the setup of an SNTP client and system
wall-clock time using the library. Refer to
The protocols implemented in this directory are intended to be demo quality
examples only. They are not intended for inclusion in production devices.

View File

@ -0,0 +1,133 @@
/*
* FreeRTOS+TCP V2.0.1
* Copyright (C) 2017 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://aws.amazon.com/freertos
* https://www.FreeRTOS.org
*/
#ifndef __FTPCMD_H__
#define __FTPCMD_H__
#define REPL_110 "110 Restart marker reply.\r\n"
#define REPL_120 "120 Try again in 2 minutes.\r\n"
#define REPL_125 "125 Data connection already open; transfer starting.\r\n"
#define REPL_150 "150 File status okay; about to open data connection.\r\n"
#define REPL_200 "200 NOOP command successful.\r\n"
#define REPL_200_PROGRESS "200 NOOP: data transfer in progress.\r\n"
#define REPL_202 "202 Command not implemented, superfluous at this site.\r\n"
#define REPL_211 "221 System status, or system help reply.\r\n"
#define REPL_211_STATUS "221-status of %s.\r\n"
#define REPL_211_END "221 End of status.\r\n"
#define REPL_212 "212 Directory status.\r\n"
#define REPL_213 "213 File status.\r\n"
#define REPL_214 "214 Help message.\r\n"
#define REPL_214_END "214 End Help message.\r\n"
#define REPL_215 "215 %s system type.\r\n"
#define REPL_220 "220 Service ready for new user.\r\n"
#define REPL_221 "221 Service closing control connection.\r\n"
#define REPL_225 "225 Data connection open; no transfer in progress.\r\n"
#define REPL_226 "226 Closing data connection.\r\n"
#define REPL_227 "227 Entering Passive Mode (%s,%s,%s,%s,%s,%s).\r\n"
#define REPL_227_D "227 Entering Passive Mode (%u,%u,%u,%u,%u,%u).\r\n"
#define REPL_230 "230 User logged in, proceed.\r\n"
#define REPL_250 "250 Requested file action okay, completed.\r\n"
#define REPL_257 "257 %s created.\r\n"
// #define REPL_257_PWD "257 \"%s\" is current working dir.\r\n"
#define REPL_257_PWD "257 \"%s\"\r\n"
#define REPL_331 "331 Only anonymous user is accepted.\r\n"
#define REPL_331_ANON "331 Anonymous login okay\r\n"
#define REPL_332 "332 Need account for login.\r\n"
#define REPL_350 "350 Requested file action pending further information.\r\n"
#define REPL_421 "421 Service not available, closing control connection.\r\n"
#define REPL_425 "425 Can't open data connection.\r\n"
#define REPL_426 "426 Connection closed; transfer aborted.\r\n"
#define REPL_450 "450 Requested file action not taken.\r\n"
#define REPL_451 "451 Requested action aborted. Local error in processing.\r\n"
#define REPL_452 "452 Requested action not taken.\r\n"
#define REPL_500 "500 Syntax error, command unrecognized.\r\n"
#define REPL_501 "501 Syntax error in parameters or arguments.\r\n"
#define REPL_502 "502 Command not implemented.\r\n"
#define REPL_503 "503 Bad sequence of commands.\r\n"
#define REPL_504 "504 Command not implemented for that parameter.\r\n"
#define REPL_530 "530 Not logged in.\r\n"
#define REPL_532 "532 Need account for storing files.\r\n"
#define REPL_550 "550 Requested action not taken.\r\n"
#define REPL_551 "551 Requested action aborted. Page type unknown.\r\n"
#define REPL_552 "552 Requested file action aborted.\r\n"
#define REPL_553 "553 Requested action not taken.\r\n"
#define REPL_553_READ_ONLY "553 Read-only file-system.\r\n"
enum EFTPCommand {
ECMD_USER,
ECMD_PASS,
ECMD_ACCT,
ECMD_CWD,
ECMD_CDUP,
ECMD_SMNT,
ECMD_QUIT,
ECMD_REIN,
ECMD_PORT,
ECMD_PASV,
ECMD_TYPE,
ECMD_STRU,
ECMD_MODE,
ECMD_RETR,
ECMD_STOR,
ECMD_STOU,
ECMD_APPE,
ECMD_ALLO,
ECMD_REST,
ECMD_RNFR,
ECMD_RNTO,
ECMD_ABOR,
ECMD_SIZE,
ECMD_MDTM,
ECMD_DELE,
ECMD_RMD,
ECMD_MKD,
ECMD_PWD,
ECMD_LIST,
ECMD_NLST,
ECMD_SITE,
ECMD_SYST,
ECMD_FEAT,
ECMD_STAT,
ECMD_HELP,
ECMD_NOOP,
ECMD_EMPTY,
ECMD_CLOSE,
ECMD_UNKNOWN,
};
typedef struct xFTP_COMMAND {
BaseType_t xCommandLength;
const char pcCommandName[7];
const unsigned char ucCommandType;
const unsigned char checkLogin;
const unsigned char checkNullArg;
} FTPCommand_t;
#define FTP_CMD_COUNT (ECMD_UNKNOWN+1)
extern const FTPCommand_t xFTPCommands[ FTP_CMD_COUNT ];
#endif // __FTPCMD_H__

View File

@ -0,0 +1,67 @@
/*
* FreeRTOS+TCP V2.0.3
* Copyright (C) 2017 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://aws.amazon.com/freertos
* https://www.FreeRTOS.org
*/
#ifndef FREERTOS_HTTP_COMMANDS_H
#define FREERTOS_HTTP_COMMANDS_H
enum {
WEB_REPLY_OK = 200,
WEB_NO_CONTENT = 204,
WEB_BAD_REQUEST = 400,
WEB_UNAUTHORIZED = 401,
WEB_NOT_FOUND = 404,
WEB_GONE = 410,
WEB_PRECONDITION_FAILED = 412,
WEB_INTERNAL_SERVER_ERROR = 500,
};
enum EWebCommand {
ECMD_GET,
ECMD_HEAD,
ECMD_POST,
ECMD_PUT,
ECMD_DELETE,
ECMD_TRACE,
ECMD_OPTIONS,
ECMD_CONNECT,
ECMD_PATCH,
ECMD_UNK,
};
struct xWEB_COMMAND
{
BaseType_t xCommandLength;
const char *pcCommandName;
const unsigned char ucCommandType;
};
#define WEB_CMD_COUNT (ECMD_UNK+1)
extern const struct xWEB_COMMAND xWebCommands[WEB_CMD_COUNT];
extern const char *webCodename (int aCode);
#endif /* FREERTOS_HTTP_COMMANDS_H */

View File

@ -0,0 +1,125 @@
/*
* FreeRTOS+TCP V2.0.3
* Copyright (C) 2017 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://aws.amazon.com/freertos
* https://www.FreeRTOS.org
*/
/*
Some code which is common to TCP servers like HTTP en FTP
*/
#ifndef FREERTOS_TCP_SERVER_H
#define FREERTOS_TCP_SERVER_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef FTP_SERVER_USES_RELATIVE_DIRECTORY
#define FTP_SERVER_USES_RELATIVE_DIRECTORY 0
#endif
enum eSERVER_TYPE
{
eSERVER_NONE,
eSERVER_HTTP,
eSERVER_FTP,
};
struct xFTP_CLIENT;
#if( ipconfigFTP_HAS_RECEIVED_HOOK != 0 )
extern void vApplicationFTPReceivedHook( const char *pcFileName, uint32_t ulSize, struct xFTP_CLIENT *pxFTPClient );
extern void vFTPReplyMessage( struct xFTP_CLIENT *pxFTPClient, const char *pcMessage );
#endif /* ipconfigFTP_HAS_RECEIVED_HOOK != 0 */
#if( ipconfigFTP_HAS_USER_PASSWORD_HOOK != 0 )
/*
* Function is called when a user name has been submitted.
* The function may return a string such as: "331 Please enter your password"
* or return NULL to use the default reply.
*/
extern const char *pcApplicationFTPUserHook( const char *pcUserName );
#endif /* ipconfigFTP_HAS_USER_PASSWORD_HOOK */
#if( ipconfigFTP_HAS_USER_PASSWORD_HOOK != 0 )
/*
* Function is called when a password was received.
* Return positive value to allow the user
*/
extern BaseType_t xApplicationFTPPasswordHook( const char *pcUserName, const char *pcPassword );
#endif /* ipconfigFTP_HAS_USER_PASSWORD_HOOK */
#if( ipconfigFTP_HAS_USER_PROPERTIES_HOOK != 0 )
/*
* The FTP server is asking for user-specific properties
*/
typedef struct
{
uint16_t usPortNumber; /* For reference only. Host-endian. */
const char *pcRootDir;
BaseType_t xReadOnly;
}
FTPUserProperties_t;
extern void vApplicationFTPUserPropertiesHook( const char *pcUserName, FTPUserProperties_t *pxProperties );
#endif /* ipconfigFTP_HAS_USER_PASSWORD_HOOK */
#if( ipconfigHTTP_HAS_HANDLE_REQUEST_HOOK != 0 )
/*
* A GET request is received containing a special character,
* usually a question mark.
* const char *pcURLData; // A request, e.g. "/request?limit=75"
* char *pcBuffer; // Here the answer can be written
* size_t uxBufferLength; // Size of the buffer
*
*/
extern size_t uxApplicationHTTPHandleRequestHook( const char *pcURLData, char *pcBuffer, size_t uxBufferLength );
#endif /* ipconfigHTTP_HAS_HANDLE_REQUEST_HOOK */
struct xSERVER_CONFIG
{
enum eSERVER_TYPE eType; /* eSERVER_HTTP | eSERVER_FTP */
BaseType_t xPortNumber; /* e.g. 80, 8080, 21 */
BaseType_t xBackLog; /* e.g. 10, maximum number of connected TCP clients */
const char * const pcRootDir; /* Treat this directory as the root directory */
};
struct xTCP_SERVER;
typedef struct xTCP_SERVER TCPServer_t;
TCPServer_t *FreeRTOS_CreateTCPServer( const struct xSERVER_CONFIG *pxConfigs, BaseType_t xCount );
void FreeRTOS_TCPServerWork( TCPServer_t *pxServer, TickType_t xBlockingTime );
#if( ipconfigSUPPORT_SIGNALS != 0 )
/* FreeRTOS_TCPServerWork() calls select().
The two functions below provide a possibility to interrupt
the call to select(). After the interruption, resume
by calling FreeRTOS_TCPServerWork() again. */
BaseType_t FreeRTOS_TCPServerSignal( TCPServer_t *pxServer );
BaseType_t FreeRTOS_TCPServerSignalFromISR( TCPServer_t *pxServer, BaseType_t *pxHigherPriorityTaskWoken );
#endif
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* FREERTOS_TCP_SERVER_H */

View File

@ -0,0 +1,185 @@
/*
* FreeRTOS+TCP V2.0.3
* Copyright (C) 2017 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://aws.amazon.com/freertos
* https://www.FreeRTOS.org
*/
/*
Some code which is common to TCP servers like HTTP and FTP
*/
#ifndef FREERTOS_SERVER_PRIVATE_H
#define FREERTOS_SERVER_PRIVATE_H
#define FREERTOS_NO_SOCKET NULL
/* FreeRTOS+FAT */
#include "ff_stdio.h"
/* Each HTTP server has 1, at most 2 sockets */
#define HTTP_SOCKET_COUNT 2
/*
* ipconfigTCP_COMMAND_BUFFER_SIZE sets the size of:
* pcCommandBuffer': a buffer to receive and send TCP commands
*
* ipconfigTCP_FILE_BUFFER_SIZE sets the size of:
* pcFileBuffer' : a buffer to access the file system: read or write data.
*
* The buffers are both used for FTP as well as HTTP.
*/
#ifndef ipconfigTCP_COMMAND_BUFFER_SIZE
#define ipconfigTCP_COMMAND_BUFFER_SIZE ( 2048 )
#endif
#ifndef ipconfigTCP_FILE_BUFFER_SIZE
#define ipconfigTCP_FILE_BUFFER_SIZE ( 2048 )
#endif
struct xTCP_CLIENT;
typedef BaseType_t ( * FTCPWorkFunction ) ( struct xTCP_CLIENT * /* pxClient */ );
typedef void ( * FTCPDeleteFunction ) ( struct xTCP_CLIENT * /* pxClient */ );
#define TCP_CLIENT_FIELDS \
enum eSERVER_TYPE eType; \
struct xTCP_SERVER *pxParent; \
Socket_t xSocket; \
const char *pcRootDir; \
FTCPWorkFunction fWorkFunction; \
FTCPDeleteFunction fDeleteFunction; \
struct xTCP_CLIENT *pxNextClient
typedef struct xTCP_CLIENT
{
/* This define contains fields which must come first within each of the client structs */
TCP_CLIENT_FIELDS;
/* --- Keep at the top --- */
} TCPClient_t;
struct xHTTP_CLIENT
{
/* This define contains fields which must come first within each of the client structs */
TCP_CLIENT_FIELDS;
/* --- Keep at the top --- */
const char *pcUrlData;
const char *pcRestData;
char pcCurrentFilename[ ffconfigMAX_FILENAME ];
size_t uxBytesLeft;
FF_FILE *pxFileHandle;
union {
struct {
uint32_t
bReplySent : 1;
};
uint32_t ulFlags;
} bits;
};
typedef struct xHTTP_CLIENT HTTPClient_t;
struct xFTP_CLIENT
{
/* This define contains fields which must come first within each of the client structs */
TCP_CLIENT_FIELDS;
/* --- Keep at the top --- */
uint32_t ulRestartOffset;
uint32_t ulRecvBytes;
size_t uxBytesLeft; /* Bytes left to send */
uint32_t ulClientIP;
TickType_t xStartTime;
uint16_t usClientPort;
Socket_t xTransferSocket;
BaseType_t xTransType;
BaseType_t xDirCount;
FF_FindData_t xFindData;
FF_FILE *pxReadHandle;
FF_FILE *pxWriteHandle;
char pcCurrentDir[ ffconfigMAX_FILENAME ];
char pcFileName[ ffconfigMAX_FILENAME ];
char pcConnectionAck[ 128 ];
char pcClientAck[ 128 ];
union {
struct {
uint32_t
bHelloSent : 1,
bLoggedIn : 1,
bStatusUser : 1,
bInRename : 1,
bReadOnly : 1;
};
uint32_t ulFTPFlags;
} bits;
union {
struct {
uint32_t
bIsListen : 1, /* pdTRUE for passive data connections (using list()). */
bDirHasEntry : 1, /* pdTRUE if ff_findfirst() was successful. */
bClientConnected : 1, /* pdTRUE after connect() or accept() has succeeded. */
bEmptyFile : 1, /* pdTRUE if a connection-without-data was received. */
bHadError : 1; /* pdTRUE if a transfer got aborted because of an error. */
};
uint32_t ulConnFlags;
} bits1;
};
typedef struct xFTP_CLIENT FTPClient_t;
BaseType_t xHTTPClientWork( TCPClient_t *pxClient );
BaseType_t xFTPClientWork( TCPClient_t *pxClient );
void vHTTPClientDelete( TCPClient_t *pxClient );
void vFTPClientDelete( TCPClient_t *pxClient );
BaseType_t xMakeAbsolute( struct xFTP_CLIENT *pxClient, char *pcBuffer, BaseType_t xBufferLength, const char *pcFileName );
BaseType_t xMakeRelative( FTPClient_t *pxClient, char *pcBuffer, BaseType_t xBufferLength, const char *pcFileName );
struct xTCP_SERVER
{
SocketSet_t xSocketSet;
/* A buffer to receive and send TCP commands, either HTTP of FTP. */
char pcCommandBuffer[ ipconfigTCP_COMMAND_BUFFER_SIZE ];
/* A buffer to access the file system: read or write data. */
char pcFileBuffer[ ipconfigTCP_FILE_BUFFER_SIZE ];
#if( ipconfigUSE_FTP != 0 )
char pcNewDir[ ffconfigMAX_FILENAME ];
#endif
#if( ipconfigUSE_HTTP != 0 )
char pcContentsType[40]; /* Space for the msg: "text/javascript" */
char pcExtraContents[40]; /* Space for the msg: "Content-Length: 346500" */
#endif
BaseType_t xServerCount;
TCPClient_t *pxClients;
struct xSERVER
{
enum eSERVER_TYPE eType; /* eSERVER_HTTP | eSERVER_FTP */
const char *pcRootDir;
Socket_t xSocket;
} xServers[ 1 ];
};
#endif /* FREERTOS_SERVER_PRIVATE_H */

View File

@ -0,0 +1,71 @@
//
// ntpClient.h
//
#ifndef __NTPCLIENT_H__
#define __NTPCLIENT_H__
#define NTP_PORT 123
typedef uint32_t quint32;
typedef int32_t qint32;
typedef uint8_t quint8;
typedef int8_t qint8;
typedef union _SNtpFlags SNtpFlags;
/**
* 64-bit NTP timestamp.
*/
struct __attribute__ ((__packed__)) _SNtpTimestamp {
/** Number of seconds passed since Jan 1 1900, in big-endian format. */
quint32 seconds;
/** Fractional time part, in <tt>1/0xFFFFFFFF</tt>s of a second. */
quint32 fraction;
};
typedef struct _SNtpTimestamp SNtpTimestamp;
/**
* Mandatory part of an NTP packet
*/
struct SNtpPacket {
/** Flags. */
unsigned char flags; // value 0xDB : mode 3 (client), version 3, leap indicator unknown 3
/** Stratum of the clock. */
quint8 stratum; // value 0 : unspecified
/** Maximum interval between successive messages, in log2 seconds. Note that the value is signed. */
qint8 poll; // 10 means 1 << 10 = 1024 seconds
/** Precision of the clock, in log2 seconds. Note that the value is signed. */
qint8 precision; // 0xFA = 250 = 0.015625 seconds
/** Round trip time to the primary reference source, in NTP short format. */
qint32 rootDelay; // 0x5D2E = 23854 or (23854/65535)= 0.3640 sec
/** Nominal error relative to the primary reference source. */
qint32 rootDispersion; // 0x0008 CAC8 = 8.7912 seconds
/** Reference identifier (either a 4 character string or an IP address). */
qint8 referenceID[4]; // or just 0000
/** The time at which the clock was last set or corrected. */
SNtpTimestamp referenceTimestamp; // Current time
/** The time at which the request departed the client for the server. */
SNtpTimestamp originateTimestamp; // Keep 0
/** The time at which the request arrived at the server. */
SNtpTimestamp receiveTimestamp; // Keep 0
/** The time at which the reply departed the server for client. */
SNtpTimestamp transmitTimestamp;
};
/* Add this number to get secs since 1-1-1900 */
#define TIME1970 2208988800UL
#endif // __NTPCLIENT_H__

View File

@ -0,0 +1,11 @@
/*
* A simple demo for NTP using FreeRTOS+TCP
*/
#ifndef NTPDEMO_H
#define NTPDEMO_H
void vStartNTPTask( uint16_t usTaskStackSize, UBaseType_t uxTaskPriority );
#endif

View File

@ -0,0 +1,3 @@
The protocols implemented in the files and folders in this directory and its
subdirectories are intended to be demo quality examples only. They are not
intended for inclusion in production devices.

Some files were not shown because too many files have changed in this diff Show More