优化SNTP连接,支持直接获取结构体。方便其他程序读取
This commit is contained in:
@@ -17,23 +17,13 @@ static uint8_t wifi_tx_buffer[WIFI_TX_BUF_SIZE];
|
||||
static volatile uint8_t wifi_tx_busy = 0;
|
||||
|
||||
WIFI_HandleTypeDef wifi = {0};
|
||||
SNTP_Time_t sntp_time = {0};
|
||||
|
||||
/* MQTT 状态 */
|
||||
static volatile uint8_t mqtt_connected = 0;
|
||||
static MQTT_State_t mqtt_state = MQTT_STATE_IDLE;
|
||||
|
||||
// SNTP 时间结构体
|
||||
typedef struct {
|
||||
uint16_t year;
|
||||
uint8_t month;
|
||||
uint8_t day;
|
||||
uint8_t hour;
|
||||
uint8_t minute;
|
||||
uint8_t second;
|
||||
uint8_t valid; // 1表示有效,0表示无效
|
||||
} SNTP_Time_t;
|
||||
|
||||
static SNTP_Time_t sntp_time = {0};
|
||||
|
||||
static void Generate_Random_ClientID(char *out_id, uint16_t max_len) {
|
||||
// 获取系统运行时间
|
||||
@@ -482,6 +472,13 @@ void wifi_task_mqtt(void *argument) {
|
||||
// 连接MQTT服务器成功后,获取SNTP时间
|
||||
WIFI_Get_SNTP_Time();
|
||||
|
||||
// 获取SNTP时间
|
||||
elog_i(TAG, "获取SNTP时间...");
|
||||
WIFI_Get_Current_Time();
|
||||
elog_i(TAG, "当前SNTP时间为: %04d-%02d-%02d %02d:%02d:%02d",
|
||||
sntp_time.year, sntp_time.month, sntp_time.day,
|
||||
sntp_time.hour, sntp_time.minute, sntp_time.second);
|
||||
|
||||
elog_i(TAG, "进入MQTT消息处理循环");
|
||||
for (;;) {
|
||||
if (wifi.rx_flag) {
|
||||
|
||||
@@ -26,9 +26,25 @@ typedef struct {
|
||||
uint16_t payload_len;
|
||||
} MQTT_Message_t;
|
||||
|
||||
|
||||
// SNTP 时间结构体
|
||||
typedef struct {
|
||||
uint16_t year;
|
||||
uint8_t month;
|
||||
uint8_t day;
|
||||
uint8_t hour;
|
||||
uint8_t minute;
|
||||
uint8_t second;
|
||||
uint8_t valid; // 1表示有效,0表示无效
|
||||
} SNTP_Time_t;
|
||||
|
||||
extern SNTP_Time_t sntp_time;
|
||||
|
||||
|
||||
/* 解析函数 */
|
||||
uint8_t WIFI_Parse_MQTT_Message(char *input, MQTT_Message_t *msg);
|
||||
|
||||
|
||||
/* MQTT运行状态 */
|
||||
typedef enum {
|
||||
MQTT_STATE_IDLE = 0,
|
||||
@@ -62,6 +78,7 @@ uint8_t WIFI_MQTT_Publish_Status(const char *json);
|
||||
/* ================= SNTP函数声明 ================= */
|
||||
uint8_t WIFI_Enable_SNTP(void);
|
||||
uint8_t WIFI_Get_SNTP_Time(void);
|
||||
|
||||
SNTP_Time_t WIFI_Get_Current_Time(void);
|
||||
uint8_t WIFI_Is_Time_Valid(void);
|
||||
|
||||
#endif /* __DX_WF_24_H__ */
|
||||
|
||||
18
README.md
18
README.md
@@ -20,4 +20,20 @@
|
||||
|
||||
> 注意:当前实现为单任务模型,在 `wifi_task_mqtt` 中完成初始化、连接、订阅及消息处理循环。
|
||||
|
||||
---
|
||||
## SNTP 网络时间同步功能
|
||||
|
||||
本工程还实现了 SNTP (Simple Network Time Protocol) 网络时间同步功能,主要特性包括:
|
||||
|
||||
- **自动时间同步**:在 MQTT 连接成功后自动获取网络时间并同步到本地。
|
||||
- **中国时区支持**:默认配置为中国时区(UTC+8),使用 `cn.ntp.org.cn` 作为 NTP 服务器。
|
||||
- **时间获取与存储**:提供 API 接口获取当前网络时间,并存储在内部结构体中。
|
||||
- **时间有效性检查**:提供函数检查获取的时间是否有效。
|
||||
|
||||
### 主要函数接口:
|
||||
|
||||
- `WIFI_Enable_SNTP()`:启用 SNTP 功能并配置 NTP 服务器
|
||||
- `WIFI_Get_SNTP_Time()`:获取当前网络时间
|
||||
- `WIFI_Get_Current_Time()`:获取存储的当前时间(返回结构体副本)
|
||||
- `WIFI_Is_Time_Valid()`:检查时间是否有效
|
||||
|
||||
### 使用示例:
|
||||
Reference in New Issue
Block a user