#ifndef __APPLICATION_H__ #define __APPLICATION_H__ #include #include #include #include #include #include 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 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>) { error = nvs_set_str(hanlde, key.c_str(), value); } else if constexpr (std::is_same_v) { error = nvs_set_str(hanlde, key.c_str(), value.c_str()); } else if constexpr (std::is_same_v || std::is_same_v) { 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 T field(const std::string &key) { T ret{}; nvs_handle_t hanlde; nvs_open(Namespace, NVS_READWRITE, &hanlde); if constexpr (std::is_same_v> || std::is_same_v) { 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) { ret = field(key); } else if constexpr (std::is_same_v) { 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__