Skip to content

Instantly share code, notes, and snippets.

@ahmedwahdan
Created October 2, 2019 06:20
Show Gist options
  • Save ahmedwahdan/606bc99e9b2a26b3f07f8ff1ee2bef6e to your computer and use it in GitHub Desktop.
Save ahmedwahdan/606bc99e9b2a26b3f07f8ff1ee2bef6e to your computer and use it in GitHub Desktop.
GreenGrass_With_OTA
/*
* Amazon FreeRTOS V201906.00 Major
* Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file aws_greengrass_discovery_demo.c
* @brief A simple Greengrass discovery example.
*
* A simple example that perform discovery of the greengrass core device.
* The JSON file is retrieved.
*/
/* Standard includes. */
#include "iot_config.h"
/* MQTT include. */
#include "iot_mqtt.h"
#include "iot_mqtt_agent.h"
/* Demo includes. */
#include "aws_demo_config.h"
/* Standard includes. */
#include <stdio.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "platform/iot_network.h"
/* Greengrass includes. */
#include "aws_ggd_config.h"
#include "aws_ggd_config_defaults.h"
#include "aws_greengrass_discovery.h"
/* Demo network handling */
#include "aws_iot_demo_network.h"
/* Required to get the broker address and port. */
#include "aws_clientcredential.h"
/* Amazon FreeRTOS OTA agent includes. */
#include "aws_iot_ota_agent.h"
#include "iot_network_manager_private.h"
/* Required for demo task stack and priority */
#include "aws_demo_config.h"
#include "aws_application_version.h"
#define otaDemoCONN_TIMEOUT_MS ( 2000UL )
#define otaDemoCONN_RETRY_INTERVAL_MS ( 5000 )
#define otaDemoCONN_RETRY_LIMIT ( 100 )
#define otaDemoKEEPALIVE_SECONDS ( 1200 )
#define myappONE_SECOND_DELAY_IN_TICKS pdMS_TO_TICKS( 10000UL )
#define otaDemoNETWORK_TYPES ( AWSIOT_NETWORK_TYPE_ALL )
#define ggdDEMO_MAX_MQTT_MESSAGES 3
#define ggdDEMO_MAX_MQTT_MSG_SIZE 500
#define ggdDEMO_DISCOVERY_FILE_SIZE 2500
#define ggdDEMO_MQTT_MSG_TOPIC "freertos/demos/ggd"
#define ggdDEMO_MQTT_MSG_DISCOVERY "{\"message\":\"Hello #%lu from Amazon FreeRTOS to Greengrass Core.\"}"
/**
* @brief Contains the user data for callback processing.
*/
typedef struct
{
const char * pcExpectedString; /**< Informs the MQTT callback of the next expected string. */
BaseType_t xCallbackStatus; /**< Used to communicate the success or failure of the callback function.
* xCallbackStatus is set to pdFALSE before the callback is executed, and is
* set to pdPASS inside the callback only if the callback receives the expected
* data. */
SemaphoreHandle_t xWakeUpSemaphore; /**< Handle of semaphore to wake up the task. */
char * pcTopic; /**< Topic to subscribe and publish to. */
} GGDUserData_t;
/* The maximum time to wait for an MQTT operation to complete. Needs to be
* long enough for the TLS negotiation to complete. */
static const TickType_t xMaxCommandTime = pdMS_TO_TICKS( 20000UL );
static const TickType_t xTimeBetweenPublish = pdMS_TO_TICKS( 1200UL );
static char pcJSONFile[ ggdDEMO_DISCOVERY_FILE_SIZE ];
/*
* The MQTT client used for all the publish and subscribes.
*/
static MQTTAgentHandle_t xMQTTClientHandle;
static BaseType_t prvMQTTConnect( GGD_HostAddressData_t * pxHostAddressData );
static void prvSendMessageToGGC( GGD_HostAddressData_t * pxHostAddressData );
static void prvDiscoverGreenGrassCore( void * pvParameters );
static IotNetworkError_t prvNetworkDisconnectCallback( void * pvContext );
/*-----------------------------------------------------------*/
static MqttConnectionContext_t xConnection =
{
.pvNetworkConnection = NULL,
.ulNetworkType = AWSIOT_NETWORK_TYPE_NONE,
.xNetworkInfo = IOT_MQTT_NETWORK_INFO_INITIALIZER,
.xMqttConnection = IOT_MQTT_CONNECTION_INITIALIZER,
.xDisconnectCallback = prvNetworkDisconnectCallback
};
static void App_OTACompleteCallback( OTA_JobEvent_t eEvent );
static void App_OTACompleteCallback( OTA_JobEvent_t eEvent )
{
OTA_Err_t xErr = kOTA_Err_Uninitialized;
/* OTA job is completed. so delete the MQTT and network connection. */
if( eEvent == eOTA_JobEvent_Activate )
{
configPRINTF( ( "Received eOTA_JobEvent_Activate callback from OTA Agent.\r\n" ) );
IotMqtt_Disconnect( xConnection.xMqttConnection, 0 );
#if defined( CONFIG_OTA_UPDATE_DEMO_ENABLED )
vMqttDemoDeleteNetworkConnection( &xConnection );
#endif
OTA_ActivateNewImage();
}
else if( eEvent == eOTA_JobEvent_Fail )
{
configPRINTF( ( "Received eOTA_JobEvent_Fail callback from OTA Agent.\r\n" ) );
/* Nothing special to do. The OTA agent handles it. */
}
else if( eEvent == eOTA_JobEvent_StartTest )
{
/* This demo just accepts the image since it was a good OTA update and networking
* and services are all working (or we wouldn't have made it this far). If this
* were some custom device that wants to test other things before calling it OK,
* this would be the place to kick off those tests before calling OTA_SetImageState()
* with the final result of either accepted or rejected. */
configPRINTF( ( "Received eOTA_JobEvent_StartTest callback from OTA Agent.\r\n" ) );
xErr = OTA_SetImageState( eOTA_ImageState_Accepted );
if( xErr != kOTA_Err_None )
{
OTA_LOG_L1( " Error! Failed to set image state as accepted.\r\n" );
}
}
}
static const char * pcStateStr[ eOTA_NumAgentStates ] =
{
"Not Ready",
"Ready",
"Active",
"Shutting down"
};
IotMqttConnection_t MQTT_AGENT_Getv2Connection( MQTTAgentHandle_t xMQTTHandle );
void OTA_Init( void)
{
configPRINTF( ( "OTA demo version %u.%u.%u\r\n",
xAppFirmwareVersion.u.x.ucMajor,
xAppFirmwareVersion.u.x.ucMinor,
xAppFirmwareVersion.u.x.usBuild ) );
/* OTA agent init */
configPRINTF( ( "WAHDAN : vRunOTAUpdateDemo : Start \r\n" ) );
configPRINTF( ( "WAHDAN : vRunOTAUpdateDemo : IotMqtt_Connect() connecto to broker \r\n" ) );
configPRINTF( ( "WAHDAN : vRunOTAUpdateDemo : IotMqtt_Connect() connecto to broker \r\n" ) );
/* Get the MQTT V2 instance of the MQTT Agent handler */
IotMqttConnection_t xMqttConnection = MQTT_AGENT_Getv2Connection( xMQTTClientHandle );
OTA_AgentInit( xMqttConnection, ( const uint8_t * ) ( clientcredentialIOT_THING_NAME ), App_OTACompleteCallback, ( TickType_t ) ~0 );
}
static void prvSendMessageToGGC( GGD_HostAddressData_t * pxHostAddressData )
{
const char * pcTopic = ggdDEMO_MQTT_MSG_TOPIC;
MQTTAgentPublishParams_t xPublishParams;
MQTTAgentReturnCode_t xReturnCode;
uint32_t ulMessageCounter = 0;
char cBuffer[ ggdDEMO_MAX_MQTT_MSG_SIZE ];
OTA_State_t eState;
if( prvMQTTConnect( pxHostAddressData ) == pdPASS )
{
/* Publish to the topic to which this task is subscribed in order
* to receive back the data that was published. */
//( void ) xTaskCreate( OTA_Run, "OTA", democonfigGREENGRASS_DISCOVERY_TASK_STACK_SIZE/2, NULL, democonfigDEMO_PRIORITY - 2, NULL );
OTA_Init();
for( ; ; ulMessageCounter++ )
{
xPublishParams.xQoS = eMQTTQoS0;
xPublishParams.pucTopic = ( const uint8_t * ) pcTopic;
xPublishParams.usTopicLength = ( uint16_t ) ( strlen( pcTopic ) );
xPublishParams.ulDataLength = ( uint32_t ) sprintf( cBuffer, ggdDEMO_MQTT_MSG_DISCOVERY, ( long unsigned int ) ulMessageCounter ); /*lint !e586 sprintf can be used for specific demo. */
xPublishParams.pvData = cBuffer;
//xReturnCode = MQTT_AGENT_Publish( xMQTTClientHandle,
// &xPublishParams,
// xMaxCommandTime );
if( ( eState = OTA_GetAgentState() ) != eOTA_AgentState_NotReady )
{
/* Wait forever for OTA traffic but allow other tasks to run and output statistics only once per second. */
configPRINTF( ( "WAHDAN : vRunOTAUpdateDemo : Inside the while loop \r\n" ) );
configPRINTF( ( "State: %s Received: %u Queued: %u Processed: %u Dropped: %u\r\n", pcStateStr[ eState ],
OTA_GetPacketsReceived(), OTA_GetPacketsQueued(), OTA_GetPacketsProcessed(), OTA_GetPacketsDropped() ) );
}
vTaskDelay( xTimeBetweenPublish );
}
configPRINTF( ( "Disconnecting from broker.\r\n" ) );
if( MQTT_AGENT_Disconnect( xMQTTClientHandle,
xMaxCommandTime ) == eMQTTAgentSuccess )
{
configPRINTF( ( "Disconnected from the broker.\r\n" ) );
if( MQTT_AGENT_Delete( xMQTTClientHandle ) == eMQTTAgentSuccess )
{
configPRINTF( ( "Deleted Client.\r\n" ) );
}
else
{
configPRINTF( ( "ERROR: MQTT_AGENT_Delete() Failed.\r\n" ) );
}
}
else
{
configPRINTF( ( "ERROR: Did not disconnected from the broker.\r\n" ) );
}
}
}
/*-----------------------------------------------------------*/
static BaseType_t prvMQTTConnect( GGD_HostAddressData_t * pxHostAddressData )
{
MQTTAgentConnectParams_t xConnectParams;
BaseType_t xResult = pdPASS;
/* Connect to the broker. */
xConnectParams.pucClientId = ( const uint8_t * ) ( clientcredentialIOT_THING_NAME );
xConnectParams.usClientIdLength = ( uint16_t ) ( strlen( clientcredentialIOT_THING_NAME ) );
xConnectParams.pcURL = pxHostAddressData->pcHostAddress;
xConnectParams.usPort = clientcredentialMQTT_BROKER_PORT;
xConnectParams.xFlags = mqttagentREQUIRE_TLS | mqttagentURL_IS_IP_ADDRESS;
xConnectParams.xURLIsIPAddress = pdTRUE; /* Deprecated. */
xConnectParams.pcCertificate = pxHostAddressData->pcCertificate;
xConnectParams.ulCertificateSize = pxHostAddressData->ulCertificateSize;
xConnectParams.pvUserData = NULL;
xConnectParams.pxCallback = NULL;
xConnectParams.xSecuredConnection = pdTRUE; /* Deprecated. */
if( MQTT_AGENT_Connect( xMQTTClientHandle,
&xConnectParams,
xMaxCommandTime ) != eMQTTAgentSuccess )
{
configPRINTF( ( "ERROR: Could not connect to the Broker.\r\n" ) );
xResult = pdFAIL;
}
return xResult;
}
/*-----------------------------------------------------------*/
static void prvDiscoverGreenGrassCore( void * pvParameters )
{
GGD_HostAddressData_t xHostAddressData;
( void ) pvParameters;
/* Create MQTT Client. */
if( MQTT_AGENT_Create( &( xMQTTClientHandle ) ) == eMQTTAgentSuccess )
{
memset( &xHostAddressData, 0, sizeof( xHostAddressData ) );
/* Demonstrate automated connection. */
configPRINTF( ( "Attempting automated selection of Greengrass device\r\n" ) );
if( GGD_GetGGCIPandCertificate( pcJSONFile,
ggdDEMO_DISCOVERY_FILE_SIZE,
&xHostAddressData )
== pdPASS )
{
configPRINTF( ( "Greengrass device discovered.\r\n" ) );
configPRINTF( ( "Establishing MQTT communication to Greengrass...\r\n" ) );
prvSendMessageToGGC( &xHostAddressData );
/* Report on space efficiency of this demo task. */
#if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 )
{
configPRINTF( ( "Heap low watermark: %u. Stack high watermark: %u.\r\n",
xPortGetMinimumEverFreeHeapSize(),
uxTaskGetStackHighWaterMark( NULL ) ) );
}
#endif
}
else
{
configPRINTF( ( "Auto-connect: Failed to retrieve Greengrass address and certificate.\r\n" ) );
}
}
configPRINTF( ( "----Demo finished----\r\n" ) );
vTaskDelete( NULL );
}
/*-----------------------------------------------------------*/
int vStartGreenGrassDiscoveryTask( bool awsIotMqttMode,
const char * pIdentifier,
void * pNetworkServerInfo,
void * pNetworkCredentialInfo,
const IotNetworkInterface_t * pNetworkInterface )
{
/* Unused parameters */
( void ) awsIotMqttMode;
( void ) pIdentifier;
( void ) pNetworkServerInfo;
( void ) pNetworkCredentialInfo;
( void ) pNetworkInterface;
prvDiscoverGreenGrassCore( NULL );
return 0;
}
@Prabhuelectro
Copy link

Where the main code start ?
How to write custom codes for esp32 ?
can you help me to use amazon freertos with esp32 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment