

# FreeRTOS Libraries
<a name="dev-guide-freertos-libraries"></a>

FreeRTOS libraries provide additional functionality to the FreeRTOS kernel and its internal libraries. You can use FreeRTOS libraries for networking and security in embedded applications. FreeRTOS libraries also enable your applications to interact with AWS IoT services. FreeRTOS includes libraries that make it possible to:
+ Securely connect devices to the AWS IoT Cloud using MQTT and device shadows.
+ Discover and connect to AWS IoT Greengrass cores.
+ Manage Wi-Fi connections.
+ Listen for and process [FreeRTOS Over-the-Air Updates](freertos-ota-dev.md).

The `libraries` directory contains the source code of the FreeRTOS libraries. There are helper functions that assist in implementing the library functionality. We do not recommend that you change these helper functions.

## FreeRTOS porting libraries
<a name="dev-guide-freertos-porting-libraries"></a>

The following porting libraries are included in configurations of FreeRTOS that are available for download on the FreeRTOS console. These libraries are platform-dependent. Their contents change according to your hardware platform. For information about porting these libraries to a device, see the [FreeRTOS Porting Guide](https://docs.aws.amazon.com/freertos/latest/portingguide/).


**FreeRTOS porting libraries**  

| Library | API Reference | Description | 
| --- | --- | --- | 
| Bluetooth Low Energy |  [Bluetooth Low Energy API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/ble/index.html)  | Using the FreeRTOS Bluetooth Low Energy library, your microcontroller can communicate with the AWS IoT MQTT broker through a gateway device. For more information, see [Bluetooth Low Energy library](freertos-ble-library.md).  | 
| Over-the-Air Updates | [AWS IoT Over-the-air update API reference](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/index.html) |  The FreeRTOS AWS IoT Over-the-air (OTA) update library lets you manage update notifications, download updates, and perform cryptographic verification of firmware updates on your FreeRTOS device. For more information, see [AWS IoT Over the air (OTA) library](ota-update-library.md).  | 
| FreeRTOS\$1POSIX | [FreeRTOS\$1POSIX API Reference](https://freertos.org/Documentation/api-ref/POSIX/index.html) |  You can use the FreeRTOS\$1POSIX library to port POSIX-compliant applications to the FreeRTOS ecosystem. For more information, see [FreeRTOS\$1POSIX](https://freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_POSIX/index.html).  | 
| Secure Sockets | [ Secure Sockets API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/secure_sockets/index.html) | For more information, see [Secure Sockets library](secure-sockets.md). | 
| FreeRTOS\$1TCP | [ FreeRTOS\$1TCP API Reference](https://freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/FreeRTOS_TCP_API_Functions.html) |  FreeRTOS\$1TCP is a scalable, open source and thread safe TCP/IP stack for FreeRTOS. For more information, see [FreeRTOS\$1TCP](https://freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/index.html).   | 
| Wi-Fi | [Wi-Fi API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/wifi/index.html) |  The FreeRTOS Wi-Fi library enables you to interface with your microcontroller's lower-level wireless stack. For more information, see the [Wi-Fi library](freertos-wifi.md).  | 
| corePKCS11 |  |  The corePKCS11 library is a reference implementation of the Public Key Cryptography Standard \$111, to support provisioning and TLS client authentication. For more information, see the [corePKCS11 library](security-pkcs.md).  | 
| TLS |  |  For more information, see [Transport Layer Security](security-tls.md).  | 
| Common I/O | Common I/O API Reference |  For more information, see [Common I/O](common-io.md).  | 
| Cellular Interface | Cellular Interface API Reference |  The Cellular Interface library exposes the capabilities of a few popular cellular modems through a uniform API. For more information, see the [Cellular Interface library](cellular-interface.md).  | 

## FreeRTOS application libraries
<a name="dev-guide-freertos-application-libraries"></a>

You can optionally include the following standalone application libraries in your FreeRTOS configuration to interact with AWS IoT services on the cloud.

**Note**  
Some of the application libraries have the same APIs as libraries in the AWS IoT Device SDK for Embedded C. For these libraries, see the [AWS IoT Device SDK C API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/c-sdk/main/index.html). For more information about the AWS IoT Device SDK for Embedded C, see [AWS IoT Device SDK for Embedded C](c-sdk.md).


**FreeRTOS application libraries**  

| Library | API Reference | Description | 
| --- | --- | --- | 
| AWS IoT Device Defender |  [ Device Defender C SDK API Reference](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/device-defender-for-aws-iot-embedded-sdk/docs/doxygen/output/html/index.html)  |  The FreeRTOS AWS IoT Device Defender library connects your FreeRTOS device to AWS IoT Device Defender. For more information, see [AWS IoT Device Defender library](afr-device-defender-library.md).  | 
| AWS IoT Greengrass | [ Greengrass API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html1/aws__greengrass__discovery_8h.html)  |  The FreeRTOS AWS IoT Greengrass library connects your FreeRTOS device to AWS IoT Greengrass. For more information, see [AWS IoT Greengrass Discovery library](freertos-lib-gg-connectivity.md).  | 
| MQTT |  [ MQTT (v1.x.x) Library API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html1/aws__mqtt__lib_8h.html) [ MQTT (v1) Agent API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html1/aws__mqtt__agent_8h.html) [MQTT (v2.x.x) C SDK API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/c-sdk/mqtt/index.html)  |  The coreMQTT library provides a client for your FreeRTOS device to publish and subscribe to MQTT topics. MQTT is the protocol that devices use to interact with AWS IoT. For more information about the coreMQTT library version 3.0.0, see [coreMQTT library](coremqtt.md).  | 
| coreMQTT Agent |  [ coreMQTT Agent Library API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/embedded-csdk/libraries/standard/coreMQTT-Agent/docs/doxygen/output/html/index.html)  |  The coreMQTT Agent library is a high level API that adds thread safety to the coreMQTT library. It lets you create a dedicated MQTT agent task that manages an MQTT connection in the background and doesn't need any intervention from other tasks. The library provides thread safe equivalents to the coreMQTT's APIs, so it can be used in multi-threaded environments. For more information about the coreMQTT Agent library see [coreMQTT Agent library](coremqtt-agent.md).  | 
| AWS IoT Device Shadow | [Device Shadow C SDK API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html1/aws__shadow_8h.html) |  The AWS IoT Device Shadow library enables your FreeRTOS device to interact with AWS IoT device shadows. For more information, see [AWS IoT Device Shadow library](freertos-lib-cloud-shadows.md).  | 

## Configuring the FreeRTOS libraries
<a name="lib-config"></a>

Configuration settings for FreeRTOS and the AWS IoT Device SDK for Embedded C are defined as C preprocessor constants. You can set configuration settings with a global configuration file, or by using a compiler option such as `-D` in `gcc`. Because configuration settings are defined as compile-time constants, a library must be rebuilt if a configuration setting is changed.

If you want to use a global configuration file to set configuration options, create and save the file with the name `iot_config.h`, and place it in your include path. Within the file, use `#define` directives to configure the FreeRTOS libraries, demos, and tests.

For more information about the supported global configuration options, see the [Global Configuration File Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/c-sdk/main/global_library_config.html#IOT_CONFIG_FILE).

# backoffAlgorithm library
<a name="backoffalgorithm-library"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Introduction
<a name="freertos-boa-introduction"></a>

The [backoffAlgorithm](https://github.com/FreeRTOS/backoffAlgorithm) library is a utility library that is used to space out repeated retransmissions of the same block of data, to avoid network congestion. This library calculates the backoff period for retrying network operations (like a failed network connection with the server) using an [ exponential backoff with jitter](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/) algorithm. 

Exponential backoff with jitter is typically used when retrying a failed connection or network request to a server that is caused by network congestion or high loads on the server. It is used to spread out the timing of the retry requests created by multiple devices attempting network connections at the same time. In an environment with poor connectivity, a client can get disconnected at any time; so a backoff strategy also helps the client to conserve battery by not repeatedly attempting reconnections when they are unlikely to succeed. 

The library is written in C and designed to be compliant with [ISO C90](https://en.wikipedia.org/wiki/ANSI_C#C90) and [MISRA C:2012](https://misra.org.uk/product/misra-c2012-third-edition-first-revision/). The library has no dependencies on any additional libraries other than the standard C library and has no heap allocation, making it suitable for IoT microcontrollers, but also fully portable to other platforms.

This library can be freely used and is distributed under the [MIT open source license](https://freertos.org/a00114.html).


****  

| Code Size of backoffAlgorithm (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| backoff\$1algorithm.c | 0.1K | 0.1K | 
| Total estimates | 0.1K | 0.1K | 

# Bluetooth Low Energy library
<a name="freertos-ble-library"></a>

**Important**  <a name="deprecation-message-library"></a>
This library is hosted on the Amazon-FreeRTOS repository which is deprecated. We recommend that you [start here](freertos-getting-started-modular.md) when you create a new project. If you already have an existing FreeRTOS project based on the now deprecated Amazon-FreeRTOS repository, see the [Amazon-FreeRTOS Github Repository Migration Guide](github-repo-migration.md).

## Overview
<a name="freertos-ble-overview"></a>

FreeRTOS supports publishing and subscribing to Message Queuing Telemetry Transport (MQTT) topics over Bluetooth Low Energy through a proxy device, such as a mobile phone. With the FreeRTOS [Bluetooth Low Energy](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/ble/index.html) (BLE) library, your microcontroller can securely communicate with the AWS IoT MQTT broker.

![\[BLE devices connecting to AWS IoT Core via MQTT/HTTP/Websocket through AWS Cognito.\]](http://docs.aws.amazon.com/freertos/latest/userguide/images/blediagram.jpg)


Using the Mobile SDKs for FreeRTOS Bluetooth Devices, you can write native mobile applications that communicate with the embedded applications on your microcontroller over BLE. For more information about the mobile SDKs, see [Mobile SDKs for FreeRTOS Bluetooth devices](freertos-ble-mobile.md). 

The FreeRTOS BLE library includes services for configuring Wi-Fi networks, transferring large amounts of data, and providing network abstractions over BLE. The FreeRTOS BLE library also includes middleware and lower-level APIs for more direct control over your BLE stack. 

## Architecture
<a name="freertos-ble-arch"></a>

Three layers make up the FreeRTOS BLE library: services, middleware, and low-level wrappers.

![\[Cloud architecture layers: User Application, Services, Middleware, Low-level Wrappers, Manufacturer BLE Stack.\]](http://docs.aws.amazon.com/freertos/latest/userguide/images/ble-architecture.png)


### Services
<a name="freertos-ble-services"></a>

The FreeRTOS BLE services layer consists of four Generic Attribute (GATT) services that leverage the middleware APIs: 
+ Device information
+ Wi-Fi provisioning
+ Network abstraction
+ Large object transfer

#### Device information
<a name="ble-device-information"></a>

The Device information service gathers details about your microcontroller, including:
+ The version of FreeRTOS that your device is using.
+ The AWS IoT endpoint of the account for which the device is registered.
+ Bluetooth Low Energy Maximum Transmission Unit (MTU).

#### Wi-Fi provisioning
<a name="ble-wifi-provisioning"></a>

The Wi-Fi provisioning service enables microcontrollers with Wi-Fi capabilities to do the following:
+ List networks in range.
+ Save networks and network credentials to flash memory.
+ Set network priority.
+ Delete networks and network credentials from flash memory.

#### Network abstraction
<a name="ble-network-abstraction"></a>

The network abstraction service abstracts the network connection type for applications. A common API interacts with your device's Wi-Fi, Ethernet, and Bluetooth Low Energy hardware stack, enabling an application to be compatible with multiple connection types.

#### Large Object Transfer
<a name="ble-object-transfer"></a>

The Large Object Transfer service sends data to, and receives data from, a client. Other services, like Wi-Fi provisioning and Network abstraction, use the Large Object Transfer service to send and receive data. You can also use the Large Object Transfer API to directly interact with the service.

#### MQTT over BLE
<a name="ble-device-mqtt"></a>

MQTT over BLE contains the GATT profile for creating an MQTT proxy service over BLE. The MQTT proxy service allows an MQTT client to communicate with the AWS MQTT broker through a gateway device. For example, you can use the proxy service to connect a device running FreeRTOS to AWS MQTT through a smartphone app. The BLE device is the GATT server and exposes services and characteristics for the gateway device. The GATT server uses these exposed services and characteristics to perform MQTT operations with the cloud for that device. For more details, refer to [Appendix A: MQTT over BLE GATT profile](#freertos-ble-gatt-profile).

### Middleware
<a name="freertos-ble-middleware"></a>

FreeRTOS Bluetooth Low Energy middleware is an abstraction from the lower-level APIs. The middleware APIs make up a more user-friendly interface to the Bluetooth Low Energy stack.

Using middleware APIs, you can register several callbacks, across multiple layers, to a single event. Initializing the Bluetooth Low Energy middleware also initializes services and starts advertising.

#### Flexible callback subscription
<a name="freertos-ble-flexible-callbacks"></a>

Suppose your Bluetooth Low Energy hardware disconnects, and the MQTT over Bluetooth Low Energy service needs to detect the disconnection. An application that you wrote might also need to detect the same disconnection event. The Bluetooth Low Energy middleware can route the event to different parts of the code where you have registered callbacks, without making the higher layers compete for lower-level resources.

### Low-level wrappers
<a name="freertos-ble-arch-lowlevel"></a>

The low-level FreeRTOS Bluetooth Low Energy wrappers are an abstraction from the manufacturer's Bluetooth Low Energy stack. Low-level wrappers offer a common set of APIs for direct control over the hardware. The low-level APIs optimize RAM usage, but are limited in functionality.

Use the Bluetooth Low Energy service APIs to interact with the Bluetooth Low Energy services. The service APIs demand more resources than the low-level APIs.

## Dependencies and requirements
<a name="freertos-ble-dependencies"></a>

The Bluetooth Low Energy library has the following direct dependencies:
+ [Linear Containers](https://docs.aws.amazon.com/freertos/latest/lib-ref/c-sdk/linear_containers/index.html) library
+ A platform layer that interfaces with the operating system for thread management, timers, clock functions, and network access.

![\[Architecture diagram showing components: BLE, List/Queue, Network, and Clock, with directional arrows indicating interactions.\]](http://docs.aws.amazon.com/freertos/latest/userguide/images/ble-dependencies.png)


Only the Wi-Fi Provisioning service has FreeRTOS library dependencies:


****  

| GATT Service | Dependency | 
| --- | --- | 
| Wi-Fi Provisioning | [Wi-Fi library](freertos-wifi.md) | 

To communicate with the AWS IoT MQTT broker, you must have an AWS account and you must register your devices as AWS IoT things. For more information about setting up, see the [AWS IoT Developer Guide](https://docs.aws.amazon.com/iot/latest/developerguide/).

FreeRTOS Bluetooth Low Energy uses Amazon Cognito for user authentication on your mobile device. To use MQTT proxy services, you must create an Amazon Cognito identity and user pools. Each Amazon Cognito Identity must have the appropriate policy attached to it. For more information, see the [Amazon Cognito Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/).

## Library configuration file
<a name="freertos-ble-configuration"></a>

Applications that use the FreeRTOS MQTT over Bluetooth Low Energy service must provide an `iot_ble_config.h` header file, in which configuration parameters are defined. Undefined configuration parameters take the default values specified in `iot_ble_config_defaults.h`.

Some important configuration parameters include:

**`IOT_BLE_ADD_CUSTOM_SERVICES`**  
Allows users to create their own services.

**`IOT_BLE_SET_CUSTOM_ADVERTISEMENT_MSG`**  
Allows users to customize the advertisement and scan response messages.

For more information, see [Bluetooth Low Energy API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/ble/index.html). 

## Optimization
<a name="freertos-ble-optimization"></a>

When optimizing your board's performance, consider the following:
+ Low-level APIs use less RAM, but offer limited functionality.
+ You can set the `bleconfigMAX_NETWORK` parameter in the `iot_ble_config.h` header file to a lower value to reduce the amount of stack consumed.
+ You can increase the MTU size to its maximum value to limit message buffering, and make code run faster and consume less RAM.

## Usage restrictions
<a name="freertos-ble-restrictions"></a>

By default, the FreeRTOS Bluetooth Low Energy library sets the `eBTpropertySecureConnectionOnly` property to TRUE, which places the device in a Secure Connections Only mode. As specified by the [Bluetooth Core Specification](https://www.bluetooth.com/specifications/bluetooth-core-specification) v5.0, Vol 3, Part C, 10.2.4, when a device is in a Secure Connections Only mode, the highest LE security mode 1 level, level 4, is required for access to any attribute that has permissions higher than the lowest LE security mode 1 level, level 1. At the LE security mode 1 level 4, a device must have input and output capabilities for numeric comparison.

Here are the supported modes, and their associated properties:

**Mode 1, Level 1 (No security)**  

```
/* Disable numeric comparison */
#define IOT_BLE_ENABLE_NUMERIC_COMPARISON        ( 0 )
#define IOT_BLE_ENABLE_SECURE_CONNECTION         ( 0 )
#define IOT_BLE_INPUT_OUTPUT                     ( eBTIONone )
#define IOT_BLE_ENCRYPTION_REQUIRED               ( 0 )
```

**Mode 1, Level 2 (Unauthenticated pairing with encryption)**  

```
#define IOT_BLE_ENABLE_NUMERIC_COMPARISON        ( 0 )
#define IOT_BLE_ENABLE_SECURE_CONNECTION         ( 0 )
#define IOT_BLE_INPUT_OUTPUT                     ( eBTIONone )
```

**Mode 1, Level 3 (Authenticated pairing with encryption)**  
This mode is not supported.

**Mode 1, Level 4 (Authenticated LE Secure Connections pairing with encryption)**  
This mode is supported by default.

For information about LE security modes, see the [Bluetooth Core Specification](https://www.bluetooth.com/specifications/bluetooth-core-specification) v5.0, Vol 3, Part C, 10.2.1.

## Initialization
<a name="freertos-ble-init"></a>

If your application interacts with the Bluetooth Low Energy stack through middleware, you only need to initialize the middleware. Middleware takes care of initializing the lower layers of the stack.

### Middleware
<a name="freertos-ble-init-middle"></a>

**To initialize the middleware**

1. Initialize any Bluetooth Low Energy hardware drivers before you call the Bluetooth Low Energy middleware API.

1. Enable Bluetooth Low Energy.

1. Initialize the middleware with `IotBLE_Init()`.
**Note**  
This initialization step is not required if you are running the AWS demos. Demo initialization is handled by the Network Manager, located at `freertos/demos/network_manager`.

### Low-level APIs
<a name="freertos-ble-init-low"></a>

If you don't want to use the FreeRTOS Bluetooth Low Energy GATT services, you can bypass the middleware and interact directly with the low-level APIs to save resources.

**To initialize the low-level APIs**

1. 

****

   Initialize any Bluetooth Low Energy hardware drivers before you call the APIs. Driver initialization is not part of the Bluetooth Low Energy low-level APIs.

1. 

****

   The Bluetooth Low Energy low-level API provides an enable/disable call to the Bluetooth Low Energy stack for optimizing power and resources. Before calling the APIs, you must enable Bluetooth Low Energy.

   ```
   const BTInterface_t * pxIface = BTGetBluetoothInterface();
   xStatus = pxIface->pxEnable( 0 );
   ```

1. 

****

   The Bluetooth manager contains APIs that are common to both Bluetooth Low Energy and Bluetooth classic. The callbacks for the common manager must be initialized second.

   ```
   xStatus = xBTInterface.pxBTInterface->pxBtManagerInit( &xBTManagerCb );
   ```

1. 

****

   The Bluetooth Low Energy adapter fits on top of the common API. You must initialize its callbacks like you initialized the common API.

   ```
   xBTInterface.pxBTLeAdapterInterface = ( BTBleAdapter_t * ) xBTInterface.pxBTInterface->pxGetLeAdapter();
   xStatus = xBTInterface.pxBTLeAdapterInterface->pxBleAdapterInit( &xBTBleAdapterCb );
   ```

1. 

****

   Register your new user application.

   ```
   xBTInterface.pxBTLeAdapterInterface->pxRegisterBleApp( pxAppUuid );
   ```

1. 

****

   Initialize the callbacks to the GATT servers.

   ```
   xBTInterface.pxGattServerInterface = ( BTGattServerInterface_t * ) xBTInterface.pxBTLeAdapterInterface->ppvGetGattServerInterface();
   xBTInterface.pxGattServerInterface->pxGattServerInit( &xBTGattServerCb );
   ```

   After you initialize the Bluetooth Low Energy adapter, you can add a GATT server. You can register only one GATT server at a time.

   ```
   xStatus = xBTInterface.pxGattServerInterface->pxRegisterServer( pxAppUuid );
   ```

1. 

****

   Set application properties like secure connection only and MTU size.

   ```
   xStatus = xBTInterface.pxBTInterface->pxSetDeviceProperty( &pxProperty[ usIndex ] );
   ```

## API reference
<a name="freertos-ble-api"></a>

For a full API reference, see [Bluetooth Low Energy API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/ble/index.html). 

## Example usage
<a name="freertos-ble-examples"></a>

The examples below demonstrate how to use the Bluetooth Low Energy library for advertising and creating new services. For full FreeRTOS Bluetooth Low Energy demo applications, see [Bluetooth Low Energy Demo Applications](https://docs.aws.amazon.com/freertos/latest/userguide/ble-demo.html).

### Advertising
<a name="freertos-ble-advertising"></a>

1. In your application, set the advertising UUID:

   ```
   static const BTUuid_t _advUUID =
   {
       .uu.uu128 = IOT_BLE_ADVERTISING_UUID,
       .ucType   = eBTuuidType128
   };
   ```

1. Then define the `IotBle_SetCustomAdvCb` callback function:

   ```
   void IotBle_SetCustomAdvCb( IotBleAdvertisementParams_t * pAdvParams,  IotBleAdvertisementParams_t * pScanParams)
   {
       memset(pAdvParams, 0, sizeof(IotBleAdvertisementParams_t));
       memset(pScanParams, 0, sizeof(IotBleAdvertisementParams_t));
   
       /* Set advertisement message */
       pAdvParams->pUUID1 = &_advUUID;
       pAdvParams->nameType = BTGattAdvNameNone;
   
       /* This is the scan response, set it back to true. */
       pScanParams->setScanRsp = true;
       pScanParams->nameType = BTGattAdvNameComplete;
   }
   ```

   This callback sends the UUID in the advertisement message and the full name in the scan response.

1. Open `vendors/vendor/boards/board/aws_demos/config_files/iot_ble_config.h`, and set `IOT_BLE_SET_CUSTOM_ADVERTISEMENT_MSG` to `1`. This triggers the `IotBle_SetCustomAdvCb` callback.

### Adding a new service
<a name="freertos-ble-add-service"></a>

For full examples of services, see `freertos/.../ble/services`.

1. Create UUIDs for the service's characteristic and descriptors:

   ```
   #define xServiceUUID_TYPE \
   {\
       .uu.uu128 = gattDemoSVC_UUID, \
       .ucType   = eBTuuidType128 \
   }
   #define xCharCounterUUID_TYPE \
   {\
       .uu.uu128 = gattDemoCHAR_COUNTER_UUID,\
       .ucType   = eBTuuidType128\
   }
   #define xCharControlUUID_TYPE \
   {\
       .uu.uu128 = gattDemoCHAR_CONTROL_UUID,\
       .ucType   = eBTuuidType128\
   }
   #define xClientCharCfgUUID_TYPE \
   {\
       .uu.uu16 = gattDemoCLIENT_CHAR_CFG_UUID,\
       .ucType  = eBTuuidType16\
   }
   ```

1. Create a buffer to register the handles of the characteristic and descriptors:

   ```
   static uint16_t usHandlesBuffer[egattDemoNbAttributes];
   ```

1. Create the attribute table. To save some RAM, define the table as a `const`.
**Important**  
Always create the attributes in order, with the service as the first attribute.

   ```
   static const BTAttribute_t pxAttributeTable[] = {
        {    
            .xServiceUUID =  xServiceUUID_TYPE
        },
       {
            .xAttributeType = eBTDbCharacteristic,
            .xCharacteristic = 
            {
                 .xUuid = xCharCounterUUID_TYPE,
                 .xPermissions = ( IOT_BLE_CHAR_READ_PERM ),
                 .xProperties = ( eBTPropRead | eBTPropNotify )
             }
        },
        {
            .xAttributeType = eBTDbDescriptor,
            .xCharacteristicDescr =
            {
                .xUuid = xClientCharCfgUUID_TYPE,
                .xPermissions = ( IOT_BLE_CHAR_READ_PERM | IOT_BLE_CHAR_WRITE_PERM )
             }
        },
       {
            .xAttributeType = eBTDbCharacteristic,
            .xCharacteristic = 
            {
                 .xUuid = xCharControlUUID_TYPE,
                 .xPermissions = ( IOT_BLE_CHAR_READ_PERM | IOT_BLE_CHAR_WRITE_PERM  ),
                 .xProperties = ( eBTPropRead | eBTPropWrite )
             }
        }
   };
   ```

1. Create an array of callbacks. This array of callbacks must follow the same order as the table array defined above.

   For example, if `vReadCounter` gets triggered when `xCharCounterUUID_TYPE` is accessed, and `vWriteCommand` gets triggered when `xCharControlUUID_TYPE` is accessed, define the array as follows:

   ```
   static const IotBleAttributeEventCallback_t pxCallBackArray[egattDemoNbAttributes] =
       {
     NULL,
     vReadCounter,
     vEnableNotification,
     vWriteCommand
   };
   ```

1. Create the service:

   ```
   static const BTService_t xGattDemoService = 
   {
     .xNumberOfAttributes = egattDemoNbAttributes,
     .ucInstId = 0,
     .xType = eBTServiceTypePrimary,
     .pusHandlesBuffer = usHandlesBuffer,
     .pxBLEAttributes = (BTAttribute_t *)pxAttributeTable
   };
   ```

1. Call the API `IotBle_CreateService` with the structure that you created in the previous step. The middleware synchronizes the creation of all services, so any new services need to already be defined when the `IotBle_AddCustomServicesCb` callback is triggered.

   1. Set `IOT_BLE_ADD_CUSTOM_SERVICES` to `1` in `vendors/vendor/boards/board/aws_demos/config_files/iot_ble_config.h`.

   1. Create IotBle\$1AddCustomServicesCb in your application:

      ```
      void IotBle_AddCustomServicesCb(void)
      {
          BTStatus_t xStatus;
          /* Select the handle buffer. */
          xStatus = IotBle_CreateService( (BTService_t *)&xGattDemoService, (IotBleAttributeEventCallback_t *)pxCallBackArray );
      }
      ```

## Porting
<a name="freertos-ble-porting"></a>

### User input and output peripheral
<a name="freertos-ble-porting-io"></a>

A secure connection requires both input and output for numeric comparison. The `eBLENumericComparisonCallback` event can be registered using the event manager:

```
xEventCb.pxNumericComparisonCb = &prvNumericComparisonCb;
xStatus = BLE_RegisterEventCb( eBLENumericComparisonCallback, xEventCb );
```

The peripheral must display the numeric passkey and take the result of the comparison as an input.

### Porting API implementations
<a name="freertos-ble-porting-apis"></a>

To port FreeRTOS to a new target, you must implement some APIs for the Wi-Fi Provisioning service and Bluetooth Low Energy functionality.

#### Bluetooth Low Energy APIs
<a name="freertos-ble-porting-ble"></a>

To use the FreeRTOS Bluetooth Low Energy middleware, you must implement some APIs.

##### APIs common between GAP for Bluetooth Classic and GAP for Bluetooth Low Energy
<a name="gap-common-apis"></a>
+ `pxBtManagerInit`
+ `pxEnable`
+ `pxDisable`
+ `pxGetDeviceProperty`
+ `pxSetDeviceProperty` (All options are mandatory expect `eBTpropertyRemoteRssi` and `eBTpropertyRemoteVersionInfo`)
+ `pxPair`
+ `pxRemoveBond`
+ `pxGetConnectionState`
+ `pxPinReply`
+ `pxSspReply`
+ `pxGetTxpower`
+ `pxGetLeAdapter`
+ `pxDeviceStateChangedCb`
+ `pxAdapterPropertiesCb`
+ `pxSspRequestCb`
+ `pxPairingStateChangedCb`
+ `pxTxPowerCb`

##### APIs specific to GAP for Bluetooth Low Energy
<a name="gap-common-apis-ble"></a>
+ `pxRegisterBleApp`
+ `pxUnregisterBleApp`
+ `pxBleAdapterInit`
+ `pxStartAdv`
+ `pxStopAdv`
+ `pxSetAdvData`
+ `pxConnParameterUpdateRequest`
+ `pxRegisterBleAdapterCb`
+ `pxAdvStartCb`
+ `pxSetAdvDataCb`
+ `pxConnParameterUpdateRequestCb`
+ `pxCongestionCb`

##### GATT server
<a name="gap-common-apis-gatt"></a>
+ `pxRegisterServer`
+ `pxUnregisterServer`
+ `pxGattServerInit`
+ `pxAddService`
+ `pxAddIncludedService`
+ `pxAddCharacteristic`
+ `pxSetVal`
+ `pxAddDescriptor`
+ `pxStartService`
+ `pxStopService`
+ `pxDeleteService`
+ `pxSendIndication`
+ `pxSendResponse`
+ `pxMtuChangedCb`
+ `pxCongestionCb`
+ `pxIndicationSentCb`
+ `pxRequestExecWriteCb`
+ `pxRequestWriteCb`
+ `pxRequestReadCb`
+ `pxServiceDeletedCb`
+ `pxServiceStoppedCb`
+ `pxServiceStartedCb`
+ `pxDescriptorAddedCb`
+ `pxSetValCallbackCb`
+ `pxCharacteristicAddedCb`
+ `pxIncludedServiceAddedCb`
+ `pxServiceAddedCb`
+ `pxConnectionCb`
+ `pxUnregisterServerCb`
+ `pxRegisterServerCb`

For more information about porting the FreeRTOS Bluetooth Low Energy library to your platform, see [Porting the Bluetooth Low Energy Library](https://docs.aws.amazon.com/freertos/latest/portingguide/afr-porting-ble.html) in the FreeRTOS Porting Guide.

# Mobile SDKs for FreeRTOS Bluetooth devices
<a name="freertos-ble-mobile"></a>

**Important**  <a name="deprecation-message-library"></a>
This library is hosted on the Amazon-FreeRTOS repository which is deprecated. We recommend that you [start here](freertos-getting-started-modular.md) when you create a new project. If you already have an existing FreeRTOS project based on the now deprecated Amazon-FreeRTOS repository, see the [Amazon-FreeRTOS Github Repository Migration Guide](github-repo-migration.md).

You can use the Mobile SDKs for FreeRTOS Bluetooth Devices to create mobile applications that interact with your microcontroller over Bluetooth Low Energy. The Mobile SDKs can also communicate with AWS services, using Amazon Cognito for user authentication.

## Android SDK for FreeRTOS Bluetooth devices
<a name="freertos-ble-android"></a>

Use the Android SDK for FreeRTOS Bluetooth Devices to build Android mobile applications that interact with your microcontroller over Bluetooth Low Energy. The SDK is available on [GitHub](https://github.com/aws/amazon-freertos-ble-android-sdk/). 

To install the Android SDK for FreeRTOS Bluetooth devices, follow the instructions for "Setting up the SDK" in the project's [ README.md](https://github.com/aws/amazon-freertos-ble-android-sdk/blob/master/README.md) file.

For information about setting up and running the demo mobile application that is included with the SDK, see [Prerequisites](ble-demo.md#ble-demo-prereqs) and [FreeRTOS Bluetooth Low Energy Mobile SDK demo application](ble-demo.md#ble-sdk-app).

## iOS SDK for FreeRTOS Bluetooth devices
<a name="freertos-ble-ios"></a>

Use the iOS SDK for FreeRTOS Bluetooth Devices to build iOS mobile applications that interact with your microcontroller over Bluetooth Low Energy. The SDK is available on [GitHub](https://github.com/aws/amazon-freertos-ble-ios-sdk/).

**To install the iOS SDK**

1. Install [CocoaPods](http://cocoapods.org/):

   ```
   $ gem install cocoapods
   $ pod setup
   ```
**Note**  
You might need to use `sudo` to install CocoaPods.

1. Install the SDK with CocoaPods (add this to your podfile):

   ```
   $ pod 'FreeRTOS', :git => 'https://github.com/aws/amazon-freertos-ble-ios-sdk.git'
   ```

For information about setting up and running the demo mobile application that is included with the SDK, see [Prerequisites](ble-demo.md#ble-demo-prereqs) and [FreeRTOS Bluetooth Low Energy Mobile SDK demo application](ble-demo.md#ble-sdk-app).

## Appendix A: MQTT over BLE GATT profile
<a name="freertos-ble-gatt-profile"></a>

### GATT Service Details
<a name="freertos-ble-gatt-profile-details"></a>

MQTT over BLE uses an instance of the data transfer GATT service to send MQTT Concise Binary Object Representation (CBOR) messages between the FreeRTOS device and the proxy device. The data transfer service exposes certain characteristics that help send and receive raw data over the BLE GATT protocol. It also handles the fragmentation and assembly of payloads greater than the BLE maximum transfer unit (MTU) size.

**Service UUID**  
`A9D7-166A-D72E-40A9-A002-4804-4CC3-FF00` 

**Service Instances**  
One instance of the GATT service is created for each MQTT session with the broker. Each service has a unique UUID (two bytes) that identifies its type. Each individual instance is differentiated by the instance ID.   
Each service is instantiated as a primary service on each BLE server device. You can create multiple instances of the service on a given device. The MQTT proxy service type has a unique UUID. 

**Characteristics**  
Characteristic content format: **CBOR**   
Max characteristic value size : 512 bytes     
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/freertos/latest/userguide/freertos-ble-library.html)

**GATT Procedure Requirements **    
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/freertos/latest/userguide/freertos-ble-library.html)

**Message Types **  
The following message types are exchanged.    
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/freertos/latest/userguide/freertos-ble-library.html)

**Large Payload Transfer Characteristics **    
**TXLargeMessage **  
TXLargeMessage is used by the device to send a large payload that is greater than the MTU size negotiated for the BLE connection.   
+ The device sends the first MTU bytes of the payload as a notification through the characteristic. 
+ The proxy sends a read request on this characteristic for the remaining bytes. 
+ The device sends up to the MTU size or the remaining bytes of the payload, whichever is less. Each time, it increases the offset read by the size of the payload sent. 
+ The proxy will continue to read the characteristic until it gets a zero length payload or a payload less than the MTU size. 
+ If the device doesn't get a read request within a specified timeout, the transfer fails and the proxy and gateway release the buffer. 
+ If the proxy doesn't get a read response within a specified timeout, the transfer fails and the proxy releases the buffer.   
**RXLargeMessage **  
RXLargeMessage is used by the device to receive a large payload that is greater than the MTU size negotiated for the BLE connection.   
+ The proxy writes messages, up to the MTU size, one by one, using write with response on this characteristic. 
+ The device buffers the message until it receives a write request with zero length or a length less than the MTU size. 
+ If the device doesn't get a write request within a specified timeout, the transfer fails and the device releases the buffer. 
+ If the proxy doesn't get a write response within a specified timeout, the transfer fails and the proxy releases the buffer. 

# Cellular Interface library
<a name="cellular-interface"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Introduction
<a name="freertos-cellular-interface-introduction"></a>

The Cellular Interface library implements a simple unified [API](https://freertos.github.io/FreeRTOS-Cellular-Interface/v1.3.0/) that hides the complexity of the cellular modem-specific AT commands and exposes a socket-like interface to C programmers.

Most cellular modems implement more or less of the AT commands defined by the [ 3GPP TS v27.007](https://portal.3gpp.org/desktopmodules/Specifications/SpecificationDetails.aspx?specificationId=1515) standard. This project provides an [implementation](https://github.com/FreeRTOS/FreeRTOS-Cellular-Interface/tree/main/source) of such standard AT commands in a [ reusable common component](https://freertos.org/Documentation/api-ref/cellular/cellular_porting_module_guide.html). The three Cellular Interface libraries in this project all take advantage of that common code. The library for each modem only implements the vendor-specific AT commands, then exposes the complete Cellular Interface library API.

The common component that implements the 3GPP TS v27.007 standard has been written in compliance with the following code quality criteria: 
+ GNU Complexity scores are not over 8
+ MISRA C:2012 coding standard. Any deviations from the standard are documented in source code comments marked by "coverity".

## Dependencies and requirements
<a name="freertos-cellular-interface-dependencies"></a>

There is no direct dependency for the Cellular Interface library. However, Ethernet, Wi-Fi and cellular cannot co-exist in the FreeRTOS network stack. Developers must choose one of the network interface to integrate with the [Secure Sockets library](https://docs.aws.amazon.com/freertos/latest/userguide/secure-sockets.html). 

## Porting
<a name="freertos-cellular-interface-porting"></a>

For information about porting the Cellular Interface library to your platform, see [ Porting the Cellular Interface library](https://docs.aws.amazon.com/freertos/latest/portingguide/freertos-porting-cellular.html) in the *FreeRTOS Porting Guide*. 

## Memory use
<a name="freertos-cellular-interface-memory-use"></a>


****  

| Code Size of cellular interface library (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| cellular\$13gpp\$1api.c | 6.3K | 5.7K | 
| cellular\$13gpp\$1urc\$1handler.c | 0.9K | 0.8K | 
| cellular\$1at\$1core.c | 1.4K | 1.2K | 
| cellular\$1common\$1api.c | 0.5K | 0.5K | 
| cellular\$1common.c | 1.6K | 1.4K | 
| cellular\$1pkthandler.c | 1.4K | 1.2K | 
| cellular\$1pktio.c | 1.8K | 1.6K | 
| Total estimates | 13.9K | 12.4K | 

## Getting started
<a name="freertos-cellular-interface-getting-started"></a>

### Download the source code
<a name="freertos-cellular-interface-download-source"></a>

The source code can be downloaded as part of the FreeRTOS libraries or by itself.

To clone the library from Github using HTTPS: 

```
git clone https://github.com/FreeRTOS/FreeRTOS-Cellular-Interface.git 
```

Using SSH:

```
git clone git@github.com:FreeRTOS/FreeRTOS-Cellular-Interface.git 
```

### Folder structure
<a name="freertos-cellular-interface-folder-structure"></a>

At the root of this repository you will see these folders: 
+ `source` : reusable common code that implements the standard AT commands defined by 3GPP TS v27.007
+ `doc` : documentation
+ `test` : unit test and cbmc
+ `tools` : tools for Coverity static analysis and CMock

### Configure and build the Library
<a name="freertos-cellular-interface-configure"></a>

The Cellular Interface library should be built as part of an application. In order to do this, you must provide certain configurations. The [ FreeRTOS\$1Cellular\$1Interface\$1Windows\$1Simulator](https://github.com/FreeRTOS/FreeRTOS/tree/main/FreeRTOS-Plus/Demo/FreeRTOS_Cellular_Interface_Windows_Simulator) project provides an [ example](https://github.com/FreeRTOS/FreeRTOS/blob/main/FreeRTOS-Plus/Demo/FreeRTOS_Cellular_Interface_Windows_Simulator/MQTT_Mutual_Auth_Demo_with_BG96/cellular_config.h) of how to configure the build. More information can be found in the [Cellular API References](https://freertos.github.io/FreeRTOS-Cellular-Interface/v1.3.0/cellular_config.html). 

Please refer to the [Cellular Interface](https://www.freertos.org/cellular/index.html) page for more information.

## Integrate the Cellular Interface library with MCU platforms
<a name="freertos-cellular-interface-integrate"></a>

The Cellular Interface library runs on MCUs using an abstracted interface, the [ Comm Interface](https://github.com/FreeRTOS/FreeRTOS-Cellular-Interface/blob/main/source/interface/cellular_comm_interface.h), to communicate with cellular modems. A Comm Interface must be implemented on the MCU platform as well. The most common implementations of the Comm Interface communicate over UART hardware, but can be implemented over other physical interfaces, such as SPI, as well. The documentation for the Comm Interface can be found in the [ Cellular Library API References](https://freertos.github.io/FreeRTOS-Cellular-Interface/v1.3.0/cellular_porting.html#cellular_porting_comm_if). The following example implementations of the Comm Interface are available:
+ [ FreeRTOS Windows simulator comm interface](https://github.com/FreeRTOS/FreeRTOS/blob/main/FreeRTOS-Plus/Demo/FreeRTOS_Cellular_Interface_Windows_Simulator/Common/comm_if_windows.c)
+ [ FreeRTOS Common IO UART comm interface](https://github.com/aws/amazon-freertos/blob/main/libraries/abstractions/common_io/include/iot_uart.h)
+ [ STM32 L475 discovery board comm interface](https://github.com/aws/amazon-freertos/blob/feature/cellular/vendors/st/boards/stm32l475_discovery/ports/comm_if/comm_if_uart.c)
+ [ Sierra Sensor Hub board comm interface](https://github.com/aws/amazon-freertos/blob/feature/cellular/vendors/sierra/boards/sensorhub/ports/comm_if/comm_if_sierra.c)

# Common I/O
<a name="common-io"></a>

**Important**  <a name="deprecation-message-library"></a>
This library is hosted on the Amazon-FreeRTOS repository which is deprecated. We recommend that you [start here](freertos-getting-started-modular.md) when you create a new project. If you already have an existing FreeRTOS project based on the now deprecated Amazon-FreeRTOS repository, see the [Amazon-FreeRTOS Github Repository Migration Guide](github-repo-migration.md).

**Overview **

In general, device drivers are independent of the underlying operating system and are specific to a given hardware configuration. A hardware abstraction layer (HAL) provides a common interface between drivers and higher-level application code. The HAL abstracts away the details of how a specific driver works and provides a uniform API to control such devices. You can use the same APIs to access various device drivers across multiple microcontroller (MCU) based reference boards.

FreeRTOS [common I/O](https://docs.aws.amazon.com/freertos/latest/lib-ref/common-io/index.html) acts as this hardware abstraction layer. It provides a set of standard APIs for accessing common serial devices on supported reference boards. These common APIs communicate and interact with these peripherals and enable your code to function across platforms. Without common I/O, writing code to work with low level devices is silicon-vendor specific.

**Supported peripherals**
+ UART
+ SPI
+ I2C

**Supported features**
+ Synchronous read/write – The function doesn't return until the requested amount of data is transferred. 
+ Asynchronous read/write – The function returns immediately and the data transfer happens asynchronously. When the action completes, a registered user callback is invoked.

**Peripheral specific**
+ I2C – Combine multiple operations into one transaction. Used to do write then read actions in one transaction. 
+ SPI – Transfer data between primary and secondary, which means the write and read happen simultaneously.

**Porting**

For more information, see the [ FreeRTOS Porting Guide](https://docs.aws.amazon.com/freertos/latest/portingguide/).

# AWS IoT Device Defender library
<a name="afr-device-defender-library"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Introduction
<a name="freertos-defender-introduction"></a>

You can use the AWS IoT Device Defender library to send security metrics from your IoT devices to AWS IoT Device Defender. You can use AWS IoT Device Defender to continuously monitor these security metrics from devices for deviations from what you have defined as appropriate behavior for each device. If something doesn't look right, AWS IoT Device Defender sends out an alert so that you can take action to fix the issue. Interactions with AWS IoT Device Defender use [MQTT](https://freertos.org/mqtt/index.html), a lightweight publish-subscribe protocol. This library provides an API to compose and recognize the MQTT topic strings used by AWS IoT Device Defender.

 For more information, see [AWS IoT Device Defender](https://docs.aws.amazon.com/iot/latest/developerguide/device-defender.html) in the *AWS IoT Developer Guide*.

The library is written in C and designed to be compliant with [ISO C90](https://en.wikipedia.org/wiki/ANSI_C#C90) and [MISRA C:2012](https://misra.org.uk/product/misra-c2012-third-edition-first-revision/). The library has no dependencies on any additional libraries other than the standard C library. It also doesn't have any platform dependencies, such as threading or synchronization. It can be used with any MQTT library and any [JSON](https://freertos.org/json/json-terminology.html) or [CBOR](https://cbor.io/) library. The library has [proofs](https://www.cprover.org/cbmc/) showing safe memory use and no heap allocation, making it suitable for IoT microcontrollers, but also fully portable to other platforms.

The AWS IoT Device Defender library can be freely used and is distributed under the [MIT open source license](https://freertos.org/a00114.html).


****  

| Code Size of AWS IoT Device Defender (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| defender.c | 1.1K | 0.6K | 
| Total estimates | 1.1K | 0.6K | 

# AWS IoT Greengrass Discovery library
<a name="freertos-lib-gg-connectivity"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Overview
<a name="freertos-gg-overview"></a>

The [AWS IoT Greengrass Discovery ](https://docs.aws.amazon.com/freertos/latest/lib-ref/html1/aws__greengrass__discovery_8h.html) library is used by your microcontroller devices to discover a Greengrass core on your network. Using the AWS IoT Greengrass Discovery APIs, your device can send messages to a Greengrass core after it finds the core's endpoint.

## Dependencies and requirements
<a name="freertos-gg-dependencies"></a>

To use the Greengrass Discovery library, you must create a thing in AWS IoT, including a certificate and policy. For more information, see [AWS IoT Getting Started](https://docs.aws.amazon.com/iot/latest/developerguide/iot-gs.html). 

You must set values for the following constants in the `freertos/demos/include/aws_clientcredential.h` file:

**`clientcredentialMQTT_BROKER_ENDPOINT`**  
Your AWS IoT endpoint.

**`clientcredentialIOT_THING_NAME`**  
The name of your IoT thing.

**`clientcredentialWIFI_SSID`**  
The SSID for your Wi-Fi network.

**`clientcredentialWIFI_PASSWORD`**  
Your Wi-Fi password.

**`clientcredentialWIFI_SECURITY`**  
The type of security used by your Wi-Fi network.

You must also set values for the following constants in the `freertos/demos/include/aws_clientcredential_keys.h` file:

**`keyCLIENT_CERTIFICATE_PEM`**  
The certificate PEM associated with your thing.

**`keyCLIENT_PRIVATE_KEY_PEM`**  
The private key PEM associated with your thing.

You must have a Greengrass group and core device set up in the console. For more information, see [Getting Started with AWS IoT Greengrass](https://docs.aws.amazon.com/greengrass/latest/developerguide/).

Although the coreMQTT library is not required for Greengrass connectivity, we strongly recommend you install it. The library can be used to communicate with the Greengrass core after it has been discovered.

## API reference
<a name="freertos-gg-api"></a>

For a full API reference, see [Greengrass API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html1/aws__greengrass__discovery_8h.html).

## Example usage
<a name="freertos-gg-example"></a>

### Greengrass workflow
<a name="freertos-lib-gg-workflow"></a>

The MCU device initiates the discovery process by requesting from AWS IoT a JSON file that contains the Greengrass core connectivity parameters. There are two methods for retrieving the Greengrass core connectivity parameters from the JSON file:
+ Automatic selection iterates through all of the Greengrass cores listed in the JSON file and connects to the first one available. 
+ Manual selection uses the information in `aws_ggd_config.h` to connect to the specified Greengrass core.

### How to use the Greengrass API
<a name="freertos-lib-gg-api"></a>

All default configuration options for the Greengrass API are defined in `aws_ggd_config_defaults.h`.

If only one Greengrass core is present, call `GGD_GetGGCIPandCertificate` to request the JSON file with Greengrass core connectivity information. When `GGD_GetGGCIPandCertificate` is returned, the `pcBuffer` parameter contains the text of the JSON file. The `pxHostAddressData` parameter contains the IP address and port of the Greengrass core to which you can connect.

For more customization options, like dynamically allocating certificates, you must call the following APIs:

**`GGD_JSONRequestStart`**  
Makes an HTTP GET request to AWS IoT to initiate the discovery request to discover a Greengrass core. `GD_SecureConnect_Send` is used to send the request to AWS IoT.

**`GGD_JSONRequestGetSize`**  
Gets the size of the JSON file from the HTTP response.

**`GGD_JSONRequestGetFile`**  
Gets the JSON object string. `GGD_JSONRequestGetSize` and `GGD_JSONRequestGetFile` use `GGD_SecureConnect_Read` to get the JSON data from the socket. `GGD_JSONRequestStart`, `GGD_SecureConnect_Send`, `GGD_JSONRequestGetSize` must be called to receive the JSON data from AWS IoT.

**`GGD_GetIPandCertificateFromJSON`**  
Extracts the IP address and the Greengrass core certificate from the JSON data. You can turn on automatic selection by setting the `xAutoSelectFlag` to `True`. Automatic selection finds the first core device your FreeRTOS device can connect to. To connect to a Greengrass core, call the `GGD_SecureConnect_Connect` function, passing in the IP address, port, and certificate of the core device. To use manual selection, set the following fields of the `HostParameters_t` parameter:    
**`pcGroupName`**  
The ID of the Greengrass group to which the core belongs. You can use the `aws greengrass list-groups` CLI command to find the ID of your Greengrass groups.  
**`pcCoreAddress`**  
The ARN of the Greengrass core to which you are connecting.

# coreHTTP library
<a name="core-http"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

**HTTP C client library for small IoT devices (MCU or small MPU)**

## Introduction
<a name="core-http-introduction"></a>

The coreHTTP library is a client implementation of a subset of the [HTTP/1.1](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) standard. The HTTP standard provides a stateless protocol that runs on top of TCP/IP and is often used in distributed, collaborative, hypertext information systems.

The coreHTTP library implements a subset of the [HTTP/1.1 ](https://tools.ietf.org/html/rfc2616) protocol standard. This library has been optimized for a low memory footprint. The library provides a fully synchronous API so applications can completely manage their concurrency. It uses fixed buffers only, so that applications have complete control of their memory allocation strategy.

The library is written in C and designed to be compliant with [ISO C90](https://en.wikipedia.org/wiki/ANSI_C#C90) and [MISRA C:2012](https://misra.org.uk/product/misra-c2012-third-edition-first-revision/). The library's only dependencies are the standard C library and [LTS version (v12.19.1) of the http-parser](https://github.com/nodejs/node/tree/v12.19.1/deps/http_parser) from Node.js. The library has [proofs](https://www.cprover.org/cbmc/) showing safe memory use and no heap allocation, making it suitable for IoT microcontrollers, but also fully portable to other platforms.

When using HTTP connections in IoT applications, we recommend that you use a secure transport interface, such as one that uses the TLS protocol as demonstrated in the [coreHTTP mutual authentication demo](core-http-ma-demo.md).

This library can be freely used and is distributed under the [MIT open source license](https://freertos.org/a00114.html).


****  

| Code Size of coreHTTP (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| core\$1http\$1client.c | 3.2K | 2.6K | 
| api.c (llhttp) | 2.6K | 2.0K | 
| http.c (llhttp) | 0.3K | 0.3K | 
| llhttp.c (llhttp) | 17.9 | 15.9 | 
| Total estimates | 23.9K | 20.7K | 

# coreJSON library
<a name="freertos-lib-corejson"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Introduction
<a name="freertos-corejson-introduction"></a>

JSON (JavaScript Object Notation) is a human-readable data serialization format. It is widely used to exchange data, such as with the [AWS IoT Device Shadow service](https://docs.aws.amazon.com/iot/latest/developerguide/iot-device-shadows.html), and is part of many APIs, such as the GitHub REST API. JSON is maintained as a standard by Ecma International.

The coreJSON library provides a parser that supports key lookups while strictly enforcing the [ECMA-404 Standard JSON Data Interchange syntax](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf). The library is written in C and designed to comply with ISO C90 and MISRA C:2012. It has [proofs](https://www.cprover.org/cbmc/) showing safe memory use and no heap allocation, making it suitable for IoT microcontrollers, but also fully portable to other platforms.

## Memory use
<a name="freertos-corejson-memory"></a>

The coreJSON library uses an internal stack to track nested structures in a JSON document. The stack exists for the duration of a single function call; it is not preserved. Stack size may be specified by defining the macro, `JSON_MAX_DEPTH`, which defaults to 32 levels. Each level consumes a single byte.


****  

| Code Size of coreJSON (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| core\$1json.c | 2.9K | 2.4K | 
| Total estimates | 2.9K | 2.4K | 

# coreMQTT library
<a name="coremqtt"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Introduction
<a name="coremqtt-introduction"></a>

The coreMQTT library is a client implementation of the [MQTT](https://en.wikipedia.org/wiki/MQTT) (Message Queue Telemetry Transport) standard. The MQTT standard provides a lightweight publish/subscribe (or [PubSub](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) messaging protocol that runs on top of TCP/IP and is often used in Machine to Machine (M2M) and Internet of Things (IoT) use cases. 

The coreMQTT library is compliant with the [ MQTT 3.1.1](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html) protocol standard. This library has been optimized for a low memory footprint. The design of this library embraces different use-cases, ranging from resource-constrained platforms using only QoS 0 MQTT PUBLISH messages to resource-rich platforms using QoS 2 MQTT PUBLISH over TLS (Transport Layer Security) connections. The library provides a menu of composable functions, which can be chosen and combined to precisely fit the needs of a particular use-case.

The library is written in **C** and designed to be compliant with [ISO C90](https://en.wikipedia.org/wiki/ANSI_C#C90) and [MISRA C:2012](https://misra.org.uk/product/misra-c2012-third-edition-first-revision/). This MQTT library has no dependencies on any additional libraries except for the following:
+ The standard C library
+ A customer-implemented network transport interface
+ (Optional) A user-implemented platform time function

The library is decoupled from the underlying network drivers through the provision of a simple send and receive transport interface specification. The application writer can select an existing transport interface, or implement their own as appropriate for their application.

The library provides a high-level API to connect to an MQTT broker, subscribe/unsubscribe to a topic, publish a message to a topic and receive incoming messages. This API takes the transport interface described above as a parameter and uses that to send and receive messages to and from the MQTT broker.

The library also exposes low level serializer/deserializer API. This API can be used to build a simple IoT application consisting of only the required a subset of MQTT functionality, without any other overhead. The serializer/deserializer API can be used in conjunction with any available transport layer API, like sockets, to send and receive messages to and from the broker.

When using MQTT connections in IoT applications, we recommended that you use a secure transport interface, such as one that uses the TLS protocol.

This MQTT library doesn't have platform dependencies, such as threading or synchronization. This library does have [proofs](https://www.cprover.org/cbmc/) that demonstrate safe memory use and no heap allocation, which makes it suitable for IoT microcontrollers, but also fully portable to other platforms. It can be freely used, and is distributed under the [MIT open source license](https://freertos.org/a00114.html).


****  

| Code Size of coreMQTT (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| core\$1mqtt.c | 4.0K | 3.4K | 
| core\$1mqtt\$1state.c | 1.7K | 1.3K | 
| core\$1mqtt\$1serializer.c | 2.8K | 2.2K | 
| Total estimates | 8.5K | 6.9K | 

# coreMQTT Agent library
<a name="coremqtt-agent"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Introduction
<a name="coremqtt-agent-introduction"></a>

The coreMQTT Agent library is a high level API that adds thread safety to the [coreMQTT library](coremqtt.md). It lets you create a dedicated MQTT agent task that manages an MQTT connection in the background and doesn't need any intervention from other tasks. The library provides thread safe equivalents to the coreMQTT's APIs, so it can be used in multi-threaded environments.

The MQTT agent is an independent task (or thread of execution). It achieves thread safety by being the only task that is permitted to access the MQTT library's API. It serializes access by isolating all MQTT API calls to a single task, and it removes the need for semaphores or any other synchronization primitives.

The library uses a thread safe messaging queue (or other inter-process communication mechanism) to serialize all requests to call MQTT APIs. The messaging implementation is decoupled from the library through a messaging interface, which allows the library to be ported to other operating systems. The messaging interface is composed of functions to send and receive pointers to the agent's command structures, and functions to allocate these command objects, which allows the application writer to decide the memory allocation strategy appropriate for their application.

The library is written in C and designed to be compliant with [ISO C90](https://en.wikipedia.org/wiki/ANSI_C#C90) and [MISRA C:2012](https://misra.org.uk/product/misra-c2012-third-edition-first-revision/). The library has no dependencies on any additional libraries other than [coreMQTT library](coremqtt.md) and the standard C library. The library has [proofs](https://www.cprover.org/cbmc/) that show safe memory use and no heap allocation, so it can be used for IoT microcontrollers, but is also fully portable to other platforms.

This library can be freely used and is distributed under the [ MIT open source license](https://www.freertos.org/a00114.html).


****  

| Code Size of coreMQTT Agent (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| core\$1mqtt\$1agent.c | 1.7K | 1.5K | 
| core\$1mqtt\$1agent\$1command\$1functions.c | 0.3K | 0.2K | 
| core\$1mqtt.c (coreMQTT) | 4.0K | 3.4K | 
| core\$1mqtt\$1state.c (coreMQTT) | 1.7K | 1.3K | 
| core\$1mqtt\$1serializer.c (coreMQTT) | 2.8K | 2.2K | 
| Total estimates | 10.5K | 8.6K | 

# AWS IoT Over the air (OTA) library
<a name="ota-update-library"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Introduction
<a name="ota-update-library-intro"></a>

The [AWS IoT Over-the-air (OTA) update library](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/index.html) enables you to manage the notification, download, and verification of firmware updates for FreeRTOS devices using HTTP or MQTT as the protocol. By using the OTA Agent library, you can logically separate firmware updates and the application running on your devices. The OTA Agent can share a network connection with the application. By sharing a network connection, you can potentially save a significant amount of RAM. In addition, the OTA Agent library lets you define application-specific logic for testing, committing, or rolling back a firmware update.

The Internet of Things (IoT) extends internet connectivity to embedded devices that were traditionally not connected. These devices can be programmed to communicate usable data over the internet, and can be remotely monitored and controlled. With advances in technology, these traditional embedded devices are getting internet capabilities in consumer, industrial, and enterprise spaces at a fast pace.

IoT devices are typically deployed in large quantities and often in places that are difficult or impractical for a human operator to access. Imagine a scenario where a security vulnerability that can expose data is discovered. In such scenarios, it is important to update the affected devices with security fixes quickly and reliably. Without the ability to perform OTA updates, it can also be difficult to update devices that are geographically dispersed. Having a technician update these devices will be costly, time consuming, and often times impractical. The time required to update these devices leaves them exposed to security vulnerabilities for a longer period. Recalling these devices for updating will also be costly and may cause significant disruption to consumers due to downtime.

Over the Air (OTA) Updates make it possible to update device firmware without an expensive recall or technician visit. This method adds the following benefits:
+ **Security** - The ability to quickly respond to security vulnerabilities and software bugs that are discovered after the devices are deployed in the field.
+ **Innovation** - Products can be updated frequently as new features are developed, driving the innovation cycle. The updates can take effect quickly with minimum downtime compared to traditional update methods.
+ **Cost** - OTA updates can reduce maintenance costs significantly compared to methods traditionally used to update these devices.

Providing the OTA functionality requires the following design considerations:
+ **Secure Communication** - Updates must use encrypted communication channels to prevent the downloads from being tampered with during transit.
+ **Recovery** - Updates can fail due to things like intermittent network connectivity or receiving an invalid update. In these scenarios, the device needs to be able to return to a stable state and avoid becoming bricked.
+ **Author Verification** - Updates must be verified to be from a trusted source, along with other validations like checking the version and compatibility.

For more information about setting up OTA updates with FreeRTOS, see [FreeRTOS Over-the-Air Updates](freertos-ota-dev.md).

### AWS IoT Over the air (OTA) library
<a name="ota-update-library-intro-detail"></a>

The AWS IoT OTA library enables you to manage notifications of a newly available updates, download them, and perform cryptographic verification of firmware updates. Using the over-the-air (OTA) client library, you can logically separate the firmware update mechanisms from the application running on your device. The over-the-air (OTA) client library can share a network connection with the application, saving memory in resource-constrained devices. In addition, the over-the-air (OTA) client library lets you define application-specific logic for testing, committing, or rolling back a firmware update. The library supports different application protocols like Message Queuing Telemetry Transport (MQTT) and Hypertext Transfer Protocol (HTTP) and provides various configuration options you can fine tune for your network type and conditions.

This library's APIs provide these major functions:
+ Register for notifications or poll for new update requests that are available.
+ Receive, parse and validate the update request.
+ Download and verify the file according to the information in the update request.
+ Run a self-test before activating the received update to ensure the functional validity of the update.
+ Update the status of the device.

This library uses AWS services to manage various cloud related functions such as sending firmware updates, monitoring large numbers of devices across multiple regions, reducing the blast radius of faulty deployments, and verifying the security of updates. This library can be used with any MQTT or HTTP library. 

The demos for this library demonstrate complete over-the-air updates using the coreMQTT Library and AWS Services on a FreeRTOS device.

## Features
<a name="freertos-ota-features"></a>

Here is the complete OTA Agent interface:

**`[ OTA\$1Init](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#ae5cc1dcc13fbcb32230f552f48b24f03)`**  
Initializes the OTA engine by starting OTA Agent ("OTA Task") in the system. Only one OTA Agent may exist.

**`[ OTA\$1Shutdown](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#ac779291eb93f4e0e6459816e60e13b09)`**  
Signal to the OTA Agent to shut down. The OTA agent will optionally unsubscribe from all MQTT job notification topics, stop in progress OTA jobs, if any, and clear all resources.

**`[ OTA\$1GetState](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#a6db3f9cb417cb135cb0e68f5b5f2b11f)`**  
Gets the current state of the OTA Agent.

**`[ OTA\$1ActivateNewImage](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#a5169ba09148e7f5668a90e776e712f8b)`**  
Activates the newest microcontroller firmware image received through OTA. (The detailed job status should now be self-test.)

**`[ OTA\$1SetImageState](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#ab68cdf65934474e1f3d2cd1046314bea)`**  
Sets the validation state of the currently running microcontroller firmware image (testing, accepted or rejected).

**`[ OTA\$1GetImageState](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#a9c5b25f9a7eff3ded8cdf088c2011742)`**  
Gets the state of the currently running microcontroller firmware image (testing, accepted or rejected).

**`[ OTA\$1CheckForUpdate](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#a1178e8009eb05e6f55f6506b625c9fc2)`**  
Requests the next available OTA update from the OTA Update service.

**`[ OTA\$1Suspend](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#a65b61ae5dd477e8b2e6c88ea0473c62b)`**  
Suspend all OTA Agent operations.

**`[ OTA\$1Resume](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#ae9d40388ac87e4ac93288de37c98a138)`**  
Resume OTA Agent operations.

**`[ OTA\$1SignalEvent](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#a2564144f284db077b8947ba58a6a72bb)`**  
Signal an event to the OTA Agent task.

**`[ OTA\$1EventProcessingTask](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#ab3a0cfdc8694a606a1d736b2f54fb113)`**  
OTA agent event processing loop.

**`[ OTA\$1GetStatistics](https://docs.aws.amazon.com/freertos/latest/lib-ref/embedded-csdk/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#a63182243ef3c18d5f36cd427b83a1a22)`**  
Get the statistics of OTA message packets which includes the number of packets received, queued, processed and dropped.

**`[ OTA\$1Err\$1strerror](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#a6f72911b8fe80f27bce42c3a36dca4b3)`**  
Error code to string conversion for OTA errors.

**`[ OTA\$1JobParse\$1strerror ](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/aws/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_8c.html#a1d42efa1af7fa0ed92060a3b7e869648)`**  
Convert an OTA Job Parsing error code to a string.

**`[ OTA\$1PalStatus\$1strerror](https://aws.github.io/ota-for-aws-iot-embedded-sdk/v3.4.0/ota_8c.html#a5a58be1ac41b7d619eeeb4861be37c89)`**  
Status code to string conversion for OTA PAL status.

**`[ OTA\$1OsStatus\$1strerror](https://aws.github.io/ota-for-aws-iot-embedded-sdk/v3.4.0/ota_8c.html#a4951f4bb1bfbb7312850454ca2b282a4)`**  
Status code to string conversion for OTA OS status.

## API reference
<a name="freertos-ota-api"></a>

For more information, see the [AWS IoT Over-the-air Update: Functions](https://aws.github.io/ota-for-aws-iot-embedded-sdk/v3.4.0/ota_functions.html).

## Example usage
<a name="freertos-ota-example"></a>

A typical OTA-capable device application using the MQTT protocol drives the OTA Agent by using the following sequence of API calls.

1. Connect to the AWS IoT coreMQTT Agent. For more information, see [coreMQTT Agent library](coremqtt-agent.md).

1. Initialize the OTA Agent by calling `OTA_Init`, including the buffers, the required ota interfaces, the thing name and the application callback. The callback implements application-specific logic that executes after completing an OTA update job. 

1. When the OTA update is complete, FreeRTOS calls the job completion callback with one of the following events: `accepted`, `rejected`, or `self test`.

1. If the new firmware image has been rejected (for example, due to a validation error), the application can typically ignore the notification and wait for the next update.

1. If the update is valid and has been marked as accepted, call `OTA_ActivateNewImage` to reset the device and boot the new firmware image.

## Porting
<a name="freertos-ota-porting"></a>

For information about porting OTA functionality to your platform, see [Porting the OTA Library](https://docs.aws.amazon.com/freertos/latest/portingguide/afr-porting-ota.html) in the FreeRTOS Porting Guide.

## Memory use
<a name="ota-update-library-memory"></a>


****  

| Code Size of AWS IoT OTA (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| ota.c | 8.3K | 7.5K | 
| ota\$1interface.c | 0.1K | 0.1K | 
| ota\$1base64.c | 0.6K | 0.6K | 
| ota\$1mqtt.c | 2.4K | 2.2K | 
| ota\$1cbor.c | 0.8K | 0.6K | 
| ota\$1http.c | 0.3K | 0.3K | 
| Total estimates | 12.5K | 11.3K | 

# corePKCS11 library
<a name="security-pkcs"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Overview
<a name="freertos-pkcs-overview"></a>

The Public Key Cryptography Standard \$111 defines a platform-independent API to manage and use cryptographic tokens. [PKCS \$111](https://en.wikipedia.org/wiki/PKCS_11) refers to the API defined by the standard and to the standard itself. The PKCS \$111 cryptographic API abstracts key storage, get/set properties for cryptographic objects, and session semantics. It's widely used for manipulating common cryptographic objects, and it's important because the functions it specifies allow application software to use, create, modify, and delete cryptographic objects, without ever exposing those objects to the application's memory. For example, FreeRTOS AWS reference integrations use a small subset of the PKCS \$111 API to access the secret (private) key necessary to create a network connection that is authenticated and secured by the [Transport Layer Security (TLS)](https://en.wikipedia.org/wiki/Transport_Layer_Security) protocol without the application ever 'seeing' the key.

The corePKCS11 library contains a software-based mock implementation of the PKCS \$111 interface (API) that uses the cryptographic functionality provided by Mbed TLS. Using a software mock enables rapid development and flexibility, but it's expected that you will replace the mock with an implementation specific to the secure key storage used in your production devices. Generally, vendors for secure cryptoprocessors, such as Trusted Platform Module (TPM), Hardware Security Module (HSM), Secure Element, or any other type of secure hardware enclave, distribute a PKCS \$111 implementation with the hardware. The purpose of the corePKCS11 software only mock library is therefore to provide a non hardware specific PKCS \$111 implementation that allows for rapid prototyping and development before switching to a cryptoprocessor specific PKCS \$111 implementation in production devices.

Only a subset of the PKCS \$111 standard is implemented, with a focus on operations involving asymmetric keys, random number generation, and hashing. The targeted use cases include certificate and key management for TLS authentication, and code-sign signature verification, on small embedded devices. See the file `pkcs11.h` (obtained from OASIS, the standard body) in the FreeRTOS source code repository. In the [ FreeRTOS reference implementation](https://docs.aws.amazon.com/embedded-csdk/latest/lib-ref/libraries/standard/corePKCS11/docs/doxygen/output/html/index.html), PKCS \$111 API calls are made by the TLS helper interface in order to perform TLS client authentication during `SOCKETS_Connect`. PKCS \$111 API calls are also made by our one-time developer provisioning workflow to import a TLS client certificate and private key for authentication to the AWS IoT MQTT broker. Those two use cases, provisioning and TLS client authentication, require implementation of only a small subset of the PKCS \$111 interface standard.

## Features
<a name="freertos-pcks-features"></a>

The following subset of PKCS \$111 is used. This list is in roughly the order in which the routines are called in support of provisioning, TLS client authentication, and cleanup. For detailed descriptions of the functions, see the PKCS \$111 documentation provided by the standard committee.

### General setup and tear down API
<a name="pkcs-required-setup-teardown"></a>
+ `C_Initialize`
+ `C_Finalize`
+ `C_GetFunctionList`
+ `C_GetSlotList`
+ `C_GetTokenInfo`
+ `C_OpenSession`
+ `C_CloseSession`
+ `C_Login`

### Provisioning API
<a name="pkcs-required-provisioning"></a>
+ `C_CreateObject CKO_PRIVATE_KEY` (for device private key)
+ `C_CreateObject CKO_CERTIFICATE` (for device certificate and code verification certificate)
+ `C_GenerateKeyPair`
+ `C_DestroyObject`

### Client authentication
<a name="pkcs-required-client-auth"></a>
+ `C_GetAttributeValue`
+ `C_FindObjectsInit`
+ `C_FindObjects`
+ `C_FindObjectsFinal`
+ `C_GenerateRandom`
+ `C_SignInit`
+ `C_Sign`
+ `C_VerifyInit`
+ `C_Verify`
+ `C_DigestInit`
+ `C_DigestUpdate`
+ `C_DigestFinal`

## Asymmetric cryptosystem support
<a name="pkcs-asym-crypto"></a>

The FreeRTOS reference implementation uses PKCS \$111 2048-bit RSA (signing only) and ECDSA with the NIST P-256 curve. The following instructions describe how to create an AWS IoT thing based on a P-256 client certificate.

Make sure you are using the following (or more recent) versions of the AWS CLI and OpenSSL:

```
aws --version
aws-cli/1.11.176 Python/2.7.9 Windows/8 botocore/1.7.34

openssl version
OpenSSL 1.0.2g  1 Mar 2016
```

The following procedure assumes that you used the `aws configure` command to configure the AWS CLI. For more information, see [Quick configuration with `aws configure`](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config) in the *AWS Command Line Interface User Guide*.

**To create an AWS IoT thing based on a P-256 client certificate**

1. Create an AWS IoT thing.

   ```
   aws iot create-thing --thing-name thing-name
   ```

1. Use OpenSSL to create a P-256 key.

   ```
   openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -pkeyopt ec_param_enc:named_curve -outform PEM -out thing-name.key
   ```

1. Create a certificate enrollment request signed by the key created in step 2.

   ```
   openssl req -new -nodes -days 365 -key thing-name.key -out thing-name.req
   ```

1. Submit the certificate enrollment request to AWS IoT.

   ```
   aws iot create-certificate-from-csr  \
     --certificate-signing-request file://thing-name.req --set-as-active  \
     --certificate-pem-outfile thing-name.crt
   ```

1. Attach the certificate (referenced by the ARN output by the previous command) to the thing.

   ```
   aws iot attach-thing-principal --thing-name thing-name \
     --principal "arn:aws:iot:us-east-1:123456789012:cert/86e41339a6d1bbc67abf31faf455092cdebf8f21ffbc67c4d238d1326c7de729"
   ```

1. Create a policy. (This policy is too permissive. It should be used for development purposes only.)

   ```
   aws iot create-policy --policy-name FullControl --policy-document file://policy.json
   ```

   The following is a listing of the policy.json file specified in the `create-policy` command. You can omit the `greengrass:*` action if you don't want to run the FreeRTOS demo for Greengrass connectivity and discovery.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Action": "iot:*",
         "Resource": "*"
       },
       {
         "Effect": "Allow",
         "Action": "greengrass:*",
         "Resource": "*"
       }
     ]
   }
   ```

------

1. Attach the principal (certificate) and policy to the thing.

   ```
   aws iot attach-principal-policy --policy-name FullControl \
     --principal "arn:aws:iot:us-east-1:123456789012:cert/86e41339a6d1bbc67abf31faf455092cdebf8f21ffbc67c4d238d1326c7de729"
   ```

Now, follow the steps in the [AWS IoT Getting Started](https://docs.aws.amazon.com/iot/latest/developerguide/iot-gs.html) section of this guide. Don’t forget to copy the certificate and private key you created into your `aws_clientcredential_keys.h` file. Copy your thing name into `aws_clientcredential.h`.

**Note**  
The certificate and private key are hard-coded for demonstration purposes only. Production-level applications should store these files in a secure location.

## Porting
<a name="freertos-pkcs-porting"></a>

For information about porting the corePKCS11 library to your platform, see [Porting the corePKCS11 Library](https://docs.aws.amazon.com/freertos/latest/portingguide/afr-porting-pkcs.html) in the FreeRTOS Porting Guide.

## Memory use
<a name="freertos-pkcs-memory"></a>


****  

| Code Size of corePKCS11 (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| core\$1pkcs11.c | 0.8K | 0.8K | 
| core\$1pki\$1utils.c | 0.5K | 0.3K | 
| core\$1pkcs11\$1mbedtls.c | 8.9K | 7.5K | 
| Total estimates | 10.2K | 8.6K | 

# Secure Sockets library
<a name="secure-sockets"></a>

**Important**  <a name="deprecation-message-library"></a>
This library is hosted on the Amazon-FreeRTOS repository which is deprecated. We recommend that you [start here](freertos-getting-started-modular.md) when you create a new project. If you already have an existing FreeRTOS project based on the now deprecated Amazon-FreeRTOS repository, see the [Amazon-FreeRTOS Github Repository Migration Guide](github-repo-migration.md).

## Overview
<a name="freertos-secure-sockets-overview"></a>

You can use the FreeRTOS [Secure Sockets](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/secure_sockets/index.html) library to create embedded applications that communicate securely. The library is designed to make onboarding easy for software developers from various network programming backgrounds.

The FreeRTOS Secure Sockets library is based on the Berkeley sockets interface, with an additional secure communication option by TLS protocol. For information about the differences between the FreeRTOS Secure Sockets library and the Berkeley sockets interface, see `SOCKETS_SetSockOpt` in the [Secure Sockets API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/secure_sockets/index.html).

**Note**  
Currently, only client APIs, plus a [lightweight IP (lwIP)](https://savannah.nongnu.org/projects/lwip/) implementation of the server side `Bind` API, are supported for FreeRTOS Secure Sockets.

## Dependencies and requirements
<a name="freertos-secure-sockets-dependencies"></a>

The FreeRTOS Secure Sockets library depends on a TCP/IP stack and on a TLS implementation. Ports for FreeRTOS meet these dependencies in one of three ways:
+ A custom implementation of both TCP/IP and TLS
+ A custom implementation of TCP/IP, and the FreeRTOS TLS layer with [mbedTLS](https://en.wikipedia.org/wiki/Mbed_TLS)
+ [FreeRTOS\$1TCP](https://freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/index.html) and the FreeRTOS TLS layer with [mbedTLS](https://en.wikipedia.org/wiki/Mbed_TLS)

The dependency diagram below shows the reference implementation included with the FreeRTOS Secure Sockets library. This reference implementation supports TLS and TCP/IP over Ethernet and Wi-Fi with FreeRTOS\$1TCP and mbedTLS as dependencies. For more information about the FreeRTOS TLS layer, see [Transport Layer Security](security-tls.md).

![\[Secure Sockets Library architecture with FreeRTOS+TCP, TLS Layer, and TLS components.\]](http://docs.aws.amazon.com/freertos/latest/userguide/images/sockets-dependencies.png)


## Features
<a name="freertos-secure-sockets-features"></a>

FreeRTOS Secure Sockets library features include:
+ A standard, Berkeley Sockets-based interface
+ Thread-safe APIs for sending and receiving data
+ Easy-to-enable TLS

## Troubleshooting
<a name="freertos-secure-sockets-troubleshooting"></a>

### Error codes
<a name="w2aac31b9c13c45c15b5"></a>

The error codes that the FreeRTOS Secure Sockets library returns are negative values. For more information about each error code, see Secure Sockets Error Codes in the [Secure Sockets API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/secure_sockets/index.html).

**Note**  
If the FreeRTOS Secure Sockets API returns an error code, the [coreMQTT library](coremqtt.md), which depends on the FreeRTOS Secure Sockets library, returns the error code `AWS_IOT_MQTT_SEND_ERROR`.

## Developer support
<a name="freertos-secure-sockets-support"></a>

The FreeRTOS Secure Sockets library includes two helper macros for handling IP addresses:

**`SOCKETS_inet_addr_quick`**  
This macro converts an IP address that is expressed as four separate numeric octets into an IP address that is expressed as a 32-bit number in network-byte order.

**`SOCKETS_inet_ntoa`**  
This macro converts an IP address that is expressed as a 32-bit number in network byte order to a string in decimal-dot notation.

## Usage restrictions
<a name="freertos-secure-sockets-restrictions"></a>

Only TCP sockets are supported by the FreeRTOS Secure Sockets library. UDP sockets are not supported.

Server APIs are not supported by the FreeRTOS Secure Sockets library, except for a [lightweight IP (lwIP)](https://savannah.nongnu.org/projects/lwip/) implementation of the server side `Bind` API. Client APIs are supported.

## Initialization
<a name="freertos-secure-sockets-initialization"></a>

To use the FreeRTOS Secure Sockets library, you need to initialize the library and its dependencies. To initialize the Secure Sockets library, use the following code in your application:

```
BaseType_t xResult = pdPASS;
xResult = SOCKETS_Init();
```

Dependent libraries must be initialized separately. For example, if FreeRTOS\$1TCP is a dependency, you need to invoke [https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/API/FreeRTOS_IPInit.html](https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/API/FreeRTOS_IPInit.html) in your application as well.

## API reference
<a name="freertos-secure-sockets-api"></a>

For a full API reference, see [ Secure Sockets API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/secure_sockets/index.html).

## Example usage
<a name="freertos-secure-sockets-example"></a>

The following code connects a client to a server.

```
#include "aws_secure_sockets.h"

#define configSERVER_ADDR0                     127
#define configSERVER_ADDR1                     0
#define configSERVER_ADDR2                     0
#define configSERVER_ADDR3                     1
#define configCLIENT_PORT                      443

/* Rx and Tx timeouts are used to ensure the sockets do not wait too long for
 * missing data. */
static const TickType_t xReceiveTimeOut = pdMS_TO_TICKS( 2000 );
static const TickType_t xSendTimeOut = pdMS_TO_TICKS( 2000 );

/* PEM-encoded server certificate */
/* The certificate used below is one of the Amazon Root CAs.\
Change this to the certificate of your choice. */
static const char cTlsECHO_SERVER_CERTIFICATE_PEM[] =
"-----BEGIN CERTIFICATE-----\n"
"MIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5\n"
"MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g\n"
"Um9vdCBDQSAzMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG\n"
"A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg\n"
"Q0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZBf8ANm+gBG1bG8lKl\n"
"ui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjrZt6j\n"
"QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSr\n"
"ttvXBp43rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkr\n"
"BqWTrBqYaGFy+uGh0PsceGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteM\n"
"YyRIHN8wfdVoOw==\n"
"-----END CERTIFICATE-----\n";

static const uint32_t ulTlsECHO_SERVER_CERTIFICATE_LENGTH = sizeof( cTlsECHO_SERVER_CERTIFICATE_PEM );

void vConnectToServerWithSecureSocket( void )
{
    Socket_t xSocket;
    SocketsSockaddr_t xEchoServerAddress;
    BaseType_t xTransmitted, lStringLength;

    xEchoServerAddress.usPort = SOCKETS_htons( configCLIENT_PORT );
    xEchoServerAddress.ulAddress = SOCKETS_inet_addr_quick( configSERVER_ADDR0,
                                                            configSERVER_ADDR1,
                                                            configSERVER_ADDR2,
                                                            configSERVER_ADDR3 );
                                                            
    /* Create a TCP socket. */
    xSocket = SOCKETS_Socket( SOCKETS_AF_INET, SOCKETS_SOCK_STREAM, SOCKETS_IPPROTO_TCP );
    configASSERT( xSocket != SOCKETS_INVALID_SOCKET );
    
    /* Set a timeout so a missing reply does not cause the task to block indefinitely. */
    SOCKETS_SetSockOpt( xSocket, 0, SOCKETS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) );
    SOCKETS_SetSockOpt( xSocket, 0, SOCKETS_SO_SNDTIMEO, &xSendTimeOut, sizeof( xSendTimeOut ) );

    /* Set the socket to use TLS. */
    SOCKETS_SetSockOpt( xSocket, 0, SOCKETS_SO_REQUIRE_TLS, NULL, ( size_t ) 0 );
    SOCKETS_SetSockOpt( xSocket, 0, SOCKETS_SO_TRUSTED_SERVER_CERTIFICATE, cTlsECHO_SERVER_CERTIFICATE_PEM, ulTlsECHO_SERVER_CERTIFICATE_LENGTH );

    if( SOCKETS_Connect( xSocket, &xEchoServerAddress, sizeof( xEchoServerAddress ) ) == 0 )
    {
        /* Send the string to the socket. */
        xTransmitted = SOCKETS_Send( xSocket,                         /* The socket receiving. */
                                     ( void * )"some message",        /* The data being sent. */
                                     12,                              /* The length of the data being sent. */
                                     0 );                             /* No flags. */

        if( xTransmitted < 0 )
        {
            /* Error while sending data */
            return;
        }

        SOCKETS_Shutdown( xSocket, SOCKETS_SHUT_RDWR );
    }
    else
    {
        //failed to connect to server
    }

    SOCKETS_Close( xSocket );
}
```

For a full example, see the [Secure Sockets echo client demo](secure-sockets-demo.md).

## Porting
<a name="freertos-secure-sockets-porting"></a>

FreeRTOS Secure Sockets depends on a TCP/IP stack and on a TLS implementation. Depending on your stack, to port the Secure Sockets library, you might need to port some of the following:
+ The [FreeRTOS\$1TCP](https://freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/index.html) TCP/IP stack
+ The [corePKCS11 library](security-pkcs.md)
+ The [Transport Layer Security](security-tls.md)

For more information about porting, see [Porting the Secure Sockets Library](https://docs.aws.amazon.com/freertos/latest/portingguide/afr-porting-ss.html) in the FreeRTOS Porting Guide.

# AWS IoT Device Shadow library
<a name="freertos-lib-cloud-shadows"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Introduction
<a name="freertos-shadow-introduction"></a>

You can use the AWS IoT Device Shadow library to store and retrieve the current state (the *shadow*) of every registered device. The device's shadow is a persistent, virtual representation of your device that you can interact with in your web applications even if the device is offline. The device state is captured as its shadow in a [JSON](https://www.json.org/) document. You can send commands to the AWS IoT Device Shadow service over MQTT or HTTP to query the latest known device state, or to change the state. Each device's shadow is uniquely identified by the name of the corresponding *thing*, a representation of a specific device or logical entity on the AWS Cloud. For more information, see [ Managing Devices with AWS IoT](https://docs.aws.amazon.com/iot/latest/developerguide/iot-thing-management.html). More details about shadows can be found in [AWS IoT documentation](https://docs.aws.amazon.com/iot/latest/developerguide/iot-device-shadows.html). 

The AWS IoT Device Shadow library has no dependencies on additional libraries other than the standard C library. It also doesn't have any platform dependencies, such as threading or synchronization. It can be used with any MQTT library and any JSON library. 

This library can be freely used and is distributed under the [MIT open source license](https://freertos.org/a00114.html).


****  

| Code Size of AWS IoT Device Shadow (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| shadow.c | 1.2K | 0.9K | 
| Total estimates | 1.2K | 0.9K | 

# AWS IoT Jobs library
<a name="freertos-lib-jobs"></a>

**Note**  <a name="out-of-date-message"></a>
The content on this page may not be up-to-date. Please refer to the [FreeRTOS.org library page](https://www.freertos.org/Documentation/03-Libraries/01-Library-overview/01-All-libraries) for the latest update.

## Introduction
<a name="freertos-lib-jobs-introduction"></a>

AWS IoT Jobs is a service that notifies one or more connected devices of a pending *job*. You can use a job to manage your fleet of devices, update firmware and security certificates on your devices, or perform administrative tasks such as restarting devices and performing diagnostics. For more information, see [Jobs](https://docs.aws.amazon.com/iot/latest/developerguide/iot-jobs.html) in the *AWS IoT Developer Guide*. Interactions with the AWS IoT Jobs service use [MQTT](https://freertos.org/mqtt/index.html), a lightweight publish-subscribe protocol. This library provides an API to compose and recognize the MQTT topic strings used by the AWS IoT Jobs service.

The AWS IoT Jobs library is written in C and designed to be compliant with [ISO C90](https://en.wikipedia.org/wiki/ANSI_C#C90) and [MISRA C:2012](https://misra.org.uk/product/misra-c2012-third-edition-first-revision/). The library has no dependencies on any additional libraries other than the standard C library. It can be used with any MQTT library and any JSON library. The library has [proofs](https://www.cprover.org/cbmc/) showing safe memory use and no heap allocation, making it suitable for IoT microcontrollers, but also fully portable to other platforms.

This library can be freely used and is distributed under the [MIT open source license](https://freertos.org/a00114.html).


****  

| Code Size of AWS IoT Jobs (example generated with GCC for ARM Cortex-M) | File | With -O1 Optimization | With -Os Optimization | 
| --- | --- | --- | --- | 
| jobs.c | 1.9K | 1.6K | 
| Total estimates | 1.9K | 1.6K | 

# Transport Layer Security
<a name="security-tls"></a>

**Important**  <a name="deprecation-message-library"></a>
This library is hosted on the Amazon-FreeRTOS repository which is deprecated. We recommend that you [start here](freertos-getting-started-modular.md) when you create a new project. If you already have an existing FreeRTOS project based on the now deprecated Amazon-FreeRTOS repository, see the [Amazon-FreeRTOS Github Repository Migration Guide](github-repo-migration.md).

The FreeRTOS Transport Layer Security (TLS) interface is a thin, optional wrapper used to abstract cryptographic implementation details away from the [Secure Sockets Layer](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/secure_sockets/index.html) (SSL) interface above it in the protocol stack. The purpose of the TLS interface is to make the current software crypto library, mbed TLS, easy to replace with an alternative implementation for TLS protocol negotiation and cryptographic primitives. The TLS interface can be swapped out without any changes required to the SSL interface. See `iot_tls.h` in the FreeRTOS source code repository.

The TLS interface is optional because you can choose to interface directly from SSL into a crypto library. The interface is not used for MCU solutions that include a full-stack offload implementation of TLS and network transport.

For more information about porting the TLS interface, see [Porting the TLS Library](https://docs.aws.amazon.com/freertos/latest/portingguide/afr-porting-tls.html) in the *FreeRTOS Porting Guide*.

# Wi-Fi library
<a name="freertos-wifi"></a>

**Important**  <a name="deprecation-message-library"></a>
This library is hosted on the Amazon-FreeRTOS repository which is deprecated. We recommend that you [start here](freertos-getting-started-modular.md) when you create a new project. If you already have an existing FreeRTOS project based on the now deprecated Amazon-FreeRTOS repository, see the [Amazon-FreeRTOS Github Repository Migration Guide](github-repo-migration.md).

## Overview
<a name="freertos-wifi-overview"></a>

The FreeRTOS [Wi-Fi](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/wifi/index.html) library abstracts port-specific Wi-Fi implementations into a common API that simplifies application development and porting for all FreeRTOS-qualified boards with Wi-Fi capabilities. Using this common API, applications can communicate with their lower-level wireless stack through a common interface.

## Dependencies and requirements
<a name="freertos-wifi-dependencies"></a>

The FreeRTOS Wi-Fi library requires the [FreeRTOS\$1TCP](https://freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/index.html) core.

## Features
<a name="freertos-wifi-features"></a>

The Wi-Fi library includes the following features:
+ Support for WEP, WPA, WPA2, and WPA3 authentication
+ Access Point Scanning
+ Power management
+ Network profiling

For more information about the features of the Wi-Fi library, see below.

### Wi-Fi modes
<a name="freertos-wifi-setup"></a>

Wi-Fi devices can be in one of three modes: Station, Access Point, or P2P. You can get the current mode of a Wi-Fi device by calling `WIFI_GetMode`. You can set a device's wi-fi mode by calling `WIFI_SetMode`. Switching modes by calling `WIFI_SetMode` disconnects the device, if it is already connected to a network.

**Station mode**  
Set your device to Station mode to connect the board to an existing access point.

**Access Point (AP) mode**  
Set your device to AP mode to make the device an access point for other devices to connect to. When your device is in AP mode, you can connect another device to your FreeRTOS device and configure the new Wi-Fi credentials. To configure AP mode, call `WIFI_ConfigureAP`. To put your device into AP mode, call `WIFI_StartAP`. To turn off AP mode, call `WIFI_StopAP`.  
FreeRTOS libraries do not provide Wi-Fi provisioning in AP mode. You must supply the additional functionality, including DHCP and HTTP server capabilities, to achieve full support of AP mode.

**P2P mode**  
Set your device to P2P mode to allow multiple devices to connect to each other directly, without an access point.

### Security
<a name="freertos-wifi-security"></a>

The Wi-Fi API supports WEP, WPA, WPA2, and WPA3 security types. When a device is in Station mode, you must specify the network security type when calling the `WIFI_ConnectAP` function. When a device is in AP mode, the device can be configured to use any of the supported security types:
+ `eWiFiSecurityOpen`
+ `eWiFiSecurityWEP`
+ `eWiFiSecurityWPA`
+ `eWiFiSecurityWPA2`
+ `eWiFiSecurityWPA3`

### Scanning and connecting
<a name="freertos-wifi-connection"></a>

To scan for nearby access points, set your device to Station mode, and call the `WIFI_Scan` function. If you find a desired network in the scan, you can connect to the network by calling `WIFI_ConnectAP` and providing the network credentials. You can disconnect a Wi-Fi device from the network by calling `WIFI_Disconnect`. For more information about scanning and connecting, see [Example usage](#freertos-wifi-example) and [API reference](#freertos-wifi-api).

### Power management
<a name="freertos-wifi-power-management"></a>

Different Wi-Fi devices have different power requirements, depending on the application and available power sources. A device might always be powered on to reduce latency or it might be intermittently connected and switch into a low power mode when Wi-Fi is not required. The interface API supports various power management modes like always on, low power, and normal mode. You set the power mode for a device using the `WIFI_SetPMMode` function. You can get the current power mode of a device by calling the `WIFI_GetPMMode` function.

### Network profiles
<a name="freertos-wifi-profiles"></a>

The Wi-Fi library enables you to save network profiles in the non-volatile memory of your devices. This allows you to save network settings so they can be retrieved when a device reconnects to a Wi-Fi network, removing the need to provision devices again after they have been connected to a network. `WIFI_NetworkAdd` adds a network profile. `WIFI_NetworkGet` retrieves a network profile. `WIFI_NetworkDel` deletes a network profile. The number of profiles you can save depends on the platform.

## Configuration
<a name="freertos-wifi-config"></a>

To use the Wi-Fi library, you need to define several identifiers in a configuration file. For information about these identifiers, see the [API reference](#freertos-wifi-api).

**Note**  
The library does not include the required configuration file. You must create one. When creating your configuration file, be sure to include any board-specific configuration identifiers that your board requires.

## Initialization
<a name="freertos-wifi-init"></a>

Before you use the Wi-Fi library, you need to initialize some board-specific components, in addition to the FreeRTOS components. Using the `vendors/vendor/boards/board/aws_demos/application_code/main.c` file as a template for initialization, do the following:

1. Remove the sample Wi-Fi connection logic in `main.c` if your application handles Wi-Fi connections. Replace the following `DEMO_RUNNER_RunDemos()` function call:

   ```
   if( SYSTEM_Init() == pdPASS )
       {
       ...
           DEMO_RUNNER_RunDemos();
       ...
           }
   ```

   With a call to your own application:

   ```
   if( SYSTEM_Init() == pdPASS )
       {
       ...
           // This function should create any tasks
           // that your application requires to run.
           YOUR_APP_FUNCTION();
       ...
           }
   ```

1. Call `WIFI_On()` to initialize and power on your Wi-Fi chip.
**Note**  
Some boards might require additional hardware initialization.

1. Pass a configured `WIFINetworkParams_t` structure to `WIFI_ConnectAP()` to connect your board to an available Wi-Fi network. For more information about the `WIFINetworkParams_t` structure, see [Example usage](#freertos-wifi-example) and [API reference](#freertos-wifi-api).

## API reference
<a name="freertos-wifi-api"></a>

For a full API reference, see [Wi-Fi API Reference](https://docs.aws.amazon.com/freertos/latest/lib-ref/html2/wifi/index.html).

## Example usage
<a name="freertos-wifi-example"></a>

### Connecting to a known AP
<a name="w2aac31b9c13c53c21b3"></a>

```
#define clientcredentialWIFI_SSID    "MyNetwork"
#define clientcredentialWIFI_PASSWORD   "hunter2"

WIFINetworkParams_t xNetworkParams;
WIFIReturnCode_t xWifiStatus;

xWifiStatus = WIFI_On(); // Turn on Wi-Fi module

// Check that Wi-Fi initialization was successful
if( xWifiStatus == eWiFiSuccess )
{
    configPRINT( ( "WiFi library initialized.\n") );
}
else
{
    configPRINT( ( "WiFi library failed to initialize.\n" ) );
    // Handle module init failure
}

/* Setup parameters. */
xNetworkParams.pcSSID = clientcredentialWIFI_SSID;
xNetworkParams.ucSSIDLength = sizeof( clientcredentialWIFI_SSID );
xNetworkParams.pcPassword = clientcredentialWIFI_PASSWORD;
xNetworkParams.ucPasswordLength = sizeof( clientcredentialWIFI_PASSWORD );
xNetworkParams.xSecurity = eWiFiSecurityWPA2;

// Connect!
xWifiStatus = WIFI_ConnectAP( &( xNetworkParams ) );

if( xWifiStatus == eWiFiSuccess )
{
    configPRINT( ( "WiFi Connected to AP.\n" ) );
    // IP Stack will receive a network-up event on success
}
else
{
    configPRINT( ( "WiFi failed to connect to AP.\n" ) );
    // Handle connection failure
}
```

### Scanning for nearby APs
<a name="w2aac31b9c13c53c21b5"></a>

```
WIFINetworkParams_t xNetworkParams;
WIFIReturnCode_t xWifiStatus;

configPRINT( ("Turning on wifi...\n") );
xWifiStatus = WIFI_On();

configPRINT( ("Checking status...\n") );
if( xWifiStatus == eWiFiSuccess )
{
    configPRINT( ("WiFi module initialized.\n") );
}
else
{
    configPRINTF( ("WiFi module failed to initialize.\n" ) );
    // Handle module init failure
}

WIFI_SetMode(eWiFiModeStation);

/* Some boards might require additional initialization steps to use the Wi-Fi library. */

while (1)
{
    configPRINT( ("Starting scan\n") );
    const uint8_t ucNumNetworks = 12; //Get 12 scan results
    WIFIScanResult_t xScanResults[ ucNumNetworks ];
    xWifiStatus = WIFI_Scan( xScanResults, ucNumNetworks ); // Initiate scan

    configPRINT( ("Scan started\n") );

    // For each scan result, print out the SSID and RSSI
    if ( xWifiStatus == eWiFiSuccess )
    {
        configPRINT( ("Scan success\n") );
        for ( uint8_t i=0; i<ucNumNetworks; i++ ) 
        {
            configPRINTF( ("%s : %d \n", xScanResults[i].cSSID, xScanResults[i].cRSSI) );
        }
    } else {
        configPRINTF( ("Scan failed, status code: %d\n", (int)xWifiStatus) );
    }
    
    vTaskDelay(200);
}
```

## Porting
<a name="freertos-wifi-porting"></a>

The `iot_wifi.c` implementation needs to implement the functions defined in `iot_wifi.h`. At the very least, the implementation needs to return `eWiFiNotSupported` for any non-essential or unsupported functions.

For more information about porting the Wi-Fi library, see [Porting the Wi-Fi Library](https://docs.aws.amazon.com/freertos/latest/portingguide/afr-porting-wifi.html) in the FreeRTOS Porting Guide.