DualLedController/components/Communication/Application.h

77 lines
2.6 KiB
C++

#ifndef __APPLICATION_H__
#define __APPLICATION_H__
#include <esp_event.h>
#include <esp_log.h>
#include <freertos/event_groups.h>
#include <nvs.h>
#include <string>
#include <type_traits>
class Application {
constexpr static int CONNECTED_BIT = BIT0;
constexpr static auto Namespace = "settings";
public:
constexpr static int WifiJoinTimeoutMillisecond = 10000;
static Application *instance();
bool wifiConnect(const std::string &ssid, const std::string &password,
int timeoutMillisecond = WifiJoinTimeoutMillisecond);
void initialize();
template <typename T>
void setField(const std::string &key, const T &value) {
nvs_handle_t hanlde;
esp_err_t error = nvs_open(Namespace, NVS_READWRITE, &hanlde);
if (error != ESP_OK) {
ESP_LOGI("App", "nvs_open() failed.");
}
if constexpr (std::is_same_v<char *, std::decay_t<T>>) {
error = nvs_set_str(hanlde, key.c_str(), value);
} else if constexpr (std::is_same_v<std::string, T>) {
error = nvs_set_str(hanlde, key.c_str(), value.c_str());
} else if constexpr (std::is_same_v<int32_t, T> || std::is_same_v<int, T>) {
error = nvs_set_i32(hanlde, key.c_str(), value);
} else {
ESP_LOGW("App", "unknown data");
}
if (error == ESP_OK) {
error = nvs_commit(hanlde);
}
nvs_close(hanlde);
}
template <typename T>
T field(const std::string &key) {
T ret{};
nvs_handle_t hanlde;
nvs_open(Namespace, NVS_READWRITE, &hanlde);
if constexpr (std::is_same_v<char *, std::decay_t<T>> || std::is_same_v<std::string, T>) {
size_t requiredSize;
nvs_get_str(hanlde, key.c_str(), nullptr, &requiredSize);
ret.resize(requiredSize);
nvs_get_str(hanlde, key.c_str(), ret.data(), &requiredSize);
} else if constexpr (std::is_same_v<int, T>) {
ret = field<int32_t>(key);
} else if constexpr (std::is_same_v<int32_t, T>) {
nvs_get_i32(hanlde, key.c_str(), &ret);
}
nvs_close(hanlde);
return ret;
}
bool contains(const std::string &key);
protected:
static void eventHandler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data);
void initializeWifi();
Application() = default;
private:
EventGroupHandle_t m_wifiEventGroup = nullptr;
nvs_handle_t m_nvs;
};
#endif // __APPLICATION_H__