Variables losing value

sagar448
Posts: 2
Joined: Thu Jul 25, 2019 11:31 pm

Variables losing value

Postby sagar448 » Thu Aug 22, 2019 8:46 pm

Hey Guys,

This is my first post so apologies if I don't explain well.

Long story short....I am doing an AWS Iot project, I generate the openssl certificates in my nodejs backend and then I use the http client on the esp32 to send a request to my backend to give the esp32 the certificates. Certificates arrive fine, I parse it with cJSON and I can print it out. I then store the certificate in a global variable and then pass it to a function in the xTaskCreate.

The problem is that variable I pass doesn't keep the certificate value, when I print it out after passing it, I see some corrupted gibberish. The variables are devName, devCert and devKey!

Here is my entire code
  1. /* ethernet Example
  2.  
  3.    This example code is in the Public Domain (or CC0 licensed, at your option.)
  4.  
  5.    Unless required by applicable law or agreed to in writing, this
  6.    software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  7.    CONDITIONS OF ANY KIND, either express or implied.
  8. */
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include "freertos/FreeRTOS.h"
  12. #include "freertos/task.h"
  13. #include "freertos/event_groups.h"
  14. #include "esp_system.h"
  15. #include "esp_event_loop.h"
  16. #include "esp_event.h"
  17. #include "esp_log.h"
  18. #include "esp_eth.h"
  19. #include "rom/gpio.h"
  20. #include "tcpip_adapter.h"
  21. #include "driver/gpio.h"
  22. #include "driver/periph_ctrl.h"
  23. #include "eth_phy/phy_lan8720.h"
  24. #include "esp_http_client.h"
  25. #include "cJSON.h"
  26. #include <sys/unistd.h>
  27. #include <sys/stat.h>
  28. #include "esp_err.h"
  29. #include "esp_spiffs.h"
  30.  
  31. const int CONNECTED_BIT = BIT0;
  32. char *devKey = NULL;
  33. char *devCert = NULL;
  34. char *devName = NULL;
  35. int val = 0;
  36. static EventGroupHandle_t ethernet_event_group;
  37.  
  38. #define DEFAULT_ETHERNET_PHY_CONFIG phy_lan8720_default_ethernet_config
  39. static const char *TAG = "Spacr";
  40. #define PIN_PHY_POWER 12
  41. #define PIN_SMI_MDC 23
  42. #define PIN_SMI_MDIO 18
  43.  
  44.  
  45. static void phy_device_power_enable_via_gpio(bool enable)
  46. {
  47.     assert(DEFAULT_ETHERNET_PHY_CONFIG.phy_power_enable);
  48.  
  49.     if (!enable) {
  50.         DEFAULT_ETHERNET_PHY_CONFIG.phy_power_enable(false);
  51.     }
  52.     gpio_pad_select_gpio(PIN_PHY_POWER);
  53.     gpio_set_direction(PIN_PHY_POWER, GPIO_MODE_OUTPUT);
  54.     if (enable == true) {
  55.         gpio_set_level(PIN_PHY_POWER, 1);
  56.         ESP_LOGI(TAG, "Power On Ethernet PHY");
  57.     } else {
  58.         gpio_set_level(PIN_PHY_POWER, 0);
  59.         ESP_LOGI(TAG, "Power Off Ethernet PHY");
  60.     }
  61.     vTaskDelay(1);
  62.  
  63.     if (enable) {
  64.         DEFAULT_ETHERNET_PHY_CONFIG.phy_power_enable(true);
  65.     }
  66. }
  67.  
  68. //Setting up ethernet RMII mode
  69. static void eth_gpio_config_rmii(void)
  70. {
  71.     phy_rmii_configure_data_interface_pins();
  72.     phy_rmii_smi_configure_pins(PIN_SMI_MDC, PIN_SMI_MDIO);
  73. }
  74.  
  75. //This is the function callback for ethernet events e.g. Ethernet Down, up etc.
  76. static esp_err_t eth_event_handler(void *ctx, system_event_t *event)
  77. {
  78.     tcpip_adapter_ip_info_t ip;
  79.  
  80.     switch (event->event_id) {
  81.     case SYSTEM_EVENT_ETH_CONNECTED:
  82.         ESP_LOGI(TAG, "Ethernet Link Up");
  83.         break;
  84.     case SYSTEM_EVENT_ETH_DISCONNECTED:
  85.         ESP_LOGI(TAG, "Ethernet Link Down");
  86.         break;
  87.     case SYSTEM_EVENT_ETH_START:
  88.         ESP_LOGI(TAG, "Ethernet Started");
  89.         break;
  90.     case SYSTEM_EVENT_ETH_GOT_IP:
  91.         memset(&ip, 0, sizeof(tcpip_adapter_ip_info_t));
  92.         ESP_ERROR_CHECK(tcpip_adapter_get_ip_info(ESP_IF_ETH, &ip));
  93.         ESP_LOGI(TAG, "Ethernet Got IP Addr");
  94.         ESP_LOGI(TAG, "~~~~~~~~~~~");
  95.         ESP_LOGI(TAG, "ETHIP:" IPSTR, IP2STR(&ip.ip));
  96.         ESP_LOGI(TAG, "ETHMASK:" IPSTR, IP2STR(&ip.netmask));
  97.         ESP_LOGI(TAG, "ETHGW:" IPSTR, IP2STR(&ip.gw));
  98.         ESP_LOGI(TAG, "~~~~~~~~~~~");
  99.         xEventGroupSetBits(ethernet_event_group, CONNECTED_BIT);
  100.         break;
  101.     case SYSTEM_EVENT_ETH_STOP:
  102.         ESP_LOGI(TAG, "Ethernet Stopped");
  103.         xEventGroupClearBits(ethernet_event_group, CONNECTED_BIT);
  104.         break;
  105.     default:
  106.         break;
  107.     }
  108.     return ESP_OK;
  109. }
  110.  
  111. void spiffInit(){
  112.     esp_vfs_spiffs_conf_t spifConf = {
  113.       .base_path = "/spiffs",
  114.       .partition_label = NULL,
  115.       .max_files = 1,
  116.       .format_if_mount_failed = true
  117.     };
  118.     esp_err_t ret = esp_vfs_spiffs_register(&spifConf);
  119.     if (ret != ESP_OK) {
  120.         if (ret == ESP_FAIL) {
  121.             ESP_LOGE(TAG, "Failed to mount or format filesystem");
  122.         } else if (ret == ESP_ERR_NOT_FOUND) {
  123.             ESP_LOGE(TAG, "Failed to find SPIFFS partition");
  124.         } else {
  125.             ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret));
  126.         }
  127.     }
  128.     size_t total = 0, used = 0;
  129.     ret = esp_spiffs_info(NULL, &total, &used);
  130.     if (ret != ESP_OK) {
  131.         ESP_LOGE(TAG, "Failed to get SPIFFS partition information (%s)", esp_err_to_name(ret));
  132.     } else {
  133.         ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
  134.     }
  135. }
  136.  
  137.  
  138. void parseDeviceCerts(char *data){
  139.     cJSON *dataJson = cJSON_Parse(data);
  140.     if (dataJson == NULL)
  141.     {
  142.         const char *error_ptr = cJSON_GetErrorPtr();
  143.         if (error_ptr != NULL)
  144.         {
  145.             fprintf(stderr, "Error before: %s\n", error_ptr);
  146.             esp_restart();
  147.         }
  148.     }else{
  149.         spiffInit();
  150.         struct stat st;
  151.         if (stat("/spiffs/deviceInfo.txt", &st) == 0 ) {
  152.             if (val == 1){
  153.                 devKey = cJSON_GetObjectItem(dataJson, "key")->valuestring;
  154.                 xEventGroupSetBits(ethernet_event_group, CONNECTED_BIT);
  155.             }else{
  156.                 devCert = cJSON_GetObjectItem(dataJson, "cert")->valuestring;
  157.             }
  158.             esp_vfs_spiffs_unregister(NULL);
  159.         }else{
  160.             devName = cJSON_GetObjectItem(dataJson, "name")->valuestring;
  161.             FILE* f = fopen("/spiffs/deviceInfo.txt", "w");
  162.             if (f == NULL) {
  163.                 ESP_LOGE(TAG, "Failed to open file for writing");
  164.                 abort();
  165.             }
  166.             fprintf(f, devName);
  167.             fclose(f);
  168.             esp_vfs_spiffs_unregister(NULL);
  169.             esp_restart();
  170.         }
  171.         cJSON_Delete(dataJson);
  172.     }
  173. }
  174.  
  175.  
  176. esp_err_t _http_event_handler(esp_http_client_event_t *evt)
  177. {
  178.     switch(evt->event_id) {
  179.         case HTTP_EVENT_ERROR:
  180.             ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
  181.             break;
  182.         case HTTP_EVENT_ON_CONNECTED:
  183.             ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED");
  184.             break;
  185.         case HTTP_EVENT_HEADER_SENT:
  186.             ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT");
  187.             break;
  188.         case HTTP_EVENT_ON_HEADER:
  189.             ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value);
  190.             break;
  191.         case HTTP_EVENT_ON_DATA:
  192.             ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
  193.             if (!esp_http_client_is_chunked_response(evt->client)) {
  194.                 ESP_LOGI(TAG, "Data Recieved");
  195.                 parseDeviceCerts((char*)evt->data);
  196.             }
  197.             break;
  198.         case HTTP_EVENT_ON_FINISH:
  199.             ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH");
  200.             break;
  201.         case HTTP_EVENT_DISCONNECTED:
  202.             ESP_LOGD(TAG, "HTTP_EVENT_DISCONNECTED");
  203.             break;
  204.     }
  205.     return ESP_OK;
  206. }
  207.  
  208.  
  209.  
  210.  
  211. extern void aws_task_run();
  212. void aws_task(void *pvParameter)
  213. {
  214.     xEventGroupWaitBits(ethernet_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
  215.     aws_task_run(devName, devCert, devKey);
  216. }
  217.  
  218.  
  219. void sendRequest(char url[], char pData[]){
  220.     esp_http_client_config_t configg = {
  221.         .url = url,
  222.         .event_handler = _http_event_handler,
  223.         .buffer_size = 6000,
  224.     };
  225.     esp_http_client_handle_t client = esp_http_client_init(&configg);
  226.      
  227.     const char *post_data = pData;
  228.     esp_http_client_set_method(client, HTTP_METHOD_POST);
  229.     esp_http_client_set_header(client, "Content-Type", "application/json");
  230.     esp_http_client_set_post_field(client, post_data, strlen(post_data));
  231.     esp_err_t err = esp_http_client_perform(client);
  232.     if (err == ESP_OK) {
  233.     ESP_LOGI(TAG, "Request Finished");
  234.     }
  235.     esp_http_client_cleanup(client);
  236. }
  237.  
  238.  
  239. void app_main()
  240. {
  241.     tcpip_adapter_init();
  242.     //spiffInit();
  243.     //unlink("/spiffs/deviceInfo.txt");
  244.     ethernet_event_group = xEventGroupCreate();
  245.     ESP_ERROR_CHECK(esp_event_loop_init(eth_event_handler, NULL));
  246.     eth_config_t config = DEFAULT_ETHERNET_PHY_CONFIG;
  247.     config.phy_addr = 0;
  248.     config.gpio_config = eth_gpio_config_rmii;
  249.     config.tcpip_input = tcpip_adapter_eth_input;
  250.     config.clock_mode = 3;
  251.     config.phy_power_enable = phy_device_power_enable_via_gpio;
  252.     ESP_ERROR_CHECK(esp_eth_init(&config));
  253.     ESP_ERROR_CHECK(esp_eth_enable());
  254.     xEventGroupWaitBits(ethernet_event_group, CONNECTED_BIT,
  255.                         false, true, portMAX_DELAY);
  256.     ESP_LOGI(TAG, "Connected to Internet success!");
  257.     xEventGroupClearBits(ethernet_event_group, CONNECTED_BIT);
  258.     spiffInit();
  259.     struct stat st;
  260.     if (stat("/spiffs/deviceInfo.txt", &st) == 0 ) {
  261.         ESP_LOGI(TAG, "File exists");
  262.         FILE* deviceInfo = fopen("/spiffs/deviceInfo.txt", "r");
  263.         if (deviceInfo == NULL) {
  264.             ESP_LOGI(TAG, "Failed to open file for reading");
  265.             abort();
  266.         }
  267.         char line[8];
  268.         fgets(line, sizeof(line), deviceInfo);
  269.         fclose(deviceInfo);
  270.         devName = line;
  271.         cJSON *root = cJSON_CreateObject();
  272.         cJSON_AddItemToObject(root, "name", cJSON_CreateString(line));
  273.         esp_vfs_spiffs_unregister(NULL);
  274.         sendRequest("http://172.16.1.128:3000/getDeviceCertificate", cJSON_PrintUnformatted(root));
  275.         val = 1;
  276.         sendRequest("http://172.16.1.128:3000/getDeviceKey", cJSON_PrintUnformatted(root));
  277.         cJSON_Delete(root);
  278.     }else{
  279.         ESP_LOGI(TAG, "First time boot");
  280.         esp_vfs_spiffs_unregister(NULL);
  281.         sendRequest("http://172.16.1.128:3000/createDeviceCertificate","{\"cACert\":\"myCAcertificate\"}");
  282.     }
  283.  
  284.     xTaskCreate(aws_task, "aws_task",  10000, NULL, 5, NULL);
  285. }
  286.  
Please help!

jcsbanks
Posts: 305
Joined: Tue Mar 28, 2017 8:03 pm

Re: Variables losing value

Postby jcsbanks » Fri Aug 23, 2019 7:59 am

I am only looking on a phone, but the global is a pointer and the string it points to is probably going out of scope when you delete after getting the JSON. I would investigate the lifetime and location of the string, and who is supposed to allocate and free memory.

https://github.com/DaveGamble/cJSON/issues/154

Who is online

Users browsing this forum: No registered users and 224 guests