AWS IoT Over-the-air Update  v2.0.0 (Release Candidate)
Client library for AWS IoT OTA
ota.c File Reference

Implementation of the AWS IoT Over-The-Air Updates Client Library. More...

#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <assert.h>
#include "ota.h"
#include "ota_config.h"
#include "ota_config_defaults.h"
#include "ota_base64_private.h"
#include "ota_platform_interface.h"
#include "ota_private.h"
#include "ota_interface_private.h"
#include "ota_os_interface.h"
#include "core_json.h"
#include "ota_appversion32.h"

Data Structures

struct  OtaStateTableEntry_t
 OTA Agent state table entry. More...
 

Macros

#define U16_OFFSET(type, member)   ( ( uint16_t ) offsetof( type, member ) )
 Offset helper.
 

Typedefs

typedef OtaErr_t(* OtaEventHandler_t) (const OtaEventData_t *pEventMsg)
 OTA event handler definition.
 

Functions

static IngestResult_t ingestDataBlock (OtaFileContext_t *pFileContext, const uint8_t *pRawMsg, uint32_t messageSize, OtaPalStatus_t *pCloseResult)
 Ingest a data block. More...
 
static IngestResult_t processDataBlock (OtaFileContext_t *pFileContext, uint32_t uBlockIndex, uint32_t uBlockSize, OtaPalStatus_t *pCloseResult, uint8_t *pPayload)
 Validate the incoming data block and store it in the file context. More...
 
static IngestResult_t ingestDataBlockCleanup (OtaFileContext_t *pFileContext, OtaPalStatus_t *pCloseResult)
 Free the resources allocated for data ingestion and close the file handle. More...
 
static OtaFileContext_tgetFileContextFromJob (const char *pRawMsg, uint32_t messageLength)
 Get the File Context From Job Document. More...
 
static DocParseErr_t validateJSON (const char *pJson, uint32_t messageLength)
 Validate JSON document and the DocModel. More...
 
static DocParseErr_t extractParameter (JsonDocParam_t docParam, void *pContextBase, const char *pValueInJson, size_t valueLength)
 Store the parameter from the json to the offset specified by the document model. More...
 
static DocParseErr_t parseJSONbyModel (const char *pJson, uint32_t messageLength, JsonDocModel_t *pDocModel)
 Extract the desired fields from the JSON document based on the specified document model. More...
 
static DocParseErr_t decodeAndStoreKey (const char *pValueInJson, size_t valueLength, void *pParamAdd)
 Decode the base64 encoded file signature key from the job document and store it in file context. More...
 
static DocParseErr_t extractAndStoreArray (const char *pKey, const char *pValueInJson, size_t valueLength, void *pParamAdd, uint32_t *pParamSizeAdd)
 Extract the value from json and store it into the allocated memory. More...
 
static DocParseErr_t verifyRequiredParamsExtracted (const JsonDocParam_t *pModelParam, const JsonDocModel_t *pDocModel)
 Check if all the required parameters for job document are extracted from the JSON. More...
 
static OtaErr_t validateUpdateVersion (const OtaFileContext_t *pFileContext)
 Validate the version of the update received. More...
 
static OtaJobParseErr_t parseJobDocFromCustomCallback (const char *pJson, uint32_t messageLength, OtaFileContext_t *pFileContext, OtaFileContext_t **pFinalFile)
 Check if the JSON can be parsed through a custom callback if initial parsing fails. More...
 
static OtaJobParseErr_t verifyActiveJobStatus (OtaFileContext_t *pFileContext, OtaFileContext_t **pFinalFile, bool *pUpdateJob)
 Check if the incoming job document is not conflicting with current job status. More...
 
static OtaJobParseErr_t validateAndStartJob (OtaFileContext_t *pFileContext, OtaFileContext_t **pFinalFile, bool *pUpdateJob)
 Check if all the file context params are valid and initialize resources for the job transfer. More...
 
static OtaFileContext_tparseJobDoc (const char *pJson, uint32_t messageLength, bool *pUpdateJob)
 Parse the OTA job document, validate and return the populated OTA context if valid. More...
 
static bool validateDataBlock (const OtaFileContext_t *pFileContext, uint32_t blockIndex, uint32_t blockSize)
 Validate block index and block size of the data block. More...
 
static IngestResult_t decodeAndStoreDataBlock (OtaFileContext_t *pFileContext, const uint8_t *pRawMsg, uint32_t messageSize, uint8_t **pPayload, uint32_t *pBlockSize, uint32_t *pBlockIndex)
 Decode and ingest the incoming data block. More...
 
static bool otaClose (OtaFileContext_t *const pFileContext)
 Close an open OTA file context and free it. More...
 
static void otaTimerCallback (OtaTimerId_t otaTimerId)
 OTA Timer callback. More...
 
static OtaErr_t setImageStateWithReason (OtaImageState_t stateToSet, uint32_t reasonToSet)
 Internal function to set the image state including an optional reason code. More...
 
static OtaErr_t updateJobStatusFromImageState (OtaImageState_t state, int32_t subReason)
 Internal function to update the job status to the jobs service from current image state. More...
 
static void agentShutdownCleanup (void)
 A helper function to cleanup resources during OTA agent shutdown.
 
static void dataHandlerCleanup (IngestResult_t result)
 A helper function to cleanup resources when data ingestion is complete.
 
static DocParseErr_t initDocModel (JsonDocModel_t *pDocModel, const JsonDocParam_t *pBodyDef, void *contextBaseAddr, uint32_t contextSize, uint16_t numJobParams)
 Prepare the document model for use by sanity checking the initialization parameters and detecting all required parameters. More...
 
