Skip to content

Error in receiving published message

0

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 or understand what is happening behind. I'll attach the code for reference.

Code:

#include "aws.h"

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;

int retry;
wifi_config_t w_config;
esp_mqtt_client_config_t a_config;
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);
        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("Wi-Fi is connecting .....\n");
            esp_wifi_connect();
            break;
        }
        case WIFI_EVENT_STA_CONNECTED:
        {
            printf("Wi-Fi 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("Wi-Fi 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 address: "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/IoTDevice/shadow/update/delta", 1);
        char *str = createJSON();
        printf("%s\n",str);
        esp_mqtt_client_publish(cln, "$aws/things/IoTDevice/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);

    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;
    w_config.sta.listen_interval = 10;

    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()
{
    a_config.broker.address.uri = //own 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;
    a_config.session.keepalive = 120;
    a_config.network.disable_auto_reconnect = false;
    a_config.network.reconnect_timeout_ms = 5000;

    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();
}

The message I want to publish is:

{
  "state": {
    "desired": {
      "temperature": 98.6,
      "status": "Normal"
    }
  }
}

but the message getting actually published is:

{
  "version": 441,
  "timestamp": 1739775917,
  "state": {
    "temperature": 98.6,
    "status": "Normal"
  },
  "metadata": {
    "temperature": {
      "timestamp": 1739775917
    },
    "status": {
      "timestamp": 1739775917
    }
  }
}

leading to parsing errors, help is much appreciated, if the problem has been found or the things happen in behind is explained

1 Answer
1

Hi. Devices shouldn't set to the desired property. They should only set the reported property: https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-document.html#document-structure

The desired property is what the cloud app modifies to try to change the state of a device.

The shadow service will add metadata to the shadow document, as described in the link I've shared.

In general, shadows are not a good choice (in terms of cost) for reporting rapidly changing telemetry and sensor values. It's likely that temperature value is noisy and changing often. For that kind of data, you should publish to your own custom topic. Then you'll have full control over the payload.

AWS
EXPERT

answered 2 years ago

AWS
EXPERT

reviewed 2 years ago

  • Actually this was a part of bigger project of water level indicator. The thing is, I want to publish the data collected from the device to server in JSON format and device could receive OTA updates from the server, so in order to send and receive, I want to understand the structure of the concepts, through this example program. If you don't mine, can you explain further, in the context of the project, and also suggest to make this example program work

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.