Sanjai S
Sanjai S

Reputation: 1

ESP32 is getting crashed while receiving from the topic

I am learning AWS IoT to publish and subscribe from and to my PC, through ESP32 Dev kit, and had written a simple program to publish an information from my PC and subscribing to shadow topic and receiving, but publishing is not happening properly. As I'm new, I could not find a solution for it. I'll attach the code for reference.

(Edit) The code has been modified with software timers for better functioning

#include "aws.h"  //all header files are declared

extern const char *wifi_ssid;
extern const char *wifi_pw;
extern const char *AWS_CERT_CA; 
extern const char *AWS_CERT_CRT;
extern const char *AWS_CERT_PRIVATE;  //all certs are in seperate C file

int retry;
esp_timer_create_args_t timer;
esp_timer_handle_t retry_timer = NULL;

char *createJSON()
{
    cJSON *object = cJSON_CreateObject();
    cJSON *state = cJSON_CreateObject();
    cJSON *desired = cJSON_CreateObject();

    cJSON_AddNumberToObject(desired,"temperature",98.6);
    cJSON_AddStringToObject(desired,"status","Normal");
    cJSON_AddItemToObject(state,"desired",desired);
    cJSON_AddItemToObject(object,"state",state);

    return cJSON_PrintUnformatted(object);
}

void debriefJSON(cJSON *r_obj)
{
    cJSON *stt = cJSON_GetObjectItem(r_obj,"state");
    cJSON *des = cJSON_GetObjectItem(stt,"desired");
    cJSON *tmp = cJSON_GetObjectItem(des,"temperature");
    cJSON *sts = cJSON_GetObjectItem(des,"status");

    if(stt == NULL)
    {
        printf("Error over first level\n");
        return;
    }
    else if(des == NULL)
    {
        printf("Error over second level\n");
        return;
    }
    else if(tmp == NULL || sts == NULL)
    {
        printf("Error over second sub-level\n");
        return;
    }

    printf("Temperature: %.1f °F\n",tmp -> valuedouble);
    printf("Status: %s\n",sts -> valuestring);
}

void timer_callback(void *arg)
{
    if (retry <= 5)
    {
        printf("Retrying Wi-Fi connection (attempt %d)...\n", retry++ + 1);
        esp_wifi_connect();
    }
    else
    {
        printf("Max retries reached. Restarting retry process...\n");
        retry = 0;
    }
}

static void wifi_event_handler(void *arg, esp_event_base_t eventbase, int32_t eventid, void *eventdata)
{
    switch(eventid)
    {
        case WIFI_EVENT_STA_START:
        {
            printf("WiFi is connecting .....\n");
            esp_wifi_connect();
            break;
        }
        case WIFI_EVENT_STA_CONNECTED:
        {
            printf("WiFi is connected .....\nSetting up MQTT .....\n");
            retry = 0;

            if (retry_timer)
            {
                esp_timer_stop(retry_timer);
                esp_timer_delete(retry_timer);
                retry_timer = NULL;
            }

            aws_set_up();
            break;
        }
        case WIFI_EVENT_STA_DISCONNECTED:
        {
            printf("WiFi is not connected .....\n");

            if(retry_timer == NULL)
            {
                timer.callback = &timer_callback;
                timer.arg = NULL;
                timer.dispatch_method = ESP_TIMER_TASK;
                timer.name = "retry_timer";
                esp_timer_create(&timer, &retry_timer);
            }

            if(retry <= 5)
            {
                esp_timer_start_once(retry_timer, 6000000);
            }
            else
            {
                esp_timer_start_once(retry_timer, 120000000);
            }
            break;
        }
        case IP_EVENT_STA_GOT_IP:
        {
            ip_event_got_ip_t *event = (ip_event_got_ip_t *)eventdata;
            printf("IP addr: "IPSTR"\n",IP2STR(&event -> ip_info.ip));
            break;
        }
    }
}

static void aws_event_handler(void *arg, esp_event_base_t eventbase, int32_t eventid, void *eventdata)
{
    esp_mqtt_event_handle_t event = (esp_mqtt_event_handle_t)eventdata;
    esp_mqtt_client_handle_t cln = event -> client;

    if(eventid == MQTT_EVENT_CONNECTED)
    {
        printf("Connected to broker\n");
        esp_mqtt_client_subscribe(cln, "$aws/things/<ThingName>/shadow/update/delta", 1);
        char *str = createJSON();
        esp_mqtt_client_publish(cln, "$aws/things/<ThingName>/shadow/update", str, 0, 1, 0);
        free(str);
    }
    else if(eventid == MQTT_EVENT_PUBLISHED)
    {
        printf("Published to topic\n");
    }        
    else if(eventid == MQTT_EVENT_SUBSCRIBED)
    {
        printf("Subscribed to topic\n");
    }
    else if(eventid == MQTT_EVENT_DATA)
    {
        printf("Message received\n");
        char *str = malloc(event -> data_len + 1);
        if(str == NULL)
        {
            printf("Error over pointer creation\n");
            return;
        }
        strncpy(str, event -> data, event -> data_len);
        cJSON *r_obj = cJSON_Parse(str);
        free(str);

        debriefJSON(r_obj);
        cJSON_Delete(r_obj);
    }
    else if(eventid == MQTT_EVENT_ERROR)
    {
        printf("Some error is happening .....\n");
    }
}

void wifi_set_up()
{
    esp_netif_init();
    esp_event_loop_create_default();
    esp_netif_create_default_wifi_sta();

    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL);
    esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL);

    wifi_init_config_t w_init_config = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&w_init_config);

    wifi_config_t w_config;
    memset(&w_config, 0, sizeof(wifi_config_t));
    strncpy((char *)w_config.sta.ssid, wifi_ssid, strlen(wifi_ssid) + 1);
    strncpy((char *)w_config.sta.password, wifi_pw, strlen(wifi_pw) + 1);
    w_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;

    esp_wifi_set_mode(WIFI_MODE_STA);
    esp_wifi_set_config(WIFI_IF_STA, &w_config);

    if(esp_wifi_start() == ESP_OK)
    {
        printf("WiFi is running ....\n");
    }
}

void aws_set_up()
{
    esp_mqtt_client_config_t a_config;
    memset(&a_config, 0, sizeof(esp_mqtt_client_config_t));
    a_config.broker.address.uri = //iot endpoint
    a_config.broker.verification.certificate = AWS_CERT_CA;
    a_config.credentials.authentication.certificate = AWS_CERT_CRT;
    a_config.credentials.authentication.key = AWS_CERT_PRIVATE;

    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&a_config);
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, aws_event_handler, client);
    esp_mqtt_client_start(client);
}

void app_main(void)
{
    nvs_flash_init();
    esp_timer_init();
    wifi_set_up();
}

Now, the publishing is irregular, and I can't find the problem.

Upvotes: 0

Views: 56

Answers (0)

Related Questions