static void initializeAppBuffers (OtaAppBuffer_t *pOtaBuffer)
 Initialize buffers for storing the file attributes. More...
 
static void initializeLocalBuffers (void)
 Initialize jobId and protocol buffers.
 
static uint32_t searchTransition (const OtaEventMsg_t *pEventMsg)
 Search the state transition table for the entry based on current state and incoming event. More...
 
static OtaErr_t processValidFileContext (void)
 Initiate download if not in self-test else reboot. More...
 
static void handleSelfTestJobDoc (OtaFileContext_t *pFileContext)
 Validate update version when receiving job doc in self test state. More...
 
static OtaErr_t processNullFileContext (void)
 Handle invalid file context. More...
 
static bool inSelftest (void)
 Check if the platform is in self-test. More...
 
static void handleUnexpectedEvents (const OtaEventMsg_t *pEventMsg)
 Function to handle events that were unexpected in the current state. More...
 
static void freeFileContextMem (OtaFileContext_t *const pFileContext)
 Free or clear multiple buffers used in the file context. More...
 
static void handleJobParsingError (const OtaFileContext_t *pFileContext, OtaJobParseErr_t err)
 Handle job parsing error. More...
 
static OtaErr_t startHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t requestJobHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t processJobHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t inSelfTestHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t initFileHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t processDataHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t requestDataHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t shutdownHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t closeFileHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t userAbortHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t suspendHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t resumeHandler (const OtaEventData_t *pEventData)
 
static OtaErr_t jobNotificationHandler (const OtaEventData_t *pEventData)
 
static void executeHandler (uint32_t index, const OtaEventMsg_t *const pEventMsg)
 
void OTA_EventProcessingTask (void *pUnused)
 OTA agent event processing loop. More...
 
bool OTA_SignalEvent (const OtaEventMsg_t *const pEventMsg)
 Signal event to the OTA Agent task. More...
 
OtaErr_t OTA_Init (OtaAppBuffer_t *pOtaBuffer, OtaInterfaces_t *pOtaInterfaces, const uint8_t *pThingName, OtaAppCallback_t OtaAppCallback)
 OTA Agent initialization function. More...
 
OtaState_t OTA_Shutdown (uint32_t ticksToWait)
 Signal to the OTA Agent to shut down. More...
 
OtaState_t OTA_GetState (void)
 Get the current state of the OTA agent. More...
 
OtaErr_t OTA_GetStatistics (OtaAgentStatistics_t *pStatistics)
 Get the statistics of OTA message packets. More...
 
OtaErr_t OTA_CheckForUpdate (void)
 Request for the next available OTA job from the job service. More...
 
OtaErr_t OTA_ActivateNewImage (void)
 Activate the newest MCU image received via OTA. More...
 
OtaErr_t OTA_SetImageState (OtaImageState_t state)
 Set the state of the current MCU image. More...
 
OtaImageState_t OTA_GetImageState (void)
 Get the state of the currently running MCU image. More...
 
OtaErr_t OTA_Suspend (void)
 Suspend OTA agent operations . More...
 
OtaErr_t OTA_Resume (void)
 Resume OTA agent operations . More...
 
const char * OTA_Err_strerror (OtaErr_t err)
 Error code to string conversion for OTA errors. More...
 
const char * OTA_JobParse_strerror (OtaJobParseErr_t err)
 Error code to string conversion for OTA Job Parsing errors. More...
 
const char * OTA_OsStatus_strerror (OtaOsStatus_t status)
 Status code to string conversion for OTA OS status. More...
 
const char * OTA_PalStatus_strerror (OtaPalMainStatus_t status)
 Status code to string conversion for OTA PAL status. More...
 

Variables

static OtaControlInterface_t otaControlInterface
 OTA control interface.
 
static OtaDataInterface_t otaDataInterface
 OTA data interface.
 
static OtaAgentContext_t otaAgent
 This is THE OTA agent context and initialization state. More...
 
static OtaStateTableEntry_t otaTransitionTable []
 Transition table for the OTA state machine. More...
 
static const char * pOtaAgentStateStrings [OtaAgentStateAll+1]
 
static const char * pOtaEventStrings [OtaAgentEventMax]
 
static uint8_t pJobNameBuffer [OTA_JOB_ID_MAX_SIZE]
 
static uint8_t pProtocolBuffer [20]
 
static Sig256_t sig256Buffer
 
static const JsonDocParam_t otaJobDocModelParamStructure [OTA_NUM_JOB_PARAMS]
 This is the OTA job document model describing the parameters, their types, destination and how to extract. More...
 

Detailed Description

Implementation of the AWS IoT Over-The-Air Updates Client Library.

Function Documentation

◆ ingestDataBlock()

static IngestResult_t ingestDataBlock ( OtaFileContext_t pFileContext,
const uint8_t *  pRawMsg,
uint32_t  messageSize,
OtaPalStatus_t pCloseResult 
)
static

Ingest a data block.

A block of file data was received by the application via some configured communication protocol. If it looks like it is in range, write it to persistent storage. If it's the last block we're expecting, close the file and perform the final signature check on it. If the close and signature check are OK, let the caller know so it can be used by the system. Firmware updates generally reboot the system and perform a self test phase. If the close or signature check fails, abort the file transfer and return the result and any available details to the caller.

Parameters
[in]pFileContextInformation of file to be streamed.
[in]pRawMsgRaw job document.
[in]messageSizeLength of document.
[in]pCloseResultResult of closing file in PAL.
Returns
IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.

◆ processDataBlock()

