Introduction
==================================
This workshop demonstrates how to use the SimpleLink™ Wi-Fi® Over-The-Air (OTA) library.
The library can be used to wirelessly load and install software updates from a cloud server.
A software update may contain any combination of application code, firmware, and user files.
At the end of this training, the audience should be able to:
* Understand the OTA process and the SimpleLink Wi-Fi solution
* Configure, build, and execute the SimpleLink `cloud_ota` application and OTA library (`ota`) on the CC3220 LaunchPad
* Create an OTA update image and upload it to a CDN (Content Delivery Network) Server
Prerequisites
=============
Completed material
------------------
* [Wi-Fi Provisioning: Connecting SimpleLink Wi-Fi Technology to a Network](http://dev.ti.com/tirex/#/?link=Software%2FSimpleLink%20CC3220%20SDK%2FSimpleLink%20Academy%2FWi-Fi%2FWi-Fi%20Provisioning)
Software
---------
* [Code Composer Studio](http://www.ti.com/tool/ccstudio) v8.0 or later
* SimpleLink Wi-Fi CC32xx Wireless MCUs support installed
* Make sure that CCS is using the latest updates: **Help → Check for Updates**
* [CC3220 SDK v2.20.00.10](http://www.ti.com/tool/simplelink-cc3220-sdk) or later
* [UniFlash](http://www.ti.com/tool/UNIFLASH) v4.3.1.1835 or later.
* Terminal emulator program such as TeraTerm or PuTTY
Hardware
---------
* 1x CC3220R LaunchPad
* 1x Micro-USB cable (included with LaunchPad/BoosterPack)
* 802.11b/g/n (2.4-GHz) Wireless Access Point (AP)
* Smart device with [Wi-Fi Starter Pro Mobile Application](http://www.ti.com/tool/wifistarterpro)
OTA Overview
==================================
OTA Concept
---------------------------------
* OTA (Over-The-Air) update is an efficient way of wirelessly distributing firmware updates or application upgrades.
* An OTA Update mechanism enables users to easily and securely update the software on their device using Wi-Fi. This involves two simple procedures:
* A vendor stores an OTA update on a CDN (Content Delivery Network) server.
* The endpoint devices with an OTA-enabled application load and install the new update.
* An OTA-enabled application must support all of the following actions:
* Polling the CDN (Content Delivery Network) server for new updates
* Downloading the new image
* Installing the image on the flash file system in a secured and fail-safe manner (the new image becomes a "candidate")
* Committing the image after it is validated (making it "operational")
* The SimpleLink OTA library offloads the above OTA actions and provides a simple API for the application.
OTA System Diagram
---------------------------------
{{b>
**API**: Application Program Interface
**CDN**: Content Delivery Network
**MCU**: Microcontroller Unit
**NWP**: Network Processor
**OTA**: Over The Air
**PCB**: Printed Circuit Board
}}
* **CDN (Content Delivery Network)**: Globally distributed network of proxy servers deployed in multiple data centers. The goal of a CDN is to serve content to end-users with high availability and high performance. Examples would be Dropbox or GitHub.
* **OTA library**: Offloads the OTA actions (such as polling the server, downloading the updates and installing them in the local flash) while exposing a simple API.
* **OTA-enabled Application**: Triggers the OTA library and respond to OTA events. The application will take decisions whether to accept or decline an update (usually based on timestamp) and whether to commit or rollback the already installed image (based on a sanity check).

SimpleLink OTA Library (`ota`)
---------------------------------
* The OTA library implements a simple HTTP client that connects to CDN server (through `CdnVendor` and `OtaHttpClient` modules).
* The HTTP client can be configured as:
* Non Secured (connects to CDN running HTTP Server)
* Secured (HTTPS server) using server authentication (by default)
* Domain Name verification (default) or without server authentication.
* The OTA library supports the following cloud CDN vendors:
* Github (demonstrated in the first demo)
* Dropbox (demonstrated in the second demo)
* Custom
* The library defines a structure for the OTA image in a tar file. The UniFlash ImageCreator tool can be used to create an OTA tar file so that the OTA library will be able to parse the loaded content and install it on local flash file system in secure and fail-safe manner (through the `OtaArchive` and `OtaJson` modules)
* The OTA library is provided as a static library project with full source code to enable user customizations.

OTA Library API
---------------------------------
The OTA library exposes very simple API set:
* `OTA_init()`: Initializes the OTA library. The host application should define a global buffer for the use of the OTA library and provide this buffer while it initiates the OTA.
* `OTA_set()`: Sets an OTA library parameter. Used to set CDN Server information and to update the status of the loaded image (`DECLINE`, `ACCEPT`, `COMMIT` or `ROLLBACK`).
* `OTA_get()`: Retrieves an OTA library parameters, e.g. `IS_ACTIVE` or `VERSIONS` info (current image version and new update version).
* `OTA_run()`: Trigger the OTA library state machine. This will trigger OTA polling, download, etc. It should be called repeatedly until it gets the `DOWNLOAD_DONE` return code.
This API set is compatible with both non-OS and OS-based platforms.
OTA Sample Application
---------------------------------
* The first role of an OTA-enabled application is to verify and commit a "candidate" image that was previously installed to local flash.
* Once the device is connected to the network and can successfully PING to the local gateway, the application assumes the image is okay.
* If the OTA state is `PENDING_COMMIT`, the application will commit the image.
* The second role of the application is to look for a new update.
* Server info is defined in compile time (in `otauser.h`).
* App repeatedly calls `OtaRun()` until OTA process is completed.
* App decides to accept or decline a new update based on its timestamp.
* An accepted update will be written to flash as a "candidate" which will be verified after the MCU gets reset.

Task 1: Preparing the OTA application
==================================
1. In CCS, import the `cloud_ota_CC3220S_LAUNCHXL_tirtos_ccs` example (`simplelink_cc32xx_sdk_x_xx_xx_xx/examples/rtos/CC3220S_LAUNCHXL/demos/cloud_ota/tirtos/ccs`).
2. You also must import the `ota` project found in `simplelink_cc32xx_sdk_x_xx_xx_xx/source/ti/net/ota/ccs`. This is the supporting OTA library. Be sure to uncheck **Copy projects into workspace**.

[[r! Warning icons for `CdnVendors` files
If you do not uncheck **Copy projects into workspace** when you import the `ota` library, you will see yellow warning icons in the `OTA/CdnVendors/` folder of your `ota` project. Update the file paths and link to the location of your `ota` library binary.
[[+y How do I update file paths and link to libraries?
1. Update the path for each of the `CdnVendors` files.
* In your `ota` project, open the properties (**Left click → Properties**) and navigate under **Resource** to **Linked Resources** and the **Linked Resources** tab.
* For each file with an invalid location, select the file and press the **Edit** button to replace the `PROJECT_LOC` project variable with `ORIGINAL_PROJECT_ROOT`.
* Be sure to press **OK** to save your changes. The warning symbol next to each file should disappear and you will be able to compile the library.

2. Link your `cloud_ota` application to the location where your `ota` library binary will be built (instead of it residing in the SDK). In the `cloud_ota` project, go to **Properties → Build → ARM Linker → File Search Path → Include library file...** and change the `ota.a` reference to `${WORKSPACE_LOC}/ota/Release/ota.a`. This will link to the OTA library built in your CCS workspace.

[[+y]]
3. If you are using a CC3220R LaunchPad or board, you will need to change the device variant for the CC3220S cloud_ota project. In **Properties → General**, select **CC3220** and make sure that "Manage the project's target-configuration automatically" is checked.

4. Update the JSON buffer size for storing the long server URL. In the `ota` project, open the `OtaJson.c` file and update the `MAX_METADATA_FILENAME` definition to reserve room for the long URL name. For this demo, we are using DropBox.

Task 2: Creating and Configuring the CDN server
==================================
1. You will need a CDN account to store the new OTA file, and we will be using [DropBox](http://dropbox.com) for this demo. Open the DropBox Developers tab from the main page or go to [dropbox.com/developers](http://dropbox.com/developers) and select **Create your app**.

2. Choose a **Dropbox API** with **App folder** access. You can choose any app name.

3. Generate an access token and save it.

4. Navigate to your Dropbox files **home → Apps → your newly created apps folder**. In this folder, create a directory **OTA_R2_MCU_FLASH**. This is where we will place the OTA bundle later.

5. In `ota/otauser.h`, update the CDN server parameter.
* Use the following CDN server parameters:
* `#define OTA_SERVER_TYPE` `OTA_SERVER_DROPBOX_V2`
* `#define OTA_VENDOR_DIR` `"OTA_R2_MCU_FLASH"`
* Add the access token we generated. The following is defined under the `DROPBOX` section:
* `#define OTA_VENDOR_TOKEN` `""`
* Note `OTA_SERVER_ROOT_CA_CERT`. This is the certificate name that we will find in task 3. You can leave this define alone for now.

[[b! Using a custom CDN Server
The `cloud_ota` demo supports Github and Dropbox. A custom vendor can also be used by defining `OTA_SERVER_TYPE` in `ota/otauser.h` as `OTA_SERVER_CUSTOM`.
For more information, please see the [OTA Application Report](http://www.ti.com/lit/swra510).
]]
Task 3: Finding a Root Certificate
==================================
1. In this step, we will find the Certificate Common Name necessary to pass Dropbox's SSL authentication. We will install this certificate (in DER format) as a user file in the device flash. To find the most up-to-date Root CA certificate, add the following code in the `else-if` statement of `SimpleLinkSockEventHandler` in `cloud_ota.c`.
```c
switch (pSock->SocketAsyncEvent.SockAsyncData.Type)
{
case SL_SSL_NOTIFICATION_WRONG_ROOT_CA:
/* on socket error Restart OTA */
UART_PRINT("SL_SOCKET_ASYNC_EVENT: ERROR - WRONG ROOT CA\n\r");
UART_PRINT("Please install the following Root Certificate:\n\r");
UART_PRINT(" %s\n\r", pSock->SocketAsyncEvent.SockAsyncData.pExtraInfo);
SignalEvent(APP_EVENT_RESTART);
break;
default:
/* on socket error Restart OTA */
UART_PRINT("SL_SOCKET_ASYNC_EVENT socket event %d, do restart\n\r", pSock->Event);
SignalEvent(APP_EVENT_RESTART);
break;
}
``` **cloud_ota.c :: SimpleLinkSockEventHandler()** - Else-if statement
It should now look like this:

[[r! Error code -688
In the case you do not have the correct CA certificate (or use a different CDN server), the HTTPS connection setup will fail. If the HTTPS connection to the CDN server fails due to an incorrect root certificate, the return value will be -688. You will need to find and install the right certificate.
]]
2. Open a terminal emulation program and select the XDS110 Class Application/User UART port.
{{y **UART Configuration**
Baud rate: 115200
Data: 8 bit
Parity: None
Stop: 1 bit
Flow control: None}}
3. Rebuild the `ota` project **then** rebuild the `cloud_ota` project. Run the `cloud_ota` application using the CCS Debugger. The example begins by starting the device in station mode and looking for an available network.
The screen capture demonstrates the case that a device cannot find a known access-point and enters the provisioning mode. You will need the `dummy_root_ca_cert_key` flashed to the CC3220 as a user file in order to complete the default provisioning demo. For more information on provisioning, see the [Wi-Fi Provisioning](http://dev.ti.com/tirex/#/?link=Software%2FSimpleLink%20CC3220%20SDK%2FSimpleLink%20Academy%2FWi-Fi%2FWi-Fi%20Provisioning) training.

[[y! Issues with CCS Debugger
Your device will need to be in Development mode to use the CCS debugger. For more details on this, see the [CC3220 Getting Started Guide](http://www.ti.com/lit/swru461).
]]
[[y! Rebuilding the OTA library
You will need to rebuild the `ota` library and `cloud_ota` example after every change to `otauser.h`.
]]
4. The screenshot below shows a successful AP connection, followed by successful PING sessions. Now you can press button 3 (SW3) on the board to trigger the OTA process.
Note that the following log was taken after `SL_ENABLE_OTA_DEBUG_TRACES` was enabled (in `ota/ota_user.h`) so it includes extra OTA messages.

5. When the LaunchPad attempts the OTA process, you will see an error message similar to the following screenshot. Make note of the complete name printed after `Please install the following Root CA Certificate:`.

6. You can search this certificate name online and download it, or you can find it using your browser's settings. For example in Chrome, go to **Settings → Advanced → Privacy and security → Manage Certificates → Trusted Root Certification Authorities**. If your browser has navigated to github.com before, search in the list for the certificate name we printed to the terminal earlier. Export it in DER format.
7. Set this certificate name as the `OTA_SERVER_ROOT_CA_CERT` define in `ota/otauser.h` that we left blank in task 2 and rebuild the `ota` project.
Task 4: Compiling and Creating the OTA Image
==================================
This task focuses on the generation of an OTA image. The image will contain an updated MCU application which will be based on the `cloud_ota` application.
1. In `cloud_ota.h`, update the `APPLICATION_NAME` definition to `"OTA APP (EX-2 Image)"` as shown below and rebuild the project. We will only change the application name (the name will help us differentiate between the current app and the updated one).

2. Create a new CC3220R UniFlash ImageCreator project.

3. Add the latest servicepack and your newly compiled binary (`cloud_ota_CC3220S_LAUNCHXL_tirtos_ccs.bin`) as a MCU image. You can find this binary in your workspace (`/cloud_ota_CC3220S_LAUNCHXL_tirtos_ccs/Debug/`)
[[y! Rebuild your project
Be sure that you have rebuilt the `ota` project and then the `cloud_ota` project before completing this step.
]]

4. Switch to the **Advanced** view on the left side and navigate to **User Files**. Add the server root certificate in DER format that we found in task 3. You should also add the `dummy_root_ca_cert_key` which is used during provisioning. Then select **Burn**.

5. Select **Create OTA** and **Skip Security** to create the OTA image tar file. The CC3220R does not have the cryptographic utilities required for this secure feature. For more information on this feature, please

The tool will generate a tar file in a format defined by the OTA library. The timestamp for the image will be automatically generated as well.
Task 5: Running the OTA Application
==================================
1. Change the OTA version (`APPLICATION_NAME` in `cloud_ota.h`) back to `OTA APP` (see task 4, step 1). Rebuild the project.
2. Add this new MCU image to the UniFlash ImageCreator project and program the image to the LaunchPad.
3. Open a terminal emulation program such as TeraTerm and select the XDS110 Class Application/User UART port.
{{y **UART Configuration**
Baud rate: 115200
Data: 8 bit
Parity: None
Stop: 1 bit
Flow control: None}}
4. The capture below shows the successful completion of the OTA process. Note that the screenshot below skipped most of the OTA messages (dealing with CDN server connection, downloading content, parsing and installing it). This log below shows the flash programming messages, the platform reset, and the activation of the newly programmed image. After the first successful ping session, the temporary image gets committed.
* The OTA tar file name contains the timestamp (date and hour) of its creation. Only an update with a newer timestamp than the one currently stored in flash will be loaded and installed.
* The first OTA update after using UniFlash ImageCreator will always work since it does not program any timestamp.
[[g! Results
Verify the successful execution on the debug terminal.

Note that after a successful OTA sequence the new image should be triggered. It can be monitored through the application name.

]]
Further Reading
================
After experiencing the OTA application with the CC3x20 device, see the following resources for further assistance in development:
* [CC3x20 Network Processor Programmer's Guide](http://www.ti.com/lit/swru455): This guide contains information on how to use the SimpleLink API for writing WLAN-enabled applications. Please refer to chapter 7 (File System) for important details on the OTA image bundle attributes.
* [CC3x20 OTA Application Report](http://www.ti.com/lit/swra510): This document describes the OTA library for the SimpleLink Wireless MCUs, and explains how to prepare a new cloud-ready update to be downloaded by the OTA library.
* [UniFlash ImageCreator User's Guide](http://www.ti.com/lit/swru469): The Imaging tool manually stores files on the external serial flash. It is also includes the capability of creating an OTA image (in a tar file) that is ready to be stored in a CDN. Image may include the SimpleLink firmware patch file and any configuration files, security certificates, web pages, and so forth.
[[b! Technical support
For any questions, please search on the
[TI SimpleLink Wi-Fi E2E Forum](https://e2e.ti.com/)
]]