AWS IoT Over-the-air Update
v3.1.0
Client library for AWS IoT OTA
|
|
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"
|
#define | U16_OFFSET(type, member) ( ( uint16_t ) offsetof( type, member ) ) |
| Offset helper.
|
|
|
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_t * | getFileContextFromJob (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 | handleCustomJob (const char *pJson, uint32_t messageLength) |
| Check if the JSON can be parsed through the app 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_t * | parseJobDoc (const JsonDocParam_t *pJsonExpectedParams, uint16_t numJobParams, 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 (void) |
| 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 | platformInSelftest (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 void | receiveAndProcessOtaEvent (void) |
| Receive and process the next available event from the event queue. 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, const OtaInterfaces_t *pOtaInterfaces, const uint8_t *pThingName, OtaAppCallback_t OtaAppCallback) |
| OTA Agent initialization function. More...
|
|
OtaState_t | OTA_Shutdown (uint32_t ticksToWait, uint8_t unsubscribeFlag) |
| 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...
|
|
Implementation of the AWS IoT Over-The-Air Updates Client Library.
◆ ingestDataBlock()
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] | pFileContext | Information of file to be streamed. |
[in] | pRawMsg | Raw job document. |
[in] | messageSize | Length of document. |
[in] | pCloseResult | Result of closing file in PAL. |
- Returns
- IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.
◆ processDataBlock()
Validate the incoming data block and store it in the file context.
- Parameters
-
[in] | pFileContext | Information of file to be streamed. |
[in] | uBlockIndex | Incoming block index. |
[in] | uBlockSize | Incoming block size. |
[out] | pCloseResult | Result of closing file in PAL. |
[in] | pPayload | Data from the block. |
- Returns
- IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.
◆ ingestDataBlockCleanup()
Free the resources allocated for data ingestion and close the file handle.
- Parameters
-
[in] | pFileContext | Information of file to be streamed. |
[out] | pCloseResult | Result 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] | pRawMsg | Raw job document. |
[in] | messageLength | length 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] | pJson | JSON job document. |
[in] | messageLength | Length of the job document. |
- Returns
- DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
◆ extractParameter()
Store the parameter from the json to the offset specified by the document model.
- Parameters
-
[in] | docParam | Structure to store the details of keys and where to store them. |
[in] | pContextBase | Start of file context. |
[in] | pValueInJson | Pointer to the value of the key in JSON buffer. |
[in] | valueLength | Length of the value. |
- Returns
- DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
◆ parseJSONbyModel()
Extract the desired fields from the JSON document based on the specified document model.
- Parameters
-
[in] | pJson | JSON job document. |
[in] | messageLength | Length of the job document. |
[in] | pDocModel | Details 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] | pValueInJson | Pointer to the value of the key in JSON buffer. |
[in] | valueLength | Length of the value. |
[out] | pParamAdd | Pointer 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] | pKey | Name of the Key to extract. |
[in] | pValueInJson | Pointer to the value of the key in JSON buffer. |
[in] | valueLength | Length of the value. |
[out] | pParamAdd | Pointer to the location where the value is stored. |
[in] | pParamSizeAdd | Size required to store the param. |
- Returns
- DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
◆ verifyRequiredParamsExtracted()
Check if all the required parameters for job document are extracted from the JSON.
- Parameters
-
[in] | pModelParam | Structure to store the details of keys and where to store them. |
[in] | pDocModel | Details of expected parameters in the job doc. |
- Returns
- DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
◆ validateUpdateVersion()
Validate the version of the update received.
- Parameters
-
[in] | pFileContext | Information of file to be streamed. |
- Returns
- OtaErr_t OtaErrNone if successful, other error codes if failure.
◆ handleCustomJob()
static OtaJobParseErr_t handleCustomJob |
( |
const char * |
pJson, |
|
|
uint32_t |
messageLength |
|
) |
| |
|
static |
Check if the JSON can be parsed through the app callback if initial parsing fails.
- Parameters
-
[in] | pJson | JSON job document. |
[in] | messageLength | Length of the job document. |
- Returns
- OtaJobParseErr_t OtaJobParseErrNone if successful, other error codes if failure.
◆ verifyActiveJobStatus()
Check if the incoming job document is not conflicting with current job status.
- Parameters
-
[in] | pFileContext | Information of file to be streamed. |
[out] | pFinalFile | File that stores all extracted params. |
[out] | pUpdateJob | Represents if the job is accepted. |
- Returns
- OtaJobParseErr_t OtaErrNone if successful, other error codes if failure.
◆ validateAndStartJob()
Check if all the file context params are valid and initialize resources for the job transfer.
- Parameters
-
[in] | pFileContext | Information of file to be streamed. |
[out] | pFinalFile | File that stores all extracted params. |
[out] | pUpdateJob | Represents if the job is accepted. |
- Returns
- OtaJobParseErr_t OtaJobParseErrNone if successful, other error codes if failure.
◆ parseJobDoc()
static OtaFileContext_t * parseJobDoc |
( |
const JsonDocParam_t * |
pJsonExpectedParams, |
|
|
uint16_t |
numJobParams, |
|
|
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] | pJsonExpectedParams | Structure to store the details of keys and where to store them. |
[in] | numJobParams | Number of parameters to be extracted. |
[in] | pJson | JSON job document. |
[in] | messageLength | Length of the job document. |
[in] | pUpdateJob | Represents 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] | pFileContext | Information of file to be streamed. |
[in] | blockIndex | Block index of incoming data block. |
[in] | blockSize | Block 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] | pFileContext | Information of file to be streamed. |
[in] | pRawMsg | Raw job document. |
[in] | messageSize | Length of document. |
[in] | pPayload | Data stored in the document. |
[out] | pBlockSize | Block size of incoming data block. |
[out] | pBlockIndex | Block index of incoming data block. |
- Returns
- IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.
◆ otaClose()
Close an open OTA file context and free it.
- Parameters
-
[in] | pFileContext | Information of file to be streamed. |
- Returns
- true if successful, false otherwise.
◆ otaTimerCallback()
OTA Timer callback.
- Parameters
-
[in] | otaTimerId | Reference to the timer to use. |
◆ setImageStateWithReason()
Internal function to set the image state including an optional reason code.
- Parameters
-
[in] | stateToSet | State to set. |
[in] | reasonToSet | Reason to set. |
- Returns
- OtaErr_t OtaErrNone if successful, other codes on failure.
◆ updateJobStatusFromImageState()
Internal function to update the job status to the jobs service from current image state.
- Parameters
-
[in] | state | State to set. |
[in] | subReason | Reason for status. |
- Returns
- OtaErr_t OtaErrNone if successful, other codes on failure.
◆ initDocModel()
Prepare the document model for use by sanity checking the initialization parameters and detecting all required parameters.
- Parameters
-
[in,out] | pDocModel | Details of expected parameters in the job doc. |
[in] | pBodyDef | Structure to store the details of keys and where to store them. |
[in] | contextBaseAddr | Start of file context. |
[in] | contextSize | Size of file context. |
[in] | numJobParams | Number of parameters to be extracted. |
- Returns
- DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
◆ initializeAppBuffers()
Initialize buffers for storing the file attributes.
- Parameters
-
[out] | pOtaBuffer | OTA 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] | pEventMsg | Incoming 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()
Validate update version when receiving job doc in self test state.
- Parameters
-
[in] | pFileContext | Stores file information. |
◆ processNullFileContext()
static OtaErr_t processNullFileContext |
( |
void |
| ) |
|
|
static |
Handle invalid file context.
- Returns
- OtaErr_t OtaErrNone if job parsing is handled.
◆ platformInSelftest()
static bool platformInSelftest |
( |
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] | pEventMsg | Stores information of the event. |
◆ freeFileContextMem()
Free or clear multiple buffers used in the file context.
- Parameters
-
[in] | pFileContext | Information of file to be streamed. |
◆ handleJobParsingError()
Handle job parsing error.
- Parameters
-
[in] | pFileContext | Pointer to the file context. |
[in] | err | Parsing error of type OtaJobParseErr_t. |
◆ receiveAndProcessOtaEvent()
static void receiveAndProcessOtaEvent |
( |
void |
| ) |
|
|
static |
Receive and process the next available event from the event queue.
Each event is processed based on the behavior defined in the OTA transition table. The state of the OTA state machine will be updated and the corresponding event handler will be called.
◆ startHandler()
Start timers and initiate request for job document.
◆ requestJobHandler()
Initiate a request for a job.
◆ processJobHandler()
Update file context from job document.
◆ inSelfTestHandler()
◆ initFileHandler()
Initialize and handle file transfer.
◆ processDataHandler()
Process incoming data blocks.
◆ requestDataHandler()
◆ shutdownHandler()
Shutdown OTA and cleanup.
◆ closeFileHandler()
Close file opened for download.
◆ userAbortHandler()
Handle user interrupt to abort task.
◆ suspendHandler()
Handle suspend event for OTA agent.
◆ resumeHandler()
Resume from a suspended state.
◆ jobNotificationHandler()
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] | pUnused | Can 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. |
For a Posix based reference of creating a thread with this task, please see the demos in AWS IoT Embedded C SDK repository.
◆ OTA_SignalEvent()
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] | pEventMsg | Event to be added to the queue |
- Returns
- true If operation is successful, false If the event can not be added
Example Signal OTA agent that a new file block has been received over the http connection.
OtaHttpStatus_t handleDataFromHTTPService(
const HTTPResponse_t * pResponse )
{
bool result = false;
if( pData != NULL )
{
memcpy( pData->
data, pResponse->pBody, pResponse->bodyLen );
eventMsg.pEventData = pData;
if( result )
{
}
}
return returnValue;
}
◆ OTA_Init()
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] | pOtaBuffer | Buffers used by the agent to store different params. |
[in] | pOtaInterfaces | A pointer to the OS context. |
[in] | pThingName | A pointer to a C string holding the Thing name. |
[in] | OtaAppCallback | Static 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.
Example
const void * pData );
{
.updateFilePathsize = OTA_MAX_FILE_PATH_SIZE,
.pCertFilePath = certFilePath,
.certFilePathSize = OTA_MAX_FILE_PATH_SIZE,
.pDecodeMemory = decodeMem,
.decodeMemorySize = otaconfigFILE_BLOCK_SIZE,
.pFileBitmap = bitmap,
.pUrl = updateUrl,
.urlSize = OTA_MAX_URL_SIZE,
.pAuthScheme = authScheme,
.authSchemeSize = OTA_MAX_AUTH_SCHEME_SIZE
};
{
.os.event.send = Posix_OtaSendEvent;
...
.mqtt.subscribe = mqttSubscribe;
.mqtt.publish = mqttPublish;
.mqtt.unsubscribe = mqttUnsubscribe;
.http.init = httpInit;
.http.request = httpRequest;
.http.deinit = httpDeinit;
.pal.getPlatformImageState = otaPal_GetPlatformImageState;
.pal.setPlatformImageState = otaPal_SetPlatformImageState;
}
char * pClientIdentifier = "uniqueClientID";
&otaInterfaces,
( const uint8_t * ) pClientIdentifier,
{
}
◆ OTA_Shutdown()
OtaState_t OTA_Shutdown |
( |
uint32_t |
ticksToWait, |
|
|
uint8_t |
unsubscribeFlag |
|
) |
| |
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] | ticksToWait | The 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. The agent does not sleep for this while but used for busy looping. |
[in] | unsubscribeFlag | Flag to indicate if unsubscribe operations should be performed from the job topics when shutdown is called. If the flag is 0 then unsubscribe operations are not called for job topics If application requires it to be unsubscribed from the job topics then flag must be set to 1 when calling OTA_Shutdown. |
- 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.
Example
uint32_t ticksToWait = 100;
uint8_t unsubscribe = 1;
...
{
}
◆ OTA_GetState()
Get the current state of the OTA agent.
- Returns
- The current state of the OTA agent.
Example Check if OTA agent is in suspended state.
while( state != OtaAgentStateSuspended )
{
}
◆ OTA_GetStatistics()
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.
Example
{
printf( " Received: %u Queued: %u Processed: %u Dropped: %u",
}
◆ OTA_CheckForUpdate()
Request for the next available OTA job from the job service.
- Returns
- OtaErrNone if successful, otherwise an error code prefixed with 'OtaErr' from the list above.
◆ OTA_ActivateNewImage()
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 'OtaErr' from the list above.
Example
const void * pData )
{
{
{
}
}
}
◆ OTA_SetImageState()
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] | state | The state to set of the OTA image. |
- Returns
- OtaErrNone if successful, otherwise an error code prefixed with 'OtaErr' from the list above.
Example Set image state to reflect new image is accepted in application callback.
const void * pData )
{
{
{
}
}
}
◆ OTA_GetImageState()
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()
Suspend OTA agent operations .
- Returns
- OtaErrNone if successful, otherwise an error code prefixed with 'OtaErr' from the list above.
Example Suspend the OTA agent when a network error occurs.
void handleNetworkErrors()
{
int16_t suspendTimeout = 5000U;
{
}
else
{
&& ( suspendTimeout > 0 ) )
{
portSleep( 1000U );
suspendTimeout -= 1000U;
}
{
}
}
}
◆ OTA_Resume()
Resume OTA agent operations .
- Returns
- OtaErrNone if successful, otherwise an error code prefixed with 'OtaErr' from the list above.
Example Resume the OTA agent after the network errors are resolved.
bool handleReconnect()
{
bool returnStatus = establishConnection();
if( returnStatus == EXIT_SUCCESS )
{
{
}
else
{
}
returnStatus = false;
}
return returnStatus;
}
◆ OTA_Err_strerror()
const char* OTA_Err_strerror |
( |
OtaErr_t |
err | ) |
|
Error code to string conversion for OTA errors.
- Parameters
-
[in] | err | The error to convert to a string. |
- Returns
- The string representation of the error.
◆ OTA_JobParse_strerror()
Error code to string conversion for OTA Job Parsing errors.
- Parameters
-
[in] | err | The error to convert to a string. |
- Returns
- The string representation of the error.
◆ OTA_OsStatus_strerror()
Status code to string conversion for OTA OS status.
- Parameters
-
[in] | status | The status to convert to a string. |
- Returns
- The string representation of the status.
◆ OTA_PalStatus_strerror()
Status code to string conversion for OTA PAL status.
- Parameters
-
[in] | status | The status to convert to a string. |
- Returns
- The string representation of the status.
◆ otaAgent
Initial value:=
{
OtaAgentStateStopped,
{ 0 },
{ 0 },
0,
0,
{ 0 },
NULL,
0,
1,
{ 0 },
0,
NULL,
NULL,
1
}
This is THE OTA agent context and initialization state.
◆ otaTransitionTable
Initial value:
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
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.
◆ otaJobDocModelParamStructure
Initial value:
This is the OTA job document model describing the parameters, their types, destination and how to extract.
◆ pJobNameBuffer
Buffer to store job name.
◆ pProtocolBuffer
Buffer to store data protocol.
◆ sig256Buffer
Buffer to store key file signature.
OtaState_t
OTA Agent states.
Definition: ota.h:114
OtaErr_t OTA_Resume(void)
Resume OTA agent operations .
Definition: ota.c:3398
@ OtaAgentEventCreateFile
Event to create a file.
Definition: ota_private.h:350
OtaInitEvent_t init
Initialization event.
Definition: ota_os_interface.h:263
#define OTA_DONT_STORE_PARAM
If destOffset in the model is 0xffffffff, do not store the value.
Definition: ota_private.h:81
static OtaErr_t requestJobHandler(const OtaEventData_t *pEventData)
Definition: ota.c:830
#define OTA_JSON_FILE_CERT_NAME_KEY
Location of the certificate on the device to find code signing.
Definition: ota_private.h:154
#define OTA_JSON_JOB_ID_KEY
Name of the job.
Definition: ota_private.h:139
OtaOSInterface_t os
OS interface to store event, timers and memory operations.
Definition: ota.h:258
OTA File Context Information.
Definition: ota_private.h:382
static OtaErr_t inSelfTestHandler(const OtaEventData_t *pEventData)
Definition: ota.c:788
@ OtaJobEventStartTest
OTA job is now in self test, perform user tests.
Definition: ota.h:168
@ OtaAgentEventSuspend
Event to suspend ota task.
Definition: ota_private.h:355
#define OTA_JSON_TIMESTAMP_KEY
Used to calculate timeout and time spent on the operation.
Definition: ota_private.h:137
uint32_t dataLength
Definition: ota_private.h:424
static OtaErr_t requestDataHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1083
OtaErr_t OTA_SetImageState(OtaImageState_t state)
Set the state of the current MCU image.
Definition: ota.c:3300
#define OTA_JSON_STREAM_NAME_KEY
Name of the stream used for download.
Definition: ota_private.h:149
This is the OTA statistics structure to hold useful info.
Definition: ota_private.h:291
OtaJobEvent_t
OTA Job callback events.
Definition: ota.h:165
@ OtaAgentEventStart
Start the OTA state machine.
Definition: ota_private.h:346
OtaErr_t
The OTA API return status. OTA agent error codes are in the upper 8 bits of the 32 bit OTA error word...
Definition: ota.h:79
@ OtaAgentEventRequestFileBlock
Event to request file blocks.
Definition: ota_private.h:351
@ OtaImageStateAccepted
The state of the OTA MCU Image post successful download and successful self_test.
Definition: ota_private.h:317
uint32_t otaPacketsDropped
Definition: ota_private.h:295
static OtaErr_t suspendHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1339
OtaEventInterface_t event
OTA Event interface.
Definition: ota_os_interface.h:306
uint8_t data[OTA_DATA_BLOCK_SIZE]
Definition: ota_private.h:423
#define OTA_JSON_PROTOCOLS_KEY
Protocols over which the download can take place.
Definition: ota_private.h:147
static OtaErr_t processDataHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1165
@ OtaAgentEventRequestJobDocument
Event for requesting job document.
Definition: ota_private.h:348
@ OtaAgentEventShutdown
Event to trigger ota shutdown.
Definition: ota_private.h:358
OtaErr_t OTA_ActivateNewImage(void)
Activate the newest MCU image received via OTA.
Definition: ota.c:3264
uint32_t otaPacketsReceived
Definition: ota_private.h:292
The OTA Agent event and data structures.
Definition: ota_private.h:422
#define OTA_STORE_NESTED_JSON
Store the reference to a nested JSON in a separate pointer.
Definition: ota_private.h:82
#define OTA_JSON_CLIENT_TOKEN_KEY
Client token.
Definition: ota_private.h:136
#define OTA_JSON_FILE_ATTRIBUTE_KEY
Additional file attributes.
Definition: ota_private.h:153
uint8_t * pUpdateFilePath
Path to store the files.
Definition: ota.h:272
static OtaErr_t startHandler(const OtaEventData_t *pEventData)
Definition: ota.c:761
#define OTA_JSON_JOB_DOC_KEY
Parameters that specify the nature of the job.
Definition: ota_private.h:145
bool OTA_SignalEvent(const OtaEventMsg_t *const pEventMsg)
Signal event to the OTA Agent task.
Definition: ota.c:2921
@ OtaErrUninitialized
The error code has not yet been set by a logic path.
Definition: ota.h:81
OtaState_t OTA_Shutdown(uint32_t ticksToWait, uint8_t unsubscribeFlag)
Signal to the OTA Agent to shut down.
Definition: ota.c:3156
OTA Interface for referencing different components.
Definition: ota.h:257
uint32_t otaPacketsQueued
Definition: ota_private.h:293
@ OtaAgentEventReceivedFileBlock
Event to trigger when file block is received.
Definition: ota_private.h:352
static OtaErr_t resumeHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1349
#define OTA_JSON_FILE_PATH_KEY
Path to store the image on the device.
Definition: ota_private.h:150
#define OTA_JOB_PARAM_OPTIONAL
Used to denote an optional document model parameter.
Definition: ota_private.h:80
#define OTA_JSON_AUTH_SCHEME_KEY
Authentication scheme for downloading a the image over HTTP.
Definition: ota_private.h:156
@ OtaAgentEventResume
Event to resume suspended task.
Definition: ota_private.h:356
OtaEvent_t eventId
Definition: ota_private.h:436
uint32_t otaPacketsProcessed
Definition: ota_private.h:294
static OtaErr_t initFileHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1012
OtaErr_t OTA_Suspend(void)
Suspend OTA agent operations .
Definition: ota.c:3365
@ OtaErrNone
No error occurred during the operation.
Definition: ota.h:80
OtaErr_t OTA_Init(OtaAppBuffer_t *pOtaBuffer, const OtaInterfaces_t *pOtaInterfaces, const uint8_t *pThingName, OtaAppCallback_t OtaAppCallback)
OTA Agent initialization function.
Definition: ota.c:3062
@ OtaImageStateUnknown
The initial state of the OTA MCU Image.
Definition: ota_private.h:315
Stores information about the event message.
Definition: ota_private.h:434
@ OtaHttpSuccess
OTA HTTP interface success.
Definition: ota_http_interface.h:87
#define OTA_JSON_FILE_GROUP_KEY
Parameters for specifying file configurations.
Definition: ota_private.h:148
@ OtaAgentEventCloseFile
Event to trigger closing file.
Definition: ota_private.h:354
#define OTA_JSON_UPDATE_DATA_URL_KEY
S3 bucket presigned url to fetch the image from .
Definition: ota_private.h:155
#define OTA_JSON_OTA_UNIT_KEY
afr-ota.
Definition: ota_private.h:146
#define OTA_JSON_STATUS_DETAILS_KEY
Current status of the job.
Definition: ota_private.h:140
#define OTA_JSON_SELF_TEST_KEY
Specifies if the platform and service is is selftest.
Definition: ota_private.h:141
#define OTA_JSON_FILE_ID_KEY
Used to identify the file in case of multiple file downloads.
Definition: ota_private.h:152
#define OTA_JSON_UPDATED_BY_KEY
Parameter to specify update status.
Definition: ota_private.h:142
@ OtaAgentEventRequestTimer
Event to request event timer.
Definition: ota_private.h:353
@ OtaAgentEventReceivedJobDocument
Event when job document is received.
Definition: ota_private.h:349
@ OtaErrActivateFailed
Failed to activate the new image.
Definition: ota.h:102
#define OTA_JSON_EXECUTION_KEY
Contains job execution parameters .
Definition: ota_private.h:138
#define OTA_MAX_BLOCK_BITMAP_SIZE
Max allowed number of bytes to track all blocks of an OTA file. Adjust block size if more range is ne...
Definition: ota_private.h:64
OtaErr_t OTA_GetStatistics(OtaAgentStatistics_t *pStatistics)
Get the statistics of OTA message packets.
Definition: ota.c:3223
@ OtaHttpRequestFailed
Error sending the HTTP request.
Definition: ota_http_interface.h:90
#define OTA_JSON_FILE_SIZE_KEY
Size of the file to be downloaded.
Definition: ota_private.h:151
static OtaErr_t closeFileHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1287
OtaState_t OTA_GetState(void)
Get the current state of the OTA agent.
Definition: ota.c:3215
static OtaErr_t processJobHandler(const OtaEventData_t *pEventData)
Definition: ota.c:980
@ OtaAgentEventStartSelfTest
Event to trigger self test.
Definition: ota_private.h:347
#define OTA_JSON_FILETYPE_KEY
Used to identify the file in case of multi file type support.
Definition: ota_private.h:157
static OtaErr_t userAbortHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1300
static OtaErr_t jobNotificationHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1363
#define OTA_JOB_PARAM_REQUIRED
Used to denote a required document model parameter.
Definition: ota_private.h:79
OtaHttpStatus_t
The OTA HTTP interface return status.
Definition: ota_http_interface.h:86
static OtaErr_t shutdownHandler(const OtaEventData_t *pEventData)
Definition: ota.c:1324
const char OTA_JsonFileSignatureKey[OTA_FILE_SIG_KEY_STR_MAX_LENGTH]
The OTA signature algorithm string is specified by the PAL.
@ OtaAgentEventUserAbort
Event triggered by user to stop agent.
Definition: ota_private.h:357
#define U16_OFFSET(type, member)
Offset helper.
Definition: ota.c:75
@ OtaJobEventActivate
OTA receive is authenticated and ready to activate.
Definition: ota.h:166
OTA Application Buffer size information.
Definition: ota.h:271