static IngestResult_t processDataBlock ( OtaFileContext_t pFileContext,
uint32_t  uBlockIndex,
uint32_t  uBlockSize,
OtaPalStatus_t pCloseResult,
uint8_t *  pPayload 
)
static

Validate the incoming data block and store it in the file context.

Parameters
[in]pFileContextInformation of file to be streamed.
[in]uBlockIndexIncoming block index.
[in]uBlockSizeIncoming block size.
[out]pCloseResultResult of closing file in PAL.
[in]pPayloadData from the block.
Returns
IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.

◆ ingestDataBlockCleanup()

static IngestResult_t ingestDataBlockCleanup ( OtaFileContext_t pFileContext,
OtaPalStatus_t pCloseResult 
)
static

Free the resources allocated for data ingestion and close the file handle.

Parameters
[in]pFileContextInformation of file to be streamed.
[out]pCloseResultResult of closing file in PAL.
Returns
IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.

◆ getFileContextFromJob()

static OtaFileContext_t * getFileContextFromJob ( const char *  pRawMsg,
uint32_t  messageLength 
)
static

Get the File Context From Job Document.

We received an OTA update job message from the job service so process the message and update the file context.

Parameters
[in]pRawMsgRaw job document.
[in]messageLengthlength of document.
Returns
OtaFileContext_t* Information of file to be streamed.

◆ validateJSON()

static DocParseErr_t validateJSON ( const char *  pJson,
uint32_t  messageLength 
)
static

Validate JSON document and the DocModel.

Parameters
[in]pJsonJSON job document.
[in]messageLengthLength of the job document.
Returns
DocParseErr_t DocParseErrNone if successful, JSON document parser errors.

◆ extractParameter()

static DocParseErr_t extractParameter ( JsonDocParam_t  docParam,
void *  pContextBase,
const char *  pValueInJson,
size_t  valueLength 
)
static

Store the parameter from the json to the offset specified by the document model.

Parameters
[in]docParamStructure to store the details of keys and where to store them.
[in]pContextBaseStart of file context.
[in]pValueInJsonPointer to the value of the key in JSON buffer.
[in]valueLengthLength of the value.
Returns
DocParseErr_t DocParseErrNone if successful, JSON document parser errors.

◆ parseJSONbyModel()

static DocParseErr_t parseJSONbyModel ( const char *  pJson,
uint32_t  messageLength,
JsonDocModel_t pDocModel 
)
static

Extract the desired fields from the JSON document based on the specified document model.

Parameters
[in]pJsonJSON job document.
[in]messageLengthLength of the job document.
[in]pDocModelDetails of expected parameters in the job doc.
Returns
DocParseErr_t DocParseErr_t DocParseErrNone if successful, JSON document parser errors.

◆ decodeAndStoreKey()

static DocParseErr_t decodeAndStoreKey ( const char *  pValueInJson,
size_t  valueLength,
void *  pParamAdd 
)
static

Decode the base64 encoded file signature key from the job document and store it in file context.

Parameters
[in]pValueInJsonPointer to the value of the key in JSON buffer.
[in]valueLengthLength of the value.
[out]pParamAddPointer to the location where the value is stored.
Returns
DocParseErr_t DocParseErrNone if successful, JSON document parser errors.

◆ extractAndStoreArray()

static DocParseErr_t extractAndStoreArray ( const char *  pKey,
const char *  pValueInJson,
size_t  valueLength,
void *  pParamAdd,
uint32_t *  pParamSizeAdd 
)
static

Extract the value from json and store it into the allocated memory.

Parameters
[in]pKeyName of the Key to extract.
[in]pValueInJsonPointer to the value of the key in JSON buffer.
[in]valueLengthLength of the value.
[out]pParamAddPointer to the location where the value is stored.
[in]pParamSizeAddSize required to store the param.
Returns
DocParseErr_t DocParseErrNone if successful, JSON document parser errors.

◆ verifyRequiredParamsExtracted()

static DocParseErr_t verifyRequiredParamsExtracted ( const JsonDocParam_t pModelParam,
const JsonDocModel_t pDocModel 
)
static

Check if all the required parameters for job document are extracted from the JSON.

Parameters
[in]pModelParamStructure to store the details of keys and where to store them.
[in]pDocModelDetails of expected parameters in the job doc.
Returns
DocParseErr_t DocParseErrNone if successful, JSON document parser errors.

◆ validateUpdateVersion()

static OtaErr_t validateUpdateVersion ( const OtaFileContext_t pFileContext)
static

Validate the version of the update received.

Parameters
[in]pFileContextInformation of file to be streamed.
Returns
OtaErr_t OtaErrNone if successful, other error codes if failure.

◆ parseJobDocFromCustomCallback()

static OtaJobParseErr_t parseJobDocFromCustomCallback ( const char *  pJson,
uint32_t  messageLength,
OtaFileContext_t pFileContext,
OtaFileContext_t **  pFinalFile 
)
static

Check if the JSON can be parsed through a custom callback if initial parsing fails.

Parameters
[in]pJsonJSON job document.
[in]messageLengthLength of the job document.
[in]pFileContextInformation of file to be streamed.
[out]pFinalFileFile that stores all extracted params.
Returns
OtaJobParseErr_t OtaJobParseErrNone if successful, other error codes if failure.

◆ verifyActiveJobStatus()

static OtaJobParseErr_t verifyActiveJobStatus ( OtaFileContext_t pFileContext,
OtaFileContext_t **  pFinalFile,
bool *  pUpdateJob 
)
static

Check if the incoming job document is not conflicting with current job status.

