ESP32S3获取天气以及时间同步

需要自己注册一个ID

http://gfeljm.tianqiapi.com/api?unescape=1&version=v61&appid=&appsecret=

代码

#include "esp_err.h"
#include "esp_sntp.h"
#include "esp_netif.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_http_client.h"

#define WIFI_SSID "xxxxxxxx"	//注意替换wifi信息
#define WIFI_PASS "xxxxxxxx"
#define CONFIG_BLINK_PERIOD 5000
static const char *TAG = "NTP_TIME";

void initialize_nvs() {
    esp_err_t ret = nvs_flash_init();// 初始化NVS, 并检查是否需要擦除NVS
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
}
char url[256]="http://gfeljm.tianqiapi.com/api?unescape=1&version=v61&appid=&appsecret="; 
char replyData[2048]={0};
int replyLen=0;

typedef struct UserData_t{
	char *data;
	int len;
}UserData_t;

static esp_err_t http_handler(esp_http_client_event_t *evt)
{
    switch(evt->event_id) {
        case HTTP_EVENT_ERROR:
            ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
            break;
        case HTTP_EVENT_ON_CONNECTED:
            ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED");
            break;
        case HTTP_EVENT_HEADER_SENT:
            ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT");
            break;
        case HTTP_EVENT_ON_HEADER:
            ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value);
            break;
        case HTTP_EVENT_ON_DATA:
            if(evt->user_data){
            	UserData_t* userData = (UserData_t*)evt->user_data;
            	memcpy(userData->data+userData->len, evt->data, evt->data_len);
            	userData->len += evt->data_len;
            }
            break;
        case HTTP_EVENT_ON_FINISH:
            ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH");
            break;
        case HTTP_EVENT_DISCONNECTED:
            printf( "HTTP_EVENT_DISCONNECTED");
            break;
        default:
        	break;
    }
    return ESP_OK;
}

int http_get(void)
{
	esp_err_t err=ESP_OK;
	//服务器回复内容设置
	UserData_t userData = {
		.data = replyData,
		.len = 0,
	};
	//url和链接时间等基础参数设置
	esp_http_client_config_t config = {
		.url = url,
		.keep_alive_enable = 0,
		.timeout_ms = 1000,
		.event_handler = http_handler,//注册回调函数
		.user_data = (void*)&userData
	};
	esp_http_client_handle_t client=esp_http_client_init(&config);
	esp_http_client_set_method(client, HTTP_METHOD_GET);//设置方式
    err = esp_http_client_perform(client);
    if(err == ESP_OK){
    	int statusCode = esp_http_client_get_status_code(client);
    	printf( "Https post status = %d\n", statusCode);
    	printf( "sever data = %s  sever data len=%d\n", userData.data,userData.len );//打印服务器回复内容
    }	
    esp_http_client_cleanup(client);//请求后主动关闭链接,节约服务器资源
    return err;
}

// SNTP 初始化
void initialize_sntp() {
    printf( "Initializing SNTP");

#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
        // 设置时间服务器(默认使用 pool.ntp.org)
    esp_sntp_setoperatingmode(SNTP_OPMODE_POLL);
    // 添加 NTP 服务器
    esp_sntp_setservername(0, "pool.ntp.org"); // 默认服务器
    esp_sntp_setservername(1, "cn.pool.ntp.org"); // 中国 NTP 服务器
    esp_sntp_setservername(2, "ntp1.aliyun.com"); //阿里云 NTP 服务器
    // 初始化 SNTP
    esp_sntp_init();
#else
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    sntp_setservername(0, "pool.ntp.org");
    sntp_setservername(1, "cn.pool.ntp.org");
    sntp_setservername(2, "ntp1.aliyun.com");
    sntp_init();// 初始化 SNTP
#endif
    // 设置时区(例如:北京时间 UTC+8)
    setenv("TZ", "CST-8", 1);
    tzset();
}

// 打印当前时间
void print_current_time() {
    time_t now;
    struct tm timeinfo;
   // char buffer[64];

   // 获取当前时间戳
    time(&now);
    // 将时间戳转换为本地时间
    localtime_r(&now, &timeinfo);
    // 格式化时间
 // 使用 strftime 格式化时间
    // strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &timeinfo);
    // printf( "Formatted time: %s", buffer);

    // strftime(buffer, sizeof(buffer), "%A, %B %d, %Y %I:%M:%S %p", &timeinfo);
    // printf( "Formatted time: %s", buffer);

    // strftime(buffer, sizeof(buffer), "Today is %A, %B %d, %Y. The time is %I:%M %p.", &timeinfo);
    // printf( "Formatted time: %s", buffer);
    // 使用 asctime 打印时间
    char *time_str = asctime(&timeinfo);
    if (time_str != NULL) {
        // 去掉 asctime 输出的换行符
        time_str[strlen(time_str) - 1] = '\0';
        printf( "Current time: %s", time_str);
    } else {
        ESP_LOGE(TAG, "Failed to convert time to string");
    }
}
//事件回调
void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        esp_wifi_connect();
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
        esp_wifi_connect();
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        ESP_LOGI("WIFI", "Got IP: " IPSTR, IP2STR(&event->ip_info.ip));
        printf( "Wi-Fi connected, initializing SNTP...");
        initialize_sntp();

        http_get();
    }
}

void initialize_wifi() {
    esp_netif_init();
    esp_event_loop_create_default();
    esp_netif_create_default_wifi_sta();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));// 注册WiFi事件处理程序
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL));// 注册IP事件处理程序

    wifi_config_t wifi_config = {
        .sta = {
            .ssid = WIFI_SSID,
            .password = WIFI_PASS,
        },
    };

    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));// 设置为STA模式
    ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));// 设置WiFi配置
    ESP_ERROR_CHECK(esp_wifi_start());// 启动WiFi
}

// 打印 Wi-Fi 信息
void print_wifi_info() {
    wifi_config_t wifi_config;
    esp_wifi_get_config(ESP_IF_WIFI_STA, &wifi_config);

    esp_netif_ip_info_t ip_info;
    esp_netif_t* netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
    if (netif && esp_netif_get_ip_info(netif, &ip_info) == ESP_OK) {
        printf( "Wi-Fi SSID: %s", (char*)wifi_config.sta.ssid);
        printf( "Wi-Fi Password: %s", (char*)wifi_config.sta.password);
        printf( "IP Address: " IPSTR, IP2STR(&ip_info.ip));
    } else {
        ESP_LOGE(TAG, "Failed to get IP information");
    }
}


void app_main(void)
{
    initialize_nvs();// 初始化NVS
    initialize_wifi();  // 初始化Wi-Fi

    while (1)
    {
        // 检查时间是否已同步
        time_t now;
        struct tm timeinfo;
        time(&now);
        localtime_r(&now, &timeinfo);//将时间戳转换为本地时间。
         // 打印当前时间的详细信息
    printf( "Current time: %04d-%02d-%02d %02d:%02d:%02d",
             timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday,
             timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);
        // 如果时间已同步(年份大于 2024)
        if (timeinfo.tm_year > (2024 - 1900)) {
            print_current_time();
            ESP_ERROR_CHECK(esp_wifi_stop());// 启动WiFi
            break;
        } else {
            printf( "Waiting for time synchronization...");
        }
        vTaskDelay(CONFIG_BLINK_PERIOD / portTICK_PERIOD_MS);
        print_wifi_info() ;
    }
    while(1)
    {
        printf( "loop\r\n");
        vTaskDelay(CONFIG_BLINK_PERIOD / portTICK_PERIOD_MS);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花开花落的个人博客

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值