133 lines
2.8 KiB
C++
133 lines
2.8 KiB
C++
/**
|
|
* @file wifi_manager.h
|
|
* @brief WiFi 配网管理器
|
|
*
|
|
* 功能:
|
|
* - 自动连接已保存的 WiFi
|
|
* - 配网失败/首次启动 → AP 模式 + 强制门户页面
|
|
* - 自定义参数: MQTT 服务器/端口/用户/密码、设备名称、环境备注
|
|
* - 长按按钮重置配置
|
|
* - LED 状态指示
|
|
* - LittleFS 持久化存储
|
|
*/
|
|
|
|
#ifndef WIFI_MANAGER_H
|
|
#define WIFI_MANAGER_H
|
|
|
|
#include <Arduino.h>
|
|
#include <WiFiManager.h>
|
|
#include <LittleFS.h>
|
|
#include <ArduinoJson.h>
|
|
#include "config.h"
|
|
|
|
// 设备配置结构体
|
|
struct DeviceConfig {
|
|
char mqtt_server[40];
|
|
char mqtt_port[6];
|
|
char mqtt_user[20];
|
|
char mqtt_pass[20];
|
|
char device_id[20];
|
|
char env_note[20]; // 环境备注 (如: "主卧", "客厅", "老人房")
|
|
};
|
|
|
|
class WiFiMgmt {
|
|
public:
|
|
WiFiMgmt();
|
|
~WiFiMgmt();
|
|
|
|
// 单例指针 (用于静态回调)
|
|
static WiFiMgmt* _instance;
|
|
|
|
/**
|
|
* @brief 初始化 WiFi 管理器
|
|
* @return true=成功
|
|
*/
|
|
bool begin();
|
|
|
|
/**
|
|
* @brief 主循环, 处理配网流程和按钮检测
|
|
* @return true=WiFi 已连接
|
|
*/
|
|
bool loop();
|
|
|
|
/**
|
|
* @brief WiFi 是否已连接
|
|
*/
|
|
bool isConnected() const;
|
|
|
|
/**
|
|
* @brief 获取设备配置
|
|
*/
|
|
DeviceConfig getConfig() const;
|
|
|
|
/**
|
|
* @brief 获取设备 ID (用于 MQTT client_id)
|
|
*/
|
|
const char* getDeviceId() const;
|
|
|
|
/**
|
|
* @brief 获取环境备注
|
|
*/
|
|
const char* getEnvNote() const;
|
|
|
|
/**
|
|
* @brief 强制进入配网模式
|
|
*/
|
|
void startConfigPortal();
|
|
|
|
/**
|
|
* @brief 清除所有配置并重启
|
|
*/
|
|
void resetSettings();
|
|
|
|
private:
|
|
/**
|
|
* @brief 尝试连接 WiFi
|
|
*/
|
|
bool _connectWiFi();
|
|
|
|
/**
|
|
* @brief 设置 LED 状态
|
|
* @param mode 0=慢闪(未连接) 1=快闪(配网) 2=常亮(已连接)
|
|
*/
|
|
void _setLEDMode(uint8_t mode);
|
|
|
|
/**
|
|
* @brief 检测按钮长按
|
|
*/
|
|
bool _checkButtonLongPress();
|
|
|
|
/**
|
|
* @brief 加载/保存配置到 LittleFS
|
|
*/
|
|
bool _loadConfig();
|
|
bool _saveConfig();
|
|
|
|
/**
|
|
* @brief 保存 WiFi 参数回调 (WiFiManager 的回调)
|
|
*/
|
|
static void _saveParamsCallback();
|
|
static void _apCallback(WiFiManager* wm);
|
|
|
|
WiFiManager _wm;
|
|
DeviceConfig _config;
|
|
bool _connected;
|
|
uint32_t _lastCheckTime;
|
|
uint32_t _buttonPressTime;
|
|
bool _buttonPressed;
|
|
|
|
// LED 闪烁状态
|
|
uint32_t _ledLastToggle;
|
|
bool _ledState;
|
|
|
|
// WiFiManager 自定义参数
|
|
WiFiManagerParameter* _param_mqtt_server;
|
|
WiFiManagerParameter* _param_mqtt_port;
|
|
WiFiManagerParameter* _param_mqtt_user;
|
|
WiFiManagerParameter* _param_mqtt_pass;
|
|
WiFiManagerParameter* _param_device_id;
|
|
WiFiManagerParameter* _param_env_note;
|
|
};
|
|
|
|
#endif // WIFI_MANAGER_H
|