Parameters
[in]pFileContextInformation of file to be streamed.
[out]pFinalFileFile that stores all extracted params.
[out]pUpdateJobRepresents if the job is accepted.
Returns
OtaJobParseErr_t OtaErrNone if successful, other error codes if failure.

◆ validateAndStartJob()

static OtaJobParseErr_t validateAndStartJob ( OtaFileContext_t pFileContext,
OtaFileContext_t **  pFinalFile,
bool *  pUpdateJob 
)
static

Check if all the file context params are valid and initialize resources for the job transfer.

Parameters
[in]pFileContextInformation of file to be streamed.
[out]pFinalFileFile that stores all extracted params.
[out]pUpdateJobRepresents if the job is accepted.
Returns
OtaJobParseErr_t OtaJobParseErrNone if successful, other error codes if failure.

◆ parseJobDoc()

static OtaFileContext_t * parseJobDoc ( const char *  pJson,
uint32_t  messageLength,
bool *  pUpdateJob 
)
static

Parse the OTA job document, validate and return the populated OTA context if valid.

Parameters
[in]pJsonJSON job document.
[in]messageLengthLength of the job document.
[in]pUpdateJobRepresents if the job is accepted.
Returns
OtaFileContext_t* File context to store file information.

◆ validateDataBlock()

static bool validateDataBlock ( const OtaFileContext_t pFileContext,
uint32_t  blockIndex,
uint32_t  blockSize 
)
static

Validate block index and block size of the data block.

Parameters
[in]pFileContextInformation of file to be streamed.
[in]blockIndexBlock index of incoming data block.
[in]blockSizeBlock size of incoming data block.
Returns
true if successful, false otherwise.

◆ decodeAndStoreDataBlock()

static IngestResult_t decodeAndStoreDataBlock ( OtaFileContext_t pFileContext,
const uint8_t *  pRawMsg,
uint32_t  messageSize,
uint8_t **  pPayload,
uint32_t *  pBlockSize,
uint32_t *  pBlockIndex 
)
static

Decode and ingest the incoming data block.

Parameters
[in]pFileContextInformation of file to be streamed.
[in]pRawMsgRaw job document.
[in]messageSizeLength of document.
[in]pPayloadData stored in the document.
[out]pBlockSizeBlock size of incoming data block.
[out]pBlockIndexBlock index of incoming data block.
Returns
IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.

◆ otaClose()

static bool otaClose ( OtaFileContext_t *const  pFileContext)
static

Close an open OTA file context and free it.

Parameters
[in]pFileContextInformation of file to be streamed.
Returns
true if successful, false otherwise.

◆ otaTimerCallback()

static void otaTimerCallback ( OtaTimerId_t  otaTimerId)
static

OTA Timer callback.

Parameters
[in]otaTimerIdReference to the timer to use.

◆ setImageStateWithReason()

static OtaErr_t setImageStateWithReason ( OtaImageState_t  stateToSet,
uint32_t  reasonToSet 
)
static

Internal function to set the image state including an optional reason code.

Parameters
[in]stateToSetState to set.
[in]reasonToSetReason to set.
Returns
OtaErr_t OtaErrNone if successful, other codes on failure.

◆ updateJobStatusFromImageState()

static OtaErr_t updateJobStatusFromImageState ( OtaImageState_t  state,
int32_t  subReason 
)
static

Internal function to update the job status to the jobs service from current image state.

Parameters
[in]stateState to set.
[in]subReasonReason for status.
Returns
OtaErr_t OtaErrNone if successful, other codes on failure.

◆ initDocModel()

static DocParseErr_t initDocModel ( JsonDocModel_t pDocModel,
const JsonDocParam_t pBodyDef,
void *  contextBaseAddr,
uint32_t  contextSize,
uint16_t  numJobParams 
)
static

Prepare the document model for use by sanity checking the initialization parameters and detecting all required parameters.

Parameters
[in,out]pDocModelDetails of expected parameters in the job doc.
[in]pBodyDefStructure to store the details of keys and where to store them.
[in]contextBaseAddrStart of file context.
[in]contextSizeSize of file context.
[in]numJobParamsNumber of parameters to be extracted.
Returns
DocParseErr_t DocParseErrNone if successful, JSON document parser errors.

◆ initializeAppBuffers()

static void initializeAppBuffers ( OtaAppBuffer_t pOtaBuffer)
static

Initialize buffers for storing the file attributes.

Parameters
[out]pOtaBufferOTA Application buffers.

◆ searchTransition()

static uint32_t searchTransition ( const OtaEventMsg_t pEventMsg)
static

Search the state transition table for the entry based on current state and incoming event.

Parameters
[in]pEventMsgIncoming event information.
Returns
uint32_t Index of the transition.

◆ processValidFileContext()

static OtaErr_t processValidFileContext ( void  )
static

Initiate download if not in self-test else reboot.

Returns
OtaErr_t OtaErrNone if successful.

◆ handleSelfTestJobDoc()

static void handleSelfTestJobDoc ( OtaFileContext_t pFileContext)
static

Validate update version when receiving job doc in self test state.

Parameters
[in]pFileContextStores file information.

◆ processNullFileContext()

static OtaErr_t processNullFileContext ( void  )
static

Handle invalid file context.

Returns
OtaErr_t OtaErrNone if job parsing is handled.

◆ inSelftest()

static bool inSelftest ( void  )
static

Check if the platform is in self-test.

Returns
true if in self-test, else false.

◆ handleUnexpectedEvents()

static void handleUnexpectedEvents ( const OtaEventMsg_t pEventMsg)
static

