DualLedController/components/Communication/Application.cpp

76 lines
2.8 KiB
C++
Raw Permalink Normal View History

2024-06-03 23:51:39 +08:00
#include "Application.h"
#include <esp_log.h>
#include <esp_wifi.h>
#include <freertos/FreeRTOS.h>
#include <string.h>
Application *Application::instance() {
static Application self;
return &self;
}
void Application::initialize() {
initializeWifi();
}
void Application::eventHandler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) {
auto self = reinterpret_cast<Application *>(arg);
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
esp_wifi_connect();
xEventGroupClearBits(self->m_wifiEventGroup, CONNECTED_BIT);
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
xEventGroupSetBits(self->m_wifiEventGroup, CONNECTED_BIT);
}
}
bool Application::wifiConnect(const std::string &ssid, const std::string &password, int timeoutMillisecond) {
wifi_config_t config = {};
strlcpy((char *)config.sta.ssid, ssid.c_str(), sizeof(config.sta.ssid));
if (!password.empty()) {
strlcpy((char *)config.sta.password, password.c_str(), sizeof(config.sta.password));
}
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &config));
esp_wifi_connect();
int bits =
xEventGroupWaitBits(m_wifiEventGroup, CONNECTED_BIT, pdFALSE, pdTRUE, timeoutMillisecond / portTICK_PERIOD_MS);
return (bits & CONNECTED_BIT) != 0;
}
void Application::initializeWifi() {
esp_log_level_set("wifi", ESP_LOG_WARN);
static bool initialized = false;
if (initialized) {
return;
}
ESP_ERROR_CHECK(esp_netif_init());
if (m_wifiEventGroup == nullptr) {
m_wifiEventGroup = xEventGroupCreate();
}
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_t *ap_netif = esp_netif_create_default_wifi_ap();
assert(ap_netif);
esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
assert(sta_netif);
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, WIFI_EVENT_STA_DISCONNECTED, &Application::eventHandler, this));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &Application::eventHandler, this));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_NULL));
ESP_ERROR_CHECK(esp_wifi_start());
initialized = true;
2024-06-05 22:59:04 +08:00
}
bool Application::contains(const std::string &key) {
nvs_handle_t hanlde;
esp_err_t error = nvs_open(Namespace, NVS_READWRITE, &hanlde);
nvs_type_t type;
error = nvs_find_key(hanlde, key.c_str(), &type);
nvs_close(hanlde);
return error == ESP_OK;
2024-06-03 23:51:39 +08:00
}