12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- #include "pairing_service/settings_controller.h"
- #include <esp_log.h>
- #include <kbf.h>
- #include <kbf/rtos.h>
- #include <kbf/wifi.h>
- #include "tasks/display_manager.h"
- using namespace kbf;
- SettingsController::SettingsController() : Controller("/settings") {}
- static bool validate(const nlohmann::json &json) {
- if (json == nullptr) {
- ESP_LOGE(SettingsController::TAG, "json is null");
- return false;
- } else if (json.find("ssid") == json.end()) {
- ESP_LOGE(SettingsController::TAG, "no SSID");
- return false;
- } else if (json.find("password") == json.end()) {
- ESP_LOGE(SettingsController::TAG, "no password");
- return false;
- }
- return true;
- }
- static rtos::EventGroup eventGroup;
- enum ConnectStatus {
- DISCONNECTED,
- GOT_IP
- };
- static bool connect(const string &ssid, const string &password) {
- static const char *TAG = "SettingsController::connect";
- ESP_LOGI(TAG, "connect(\"%s\", ...)", ssid.c_str());
- ESP_LOGD(TAG, "credentials: %s; %s", ssid.c_str(), password.c_str());
- eventGroup.clear();
- wifi::sta::start();
- wifi::sta::onDisconnect = {[]() { eventGroup.setBit(DISCONNECTED); }};
- wifi::sta::onIp = {[]() { eventGroup.setBit(GOT_IP); }};
- wifi::sta::connect(ssid, password, true, CONFIG_DK_PAIRING_WIFI_MAX_RETRY);
- eventGroup.waitForAny({DISCONNECTED, GOT_IP}, CONFIG_DK_PAIRING_WIFI_TIMEOUT);
- if (eventGroup.getBit(GOT_IP)) {
- ESP_LOGI(TAG, "connection successful");
- return true;
- }
- if (eventGroup.getBit(DISCONNECTED)) {
- ESP_LOGW(TAG, "connection failed");
- return false;
- }
- ESP_LOGW(TAG, "connection timeout");
- return false;
- }
- http::Response SettingsController::get(const kbf::http::Request &request) {
- auto wifiConfig = dk::settings::wifi();
- auto response = nlohmann::json({
- {"ssid", wifiConfig.ssid},
- {"password", wifiConfig.password}
- });
- return http::Response(response);
- }
- http::Response SettingsController::post(const kbf::http::Request &request) {
- auto json = request.json();
- if (!validate(json)) return http::Response("", 500);
- auto ssid = json.find("ssid")->get<string>();
- auto password = json.find("password")->get<string>();
- DisplayManager::setMessage("SSID " + ssid);
- if (!connect(ssid, password)) {
- ESP_LOGW(TAG, "unable to connect to SSID: %s", ssid.c_str());
- DisplayManager::setMessage("connect failed", 1000);
- // TODO set pairing mode
- // dk::mainEventGroup->setBit(dk::MainEvents::SET_PAIRING_MODE); // TODO is this OK?
- return http::Response(nlohmann::json({{"success", false}}));
- }
- dk::settings::Wifi wifiConfig = {
- .ssid = ssid,
- .password = password,
- };
- dk::settings::setWifi(wifiConfig);
- DisplayManager::setMessage("connected");
- return http::Response(nlohmann::json({{"success", true}}));
- }
|