Function to handle events that were unexpected in the current state.

Parameters
[in]pEventMsgStores information of the event.

◆ freeFileContextMem()

static void freeFileContextMem ( OtaFileContext_t *const  pFileContext)
static

Free or clear multiple buffers used in the file context.

Parameters
[in]pFileContextInformation of file to be streamed.

◆ handleJobParsingError()

static void handleJobParsingError ( const OtaFileContext_t pFileContext,
OtaJobParseErr_t  err 
)
static

Handle job parsing error.

Parameters
[in]pFileContextPointer to the file context.
[in]errParsing error of type OtaJobParseErr_t.

◆ startHandler()

static OtaErr_t startHandler ( const OtaEventData_t pEventData)
static

Start timers and initiate request for job document.

◆ requestJobHandler()

static OtaErr_t requestJobHandler ( const OtaEventData_t pEventData)
static

Initiate a request for a job.

◆ processJobHandler()

static OtaErr_t processJobHandler ( const OtaEventData_t pEventData)
static

Update file context from job document.

◆ inSelfTestHandler()

static OtaErr_t inSelfTestHandler ( const OtaEventData_t pEventData)
static

Handle self test.

◆ initFileHandler()

static OtaErr_t initFileHandler ( const OtaEventData_t pEventData)
static

Initialize and handle file transfer.

◆ processDataHandler()

static OtaErr_t processDataHandler ( const OtaEventData_t pEventData)
static

Process incoming data blocks.

◆ requestDataHandler()

static OtaErr_t requestDataHandler ( const OtaEventData_t pEventData)
static

Request for data blocks.

◆ shutdownHandler()

static OtaErr_t shutdownHandler ( const OtaEventData_t pEventData)
static

Shutdown OTA and cleanup.

◆ closeFileHandler()

static OtaErr_t closeFileHandler ( const OtaEventData_t pEventData)
static

Close file opened for download.

◆ userAbortHandler()

static OtaErr_t userAbortHandler ( const OtaEventData_t pEventData)
static

Handle user interrupt to abort task.

◆ suspendHandler()

static OtaErr_t suspendHandler ( const OtaEventData_t pEventData)
static

Handle suspend event for OTA agent.

◆ resumeHandler()

static OtaErr_t resumeHandler ( const OtaEventData_t pEventData)
static

Resume from a suspended state.

◆ jobNotificationHandler()

static OtaErr_t jobNotificationHandler ( const OtaEventData_t pEventData)
static

Upon receiving a new job document cancel current job if present and initiate new download.

◆ executeHandler()

static void executeHandler ( uint32_t  index,
const OtaEventMsg_t *const  pEventMsg 
)
static

Execute the handler for selected index from the transition table.

◆ OTA_EventProcessingTask()

void OTA_EventProcessingTask ( void *  pUnused)

OTA agent event processing loop.

This is the main event loop to handle events for OTA update and needs to be called by the application task. This loop will continue to handle and execute events received for OTA Update until this tasks is terminated by the application.

Parameters
[in]pUnusedCan be used to pass down functionality to the agent task, Unused for now. This can be a function pointer that executes as the first routine when the event loop starts.

◆ OTA_SignalEvent()

bool OTA_SignalEvent ( const OtaEventMsg_t *const  pEventMsg)

Signal event to the OTA Agent task.

This function adds the event to the back of event queue and used by internal OTA modules to signal agent task.

Parameters
[in]pEventMsgEvent to be added to the queue
Returns
true If operation is successful, false If the event can not be added

◆ OTA_Init()

OtaErr_t OTA_Init ( OtaAppBuffer_t pOtaBuffer,
OtaInterfaces_t pOtaInterfaces,
const uint8_t *  pThingName,
OtaAppCallback_t  OtaAppCallback 
)

OTA Agent initialization function.

Initialize the OTA engine by starting the OTA Agent ("OTA Task") in the system. This function must be called with the connection client context before calling OTA_CheckForUpdate. Only one OTA Agent may exist.

Parameters
[in]pOtaBufferBuffers used by the agent to store different params.
[in]pOtaInterfacesA pointer to the OS context.
[in]pThingNameA pointer to a C string holding the Thing name.
[in]OtaAppCallbackStatic callback function for when an OTA job is complete. This function will have input of the state of the OTA image after download and during self-test.
Returns
OtaErr_t The state of the OTA Agent upon return from the OtaState_t enum. If the agent was successfully initialized and ready to operate, the state will be OtaAgentStateReady. Otherwise, it will be one of the other OtaState_t enum values.

◆ OTA_Shutdown()

OtaState_t OTA_Shutdown ( uint32_t  ticksToWait)

Signal to the OTA Agent to shut down.

Signals the OTA agent task to shut down. The OTA agent will unsubscribe from all MQTT job notification topics, stop in progress OTA jobs, if any, and clear all resources.

Parameters
[in]ticksToWaitThe number of ticks to wait for the OTA Agent to complete the shutdown process. If this is set to zero, the function will return immediately without waiting. The actual state is returned to the caller.
Returns
One of the OTA agent states from the OtaState_t enum. A normal shutdown will return OtaAgentStateNotReady. Otherwise, refer to the OtaState_t enum for details.

◆ OTA_GetState()

OtaState_t OTA_GetState ( void  )

Get the current state of the OTA agent.

Returns
The current state of the OTA agent.

◆ OTA_GetStatistics()

OtaErr_t OTA_GetStatistics ( OtaAgentStatistics_t pStatistics)

Get the statistics of OTA message packets.

