学习笔记ESP32——心智天气获取和解析

一、获取心知天气函数

 把其中的密钥改成自己注册的

char* xinzhi_task(char * city_str)
{
    int8_t return_res = 1;
    char* weather_buffer = NULL;
    int content_length = 0;

    char city_temp[] = {"http://api.seniverse.com/v3/weather/now.json?key=SuipJRRw3EKYIeK2Mg&location=                                          &language=zh-Hans&unit=c"};
    //char *url_str = utf8_url_encode((const char *)city_str);
    //free(city_str);
    sprintf( city_temp, "http://api.seniverse.com/v3/weather/now.json?key=SuipJRRw3EKYIeK2M&location=%s&language=zh-Hans&unit=c", "shanghai");
    //free(url_str);
    ESP_LOGI(TAG, "待打开的url  \r\n%s\r\n",  city_temp);
    esp_http_client_config_t config = 
    {
        .event_handler = _http_event_handler,
        .url = city_temp,
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);

    if( client == NULL )
    {
        return NULL;
    }

    // GET Request
    esp_http_client_set_method(client, HTTP_METHOD_GET);
    esp_err_t err = esp_http_client_open(client, 0);
    if (return_res && err != ESP_OK) 
    {
        ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err));
        return_res = 0;
    } 
    else 
    {
        content_length = esp_http_client_fetch_headers(client);     //获取到之后要读的长度
        if (content_length < 0) 
        {
            ESP_LOGE(TAG, "HTTP client fetch headers failed");
            return_res = 0;
        } else 
        {
            weather_buffer = malloc(content_length);        //malloc方式分配存储空间
            memset(weather_buffer, 0, content_length);      //将weather_buffer中当前位置后面的content_length个字节用0替换
            if( weather_buffer == NULL )
            {
                return_res = 0;
            }
            else
            {
                int data_read = esp_http_client_read_response(client, weather_buffer, content_length);
                if (data_read >= 0) 
                {
                    ESP_LOGI(TAG, "HTTP GET Status = %d, content_length = %d, data_read = %d",
                    esp_http_client_get_status_code(client),
                    esp_http_client_get_content_length(client),
                    data_read);
                    //ESP_LOG_BUFFER_HEX(TAG, weather_buffer, data_read);
                    ESP_LOGI( TAG, "Data %s \r\n",  weather_buffer);
                } 
                else 
                {
                    ESP_LOGE(TAG, "Failed to read response");
                    return_res = 0;
                }
            }
        }
    }
    esp_http_client_close(client);

    if(!return_res)
    {
        free(weather_buffer);
        weather_buffer = NULL;
    }
    return weather_buffer;
}

在event_handler里调用 

解析函数,这里使用cJSON ,记得包含#include "cJSON.h"

static bool parse_weather_json(char *analysis_buf)
{
    if( analysis_buf == NULL )
    {
        return false;
    }

    cJSON * json_root = cJSON_Parse(analysis_buf);
    if( json_root != NULL )
    {
        cJSON *cjson_arr = cJSON_GetObjectItem(json_root,"results");
        cJSON *cjson_location = cJSON_GetObjectItem(cJSON_GetArrayItem(cjson_arr, 0),"location");
        ESP_LOGI(TAG, "城市 -> %s\r\n", cJSON_GetObjectItem(cjson_location,"name")->valuestring );
        cJSON *cjson_now = cJSON_GetObjectItem(cJSON_GetArrayItem(cjson_arr, 0),"now");
        ESP_LOGI(TAG, "天气 -> %s\r\n", cJSON_GetObjectItem(cjson_now,"text")->valuestring );
        ESP_LOGI(TAG, "code -> %s\r\n", cJSON_GetObjectItem(cjson_now,"code")->valuestring );
        ESP_LOGI(TAG, "气温 -> %s\r\n", cJSON_GetObjectItem(cjson_now,"temperature")->valuestring );

        cJSON_Delete(json_root);
    }

    free(analysis_buf);

    return true;
}

  在event_handler里嵌套调用

