I don' t know if I have found a bug or maybe there is some bug in my code. I have written a function that scans the avalaible AP's and returns them in a json format. It worked, until I noticed that my webpage sometimes wasn't loading the new AP's, then I saw the json was malformed. When I looked into it, then I saw that was returning (sometimes) more APs than where avaliable, and when I was reading them and writing them into an array with a json form, they where overflowing, making the json malformed.
Here is the code:
Code: Select all
size_t scan_APs(char **scanned_APs){
//Scans APs and returns them in a jsonfied form for processing them in the configurator
// Redone: It returns the size, but receives a pointer to where the data will be set
ESP_LOGD(TAG, "Scanning Wifi Access Points, and stringifying them to json format");
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
uint16_t ap_count = 0;
uint16_t number = DEFAULT_SCAN_LIST_SIZE;
wifi_ap_record_t ap_info[DEFAULT_SCAN_LIST_SIZE];
esp_wifi_scan_start(NULL, true);
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&ap_count));
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&number, ap_info));
// Max size of ssid is 32 Caracters,
size_t used_space=0;
const size_t max_size = 1024;
*scanned_APs = malloc(max_size);
ESP_LOGI(__func__, "Found Networks: %d", ap_count);
used_space = snprintf(*scanned_APs, max_size, "{\"wifi_APs\":[\n");
int i = 0;
while((i < ap_count) & (used_space < max_size)){
//The other end just wants to know Name, Security and RSSI
//if(ap_info[i].ssid == "" | ap_info[i].rssi >= 0)break; //This condition is not possible, but the
used_space += snprintf(*scanned_APs + used_space, max_size - used_space,
"{\"Name\": \"%s\",\n\"Authmode\": \"%d\",\n\"RSSI\": \"%d\"\n},", ap_info[i].ssid, ap_info[i].authmode, ap_info[i].rssi);
i++;
}
used_space--; //This way we rewrite the , of the end of the previous and last object
used_space += snprintf(*scanned_APs + used_space, max_size - used_space, "\n]}");
//used_space = snprintf(*scanned_APs, max_size, "{'wifi_ap':'thisisatest'}");
ESP_LOGD(TAG, "Number of Scanned Networks: %d \nScanned Networks: \n %s", ap_count, *scanned_APs);
ESP_LOGD(TAG, "Size Scanned Networks: %d", used_space);
scanned_APs = realloc(*scanned_APs, used_space);
return used_space;
}