Packet statistics are:

  • Received: The number of OTA packets that have been received but not necessarily queued for processing by the OTA agent.
  • Queued: The number of OTA packets that have been queued for processing. This implies there was a free message queue entry so it can be passed to the agent for processing.
  • Processed: The number of OTA packets that have actually been processed.
  • Dropped: The number of OTA packets that have been dropped because of either no queue or at shutdown cleanup.
Note
Calling OTA_Init will reset this statistic.
Returns
OtaErrNone if the statistics can be received successfully.

◆ OTA_CheckForUpdate()

OtaErr_t OTA_CheckForUpdate ( void  )

Request for the next available OTA job from the job service.

Returns
OtaErrNone if successful, otherwise an error code prefixed with 'kOTA_Err_' from the list above.

◆ OTA_ActivateNewImage()

OtaErr_t OTA_ActivateNewImage ( void  )

Activate the newest MCU image received via OTA.

This function should reset the MCU and cause a reboot of the system to execute the newly updated firmware. It should be called by the user code sometime after the OtaJobEventActivate event is passed to the users application via the OTA Job Complete Callback mechanism. Refer to the OTA_Init function for more information about configuring the callback.

Returns
OtaErrNone if successful, otherwise an error code prefixed with 'kOTA_Err_' from the list above.

◆ OTA_SetImageState()

OtaErr_t OTA_SetImageState ( OtaImageState_t  state)

Set the state of the current MCU image.

The states are OtaImageStateTesting, OtaImageStateAccepted, OtaImageStateAborted or OtaImageStateRejected; see OtaImageState_t documentation. This will update the status of the current image and publish to the active job status topic.

Parameters
[in]stateThe state to set of the OTA image.
Returns
OtaErrNone if successful, otherwise an error code prefixed with 'kOTA_Err_' from the list above.

◆ OTA_GetImageState()

OtaImageState_t OTA_GetImageState ( void  )

Get the state of the currently running MCU image.

The states are OtaImageStateTesting, OtaImageStateAccepted, OtaImageStateAborted or OtaImageStateRejected; see OtaImageState_t documentation.

Returns
The state of the current context's OTA image.

◆ OTA_Suspend()

OtaErr_t OTA_Suspend ( void  )

Suspend OTA agent operations .

Returns
OtaErrNone if successful, otherwise an error code prefixed with 'kOTA_Err_' from the list above.

◆ OTA_Resume()

OtaErr_t OTA_Resume ( void  )

Resume OTA agent operations .

Returns
OtaErrNone if successful, otherwise an error code prefixed with 'kOTA_Err_' from the list above.

◆ OTA_Err_strerror()

const char* OTA_Err_strerror ( OtaErr_t  err)

Error code to string conversion for OTA errors.

Parameters
[in]errThe error to convert to a string.
Returns
The string representation of the error.

◆ OTA_JobParse_strerror()

const char* OTA_JobParse_strerror ( OtaJobParseErr_t  err)

Error code to string conversion for OTA Job Parsing errors.

Parameters
[in]errThe error to convert to a string.
Returns
The string representation of the error.

◆ OTA_OsStatus_strerror()

const char* OTA_OsStatus_strerror ( OtaOsStatus_t  status)

Status code to string conversion for OTA OS status.

Parameters
[in]statusThe status to convert to a string.
Returns
The string representation of the status.

◆ OTA_PalStatus_strerror()

const char* OTA_PalStatus_strerror ( OtaPalMainStatus_t  status)

Status code to string conversion for OTA PAL status.

Parameters
[in]statusThe status to convert to a string.
Returns
The string representation of the status.

Variable Documentation

◆ otaAgent

OtaAgentContext_t otaAgent
static
Initial value:
=
{
OtaAgentStateStopped,
{ 0 },
{ 0 },
0,
0,
{ 0 },
NULL,
0,
1,
{ 0 },
0,
NULL,
NULL,
NULL
}

This is THE OTA agent context and initialization state.

◆ otaTransitionTable

OtaStateTableEntry_t otaTransitionTable[]
static
Initial value:
=
{
{ OtaAgentStateReady, OtaAgentEventStart, startHandler, OtaAgentStateRequestingJob },
{ OtaAgentStateRequestingJob, OtaAgentEventRequestJobDocument, requestJobHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateRequestingJob, OtaAgentEventRequestTimer, requestJobHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateWaitingForJob, OtaAgentEventReceivedJobDocument, processJobHandler, OtaAgentStateCreatingFile },
{ OtaAgentStateCreatingFile, OtaAgentEventStartSelfTest, inSelfTestHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateCreatingFile, OtaAgentEventCreateFile, initFileHandler, OtaAgentStateRequestingFileBlock },
{ OtaAgentStateCreatingFile, OtaAgentEventRequestTimer, initFileHandler, OtaAgentStateRequestingFileBlock },
{ OtaAgentStateRequestingFileBlock, OtaAgentEventRequestFileBlock, requestDataHandler, OtaAgentStateWaitingForFileBlock },
{ OtaAgentStateRequestingFileBlock, OtaAgentEventRequestTimer, requestDataHandler, OtaAgentStateWaitingForFileBlock },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventReceivedFileBlock, processDataHandler, OtaAgentStateWaitingForFileBlock },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventRequestTimer, requestDataHandler, OtaAgentStateWaitingForFileBlock },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventRequestFileBlock, requestDataHandler, OtaAgentStateWaitingForFileBlock },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventRequestJobDocument, requestJobHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventReceivedJobDocument, jobNotificationHandler, OtaAgentStateRequestingJob },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventCloseFile, closeFileHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateSuspended, OtaAgentEventResume, resumeHandler, OtaAgentStateRequestingJob },
{ OtaAgentStateAll, OtaAgentEventSuspend, suspendHandler, OtaAgentStateSuspended },
{ OtaAgentStateAll, OtaAgentEventUserAbort, userAbortHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateAll, OtaAgentEventShutdown, shutdownHandler, OtaAgentStateStopped },
}

