基于VSCode的ESP32开发环境的搭建
1.首先创建一个HTTPS Request例程
查看->控制面板->ESP-IDF:展示示例项目
2.输入wifi账号密码
首先让模块能够正常连接上wifi
3.天气API
这是我使用的API,你也可以使用别家的 天气API链接
4.填入API
5.查看结果
6.解析数据
返回的数据是cJson格式的 { }里的就是我们需要的数据
{"cityid":"101280601","city":"深圳","update_time":"15:23","wea":"多云","wea_img":"yun","tem":"20","tem_day":"17","tem_night":"11","win":"西南风","win_speed":"3级","win_meter":"14km\/h","air":"34"}
6.添加cJSON头文件
#include "cJSON.h"
修改https_get_request函数
static void https_get_request(esp_tls_cfg_t cfg)
{
char buf[512];
int ret, len;
struct esp_tls *tls = esp_tls_conn_http_new(WEB_URL, &cfg);
if (tls != NULL)
{
ESP_LOGI(TAG, "Connection established...");
}
else
{
ESP_LOGE(TAG, "Connection failed...");
goto exit;
}
#ifdef CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS
if (tls_client_session == NULL)
{
tls_client_session = esp_tls_get_client_session(tls);
}
#endif
size_t written_bytes = 0;
do
{
ret = esp_tls_conn_write(tls,
REQUEST + written_bytes,
sizeof(REQUEST) - written_bytes);
if (ret >= 0)
{
ESP_LOGI(TAG, "%d bytes written", ret);
written_bytes += ret;
}
else if (ret != ESP_TLS_ERR_SSL_WANT_READ && ret != ESP_TLS_ERR_SSL_WANT_WRITE)
{
ESP_LOGE(TAG, "esp_tls_conn_write returned: [0x%02X](%s)", ret, esp_err_to_name(ret));
goto exit;
}
} while (written_bytes < sizeof(REQUEST));
ESP_LOGI(TAG, "Reading HTTP response...");
do
{
len = sizeof(buf) - 1;
bzero(buf, sizeof(buf));
ret = esp_tls_conn_read(tls, (char *)buf, len);
if (ret == ESP_TLS_ERR_SSL_WANT_WRITE || ret == ESP_TLS_ERR_SSL_WANT_READ)
{
continue;
}
if (ret < 0)
{
ESP_LOGE(TAG, "esp_tls_conn_read returned [-0x%02X](%s)", -ret, esp_err_to_name(ret));
break;
}
if (ret == 0)
{
ESP_LOGI(TAG, "connection closed");
break;
}
len = ret;
ESP_LOGD(TAG, "%d bytes read", len);
for (int i = 0; i < len; i++)
{
putchar(buf[i]);
}
putchar('\n');
char *str_1 = strchr(buf, '{');
if (str_1 != NULL)
{
char *str_2 = strchr(buf, '}');
ESP_LOGI(TAG, "str_1 = %d str_2 = %d %d", str_1, str_2, str_2 - str_1);
char dest[250] = {""};
strncpy(dest, str_1, str_2 - str_1 + 1);
ESP_LOGI(TAG, "%s", dest);
cJSON *pJsonRoot = cJSON_Parse(dest);
if (pJsonRoot != NULL)
{
char bssid[23] = {0};
cJSON *pMacAdress = cJSON_GetObjectItem(pJsonRoot, "city");
if (pMacAdress != NULL)
{
if (cJSON_IsString(pMacAdress))
{
strcpy(bssid, pMacAdress->valuestring);
ESP_LOGI(TAG, "city = [%s]", bssid);
}
}
pMacAdress = cJSON_GetObjectItem(pJsonRoot, "wea");
if (pMacAdress != NULL)
{
if (cJSON_IsString(pMacAdress))
{
strcpy(bssid, pMacAdress->valuestring);
ESP_LOGI(TAG, "wea = [%s]", bssid);
}
}
pMacAdress = cJSON_GetObjectItem(pJsonRoot, "tem");
if (pMacAdress != NULL)
{
if (cJSON_IsString(pMacAdress))
{
strcpy(bssid, pMacAdress->valuestring);
ESP_LOGI(TAG, "tem = [%s]", bssid);
}
}
}
}
} while (1);
exit:
esp_tls_conn_delete(tls);
for (int countdown = 10; countdown >= 0; countdown--)
{
ESP_LOGI(TAG, "%d...", countdown);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
7.移植到别的项目中
|