parse_weather_json(xinzhi_task(NULL));

 二、城市信息

 ip地址后面使用自己的ip

char* city_task(void)
{
    int8_t return_res = 1;
    char* city_buffer = NULL;
    int content_length = 0;

    esp_http_client_config_t config = 
    {
        .event_handler = _http_event_handler,
        .url = "http://whois.pconline.com.cn/ipJson.jsp?ip=xxx.xxx.xxx.xxx&json=true",
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);

    if( client == NULL )
    {
        return NULL;        
    }

    // GET Request
    esp_http_client_set_method(client, HTTP_METHOD_GET);
    esp_err_t err = esp_http_client_open(client, 0);
    if (return_res && err != ESP_OK) 
    {
        ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err));
        return_res = 0;
    } 
    else 
    {
        content_length = esp_http_client_fetch_headers(client);
        if (content_length < 0) 
        {
            ESP_LOGE(TAG, "HTTP client fetch headers failed");
            return_res = 0;
        } else 
        {
            city_buffer = malloc(300);
            memset(city_buffer, 0, 300);
            if(city_buffer == NULL)
            {
                return_res = 0;
            }
            else
            {
                int data_read = esp_http_client_read_response(client, city_buffer, 300);
                if (data_read >= 0) 
                {
                    ESP_LOGI(TAG, "HTTP GET Status = %d, content_length = %d, data_read = %d",
                    esp_http_client_get_status_code(client),
                    esp_http_client_get_content_length(client),
                    data_read);
                    //ESP_LOG_BUFFER_HEX(TAG, city_buffer, data_read);
                    ESP_LOGI( TAG, "Data %s \r\n",  city_buffer);
                }
                else 
                {
                    return_res = 0;
                    ESP_LOGE(TAG, "Failed to read response");
                }
            }
        }
    }
    esp_http_client_close(client);

    if( return_res == 0 )
    {
        free(city_buffer);
        city_buffer = NULL;
    }

    return city_buffer;
}

解析

static char* parse_city_json(char *analysis_buf)
{
    char* city_str = NULL;
    if( analysis_buf == NULL )
    {
        return false;
    }

    cJSON * json_root = cJSON_Parse(analysis_buf);
    if( json_root != NULL )
    {
        ESP_LOGI(TAG, "城市[%d] -> %s\r\n", strlen(cJSON_GetObjectItem(json_root,"city")->valuestring)+1, cJSON_GetObjectItem(json_root,"city")->valuestring );
        city_str = malloc(strlen(cJSON_GetObjectItem(json_root,"city")->valuestring)+1);
        strcpy( city_str,
                cJSON_GetObjectItem(json_root,"city")->valuestring);
        cJSON_Delete(json_root);
        char* utf8_str = malloc(strlen(city_str)*2+1);
        gb2312ToUtf8(utf8_str, strlen(city_str)*2+1, city_str, strlen(city_str));
        free(city_str);
        city_str = utf8_str;
        ESP_LOGI(TAG, "城市[%s]", city_str);
    }
    free(analysis_buf);

    return city_str;
}

 先解析出cJSON后,先用gb2312ToUtf8()函数转成utf8输出,把输出的结果放在心知天气函数xinzhi_task里,在把刚刚注释的utf8转url函数打开,同时修改sprintf()里的字符串,改成转码后用来存放的city_str变量。

char* xinzhi_task(char * city_str)
{
    int8_t return_res = 1;
    char* weather_buffer = NULL;
    int content_length = 0;

    char city_temp[] = {"http://api.seniverse.com/v3/weather/now.json?key=SuipJRRw3EKYIeK2Mg&location=                                          &language=zh-Hans&unit=c"};
    char *url_str = utf8_url_encode((const char *)city_str);
    free(city_str);
    sprintf( city_temp, "http://api.seniverse.com/v3/weather/now.json?key=SuipJRRw3EKYIeK2M&location=%s&language=zh-Hans&unit=c", url_str);
    free(url_str);

 在event_handler里嵌套调用

        parse_weather_json(xinzhi_task(parse_weather_json(city_task()))) 

编译下载成功 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值