Transition table for the OTA state machine.

◆ pOtaAgentStateStrings

const char* pOtaAgentStateStrings[OtaAgentStateAll+1]
static
Initial value:
=
{
"Init",
"Ready",
"RequestingJob",
"WaitingForJob",
"CreatingFile",
"RequestingFileBlock",
"WaitingForFileBlock",
"ClosingFile",
"Suspended",
"ShuttingDown",
"Stopped",
"All"
}

< String set to represent the States of the OTA agent.

◆ pOtaEventStrings

const char* pOtaEventStrings[OtaAgentEventMax]
static
Initial value:
=
{
"Start",
"StartSelfTest",
"RequestJobDocument",
"ReceivedJobDocument",
"CreateFile",
"RequestFileBlock",
"ReceivedFileBlock",
"RequestTimer",
"CloseFile",
"Suspend",
"Resume",
"UserAbort",
"Shutdown"
}

< String set to represent the Events for the OTA agent.

◆ pJobNameBuffer

uint8_t pJobNameBuffer[OTA_JOB_ID_MAX_SIZE]
static

Buffer to store job name.

◆ pProtocolBuffer

uint8_t pProtocolBuffer[20]
static

Buffer to store data protocol.

◆ sig256Buffer

Sig256_t sig256Buffer
static

Buffer to store key file signature.

◆ otaJobDocModelParamStructure

const JsonDocParam_t otaJobDocModelParamStructure[OTA_NUM_JOB_PARAMS]
static
Initial value:
=
{
{ OTA_JSON_JOB_ID_KEY, OTA_JOB_PARAM_REQUIRED, U16_OFFSET( OtaFileContext_t, pJobName ), U16_OFFSET( OtaFileContext_t, jobNameMaxSize ), ModelParamTypeStringCopy},
{ OTA_JSON_STREAM_NAME_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pStreamName ), U16_OFFSET( OtaFileContext_t, streamNameMaxSize ), ModelParamTypeStringCopy},
{ OTA_JSON_PROTOCOLS_KEY, OTA_JOB_PARAM_REQUIRED, U16_OFFSET( OtaFileContext_t, pProtocols ), U16_OFFSET( OtaFileContext_t, protocolMaxSize ), ModelParamTypeArrayCopy},
{ OTA_JSON_FILE_PATH_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pFilePath ), U16_OFFSET( OtaFileContext_t, filePathMaxSize ), ModelParamTypeStringCopy},
{ OTA_JSON_FILE_CERT_NAME_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pCertFilepath ), U16_OFFSET( OtaFileContext_t, certFilePathMaxSize ), ModelParamTypeStringCopy},
{ OTA_JSON_UPDATE_DATA_URL_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pUpdateUrlPath ), U16_OFFSET( OtaFileContext_t, updateUrlMaxSize ), ModelParamTypeStringCopy},
{ OTA_JSON_AUTH_SCHEME_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pAuthScheme ), U16_OFFSET( OtaFileContext_t, authSchemeMaxSize ), ModelParamTypeStringCopy},
}

This is the OTA job document model describing the parameters, their types, destination and how to extract.

OtaAgentEventCreateFile
@ OtaAgentEventCreateFile
Event to create a file.
Definition: ota_private.h:358
OTA_DONT_STORE_PARAM
#define OTA_DONT_STORE_PARAM
If destOffset in the model is 0xffffffff, do not store the value.
Definition: ota_private.h:79
requestJobHandler
static OtaErr_t requestJobHandler(const OtaEventData_t *pEventData)
Definition: ota.c:791
OTA_JSON_FILE_CERT_NAME_KEY
#define OTA_JSON_FILE_CERT_NAME_KEY
Location of the certificate on the device to find code signing.
Definition: ota_private.h:146
OTA_JSON_JOB_ID_KEY
#define OTA_JSON_JOB_ID_KEY
Name of the job.
Definition: ota_private.h:131
OtaFileContext_t
OTA File Context Information.
Definition: ota_private.h:390
inSelfTestHandler
static OtaErr_t inSelfTestHandler(const OtaEventData_t *pEventData)
Definition: ota.c:755
OtaAgentEventSuspend
@ OtaAgentEventSuspend
Event to suspend ota task.
Definition: ota_private.h:363
OTA_JSON_TIMESTAMP_KEY
#define OTA_JSON_TIMESTAMP_KEY
Used to calculate timeout and time spent on the operation.
Definition: ota_private.h:129
requestDataHandler
static OtaErr_t requestDataHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1055
OTA_JSON_STREAM_NAME_KEY
#define OTA_JSON_STREAM_NAME_KEY
Name of the stream used for download.
Definition: ota_private.h:141
OtaAgentEventStart
@ OtaAgentEventStart
Start the OTA state machine.
Definition: ota_private.h:354
OtaAgentEventRequestFileBlock
@ OtaAgentEventRequestFileBlock
Event to request file blocks.
Definition: ota_private.h:359
suspendHandler
static OtaErr_t suspendHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1284
OTA_JSON_PROTOCOLS_KEY
#define OTA_JSON_PROTOCOLS_KEY
Protocols over which the download can take place.
Definition: ota_private.h:139
processDataHandler
static OtaErr_t processDataHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1146
OtaAgentEventRequestJobDocument
@ OtaAgentEventRequestJobDocument
Event for requesting job document.
Definition: ota_private.h:356
OtaAgentEventShutdown
@ OtaAgentEventShutdown
Event to trigger ota shutdown.
Definition: ota_private.h:366
OTA_STORE_NESTED_JSON
#define OTA_STORE_NESTED_JSON
Store the reference to a nested JSON in a separate pointer.
Definition: ota_private.h:80
OTA_JSON_CLIENT_TOKEN_KEY
#define OTA_JSON_CLIENT_TOKEN_KEY
Client token.
Definition: ota_private.h:128
OTA_JSON_FILE_ATTRIBUTE_KEY
#define OTA_JSON_FILE_ATTRIBUTE_KEY
Additional file attributes.
Definition: ota_private.h:145
startHandler
static OtaErr_t startHandler(const OtaEventData_t *pEventData)
Definition: ota.c:728
OTA_JSON_JOB_DOC_KEY
#define OTA_JSON_JOB_DOC_KEY
Parameters that specify the nature of the job.
Definition: ota_private.h:137
OtaAgentEventReceivedFileBlock
@ OtaAgentEventReceivedFileBlock
Event to trigger when file block is received.
Definition: ota_private.h:360
resumeHandler
static OtaErr_t resumeHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1294
OTA_JSON_FILE_PATH_KEY
#define OTA_JSON_FILE_PATH_KEY
Path to store the image on the device.
Definition: ota_private.h:142
OTA_JOB_PARAM_OPTIONAL
#define OTA_JOB_PARAM_OPTIONAL
Used to denote an optional document model parameter.
Definition: ota_private.h:78
OTA_JSON_AUTH_SCHEME_KEY
#define OTA_JSON_AUTH_SCHEME_KEY
Authentication scheme for downloading a the image over HTTP.
Definition: ota_private.h:148
OtaAgentEventResume
@ OtaAgentEventResume
Event to resume suspended task.
Definition: ota_private.h:364
initFileHandler
static OtaErr_t initFileHandler(const OtaEventData_t *pEventData)
Definition: ota.c:984
OtaImageStateUnknown
@ OtaImageStateUnknown
The initial state of the OTA MCU Image.
Definition: ota_private.h:323
OTA_JSON_FILE_GROUP_KEY
#define OTA_JSON_FILE_GROUP_KEY
Parameters for specifying file configurations.
Definition: ota_private.h:140
OtaAgentEventCloseFile
@ OtaAgentEventCloseFile
Event to trigger closing file.
Definition: ota_private.h:362
OTA_JSON_UPDATE_DATA_URL_KEY
#define OTA_JSON_UPDATE_DATA_URL_KEY
S3 bucket presigned url to fetch the image from .
Definition: ota_private.h:147
OTA_JSON_OTA_UNIT_KEY
#define OTA_JSON_OTA_UNIT_KEY
afr-ota.
Definition: ota_private.h:138
OTA_JSON_STATUS_DETAILS_KEY
#define OTA_JSON_STATUS_DETAILS_KEY
Current status of the job.
Definition: ota_private.h:132
OTA_JSON_SELF_TEST_KEY
#define OTA_JSON_SELF_TEST_KEY
Specifies if the platform and service is is selftest.
Definition: ota_private.h:133
OTA_JSON_FILE_ID_KEY
#define OTA_JSON_FILE_ID_KEY
Used to identify the file in case of multiple file downloads.
Definition: ota_private.h:144
OTA_JSON_UPDATED_BY_KEY
#define OTA_JSON_UPDATED_BY_KEY
Parameter to specify update status.
Definition: ota_private.h:134
OtaAgentEventRequestTimer
@ OtaAgentEventRequestTimer
Event to request event timer.
Definition: ota_private.h:361
OtaAgentEventReceivedJobDocument
@ OtaAgentEventReceivedJobDocument
Event when job document is received.
Definition: ota_private.h:357
OTA_JSON_EXECUTION_KEY
#define OTA_JSON_EXECUTION_KEY
Contains job execution parameters .
Definition: ota_private.h:130
OTA_JSON_FILE_SIZE_KEY
#define OTA_JSON_FILE_SIZE_KEY
Size of the file to be downloaded.
Definition: ota_private.h:143
closeFileHandler
static OtaErr_t closeFileHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1232
processJobHandler
static OtaErr_t processJobHandler(const OtaEventData_t *pEventData)
Definition: ota.c:952
OtaAgentEventStartSelfTest
@ OtaAgentEventStartSelfTest
Event to trigger self test.
Definition: ota_private.h:355
OTA_JSON_FILETYPE_KEY
#define OTA_JSON_FILETYPE_KEY
Used to identify the file in case of multi file type support.
Definition: ota_private.h:149
userAbortHandler
static OtaErr_t userAbortHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1245
jobNotificationHandler
static OtaErr_t jobNotificationHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1308
OTA_JOB_PARAM_REQUIRED
#define OTA_JOB_PARAM_REQUIRED
Used to denote a required document model parameter.
Definition: ota_private.h:77
shutdownHandler
static OtaErr_t shutdownHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1269
OTA_JsonFileSignatureKey
const char OTA_JsonFileSignatureKey[OTA_FILE_SIG_KEY_STR_MAX_LENGTH]
The OTA signature algorithm string is specified by the PAL.
OtaAgentEventUserAbort
@ OtaAgentEventUserAbort
Event triggered by user to stop agent.
Definition: ota_private.h:365
U16_OFFSET
#define U16_OFFSET(type, member)
Offset helper.
Definition: ota.c:75