- Fix preferences lib
- Fix ADHOC
- Optimize API
- Implement full preferences lib
- Implement API with preferences lib
This commit is contained in:
ZanzyTHEbar 2022-08-15 05:54:06 +01:00
parent b69e6f9fad
commit 8ce0ea0860
12 changed files with 449 additions and 298 deletions

View File

@ -2,7 +2,7 @@
Preferences preferences; Preferences preferences;
ProjectConfig::ProjectConfig() : Config(&preferences ,"config"), _already_loaded(false) {} ProjectConfig::ProjectConfig() : Config(&preferences, "config"), _already_loaded(false) {}
ProjectConfig::~ProjectConfig() {} ProjectConfig::~ProjectConfig() {}
@ -18,19 +18,28 @@ void ProjectConfig::initConfig()
"", "",
0, 0,
}; };
this->config.camera = { this->config.camera = {
0, 0,
0, 0,
0, 0,
0, 0,
}; };
this->config.networks = { this->config.networks = {
{ {
"", "",
"", "",
"", "",
0,
}, },
}; };
this->config.ap_network = {
"",
"",
0,
};
} }
void ProjectConfig::load() void ProjectConfig::load()
@ -42,13 +51,41 @@ void ProjectConfig::load()
return; return;
} }
bool device_success = this->read("device", this->config.device); bool device_name_success = this->read("device_name", this->config.device.name);
bool camera_success = this->read("camera", this->config.camera); bool device_otapassword_success = this->read("ota_pass", this->config.device.OTAPassword);
bool network_info_success = this->read("network_info", this->config.networks); bool device_otaport_success = this->read("ota_port", this->config.device.OTAPort);
bool device_success = device_name_success && device_otapassword_success && device_otaport_success;
bool camera_vflip_success = this->read("camera_vflip", this->config.camera.vflip);
bool camera_framesize_success = this->read("cameraFrmsz", this->config.camera.framesize);
bool camera_href_success = this->read("camera_href", this->config.camera.href);
bool camera_quality_success = this->read("camera_quality", this->config.camera.quality);
bool camera_success = camera_vflip_success && camera_framesize_success && camera_href_success && camera_quality_success;
bool network_info_success;
for (int i = 0; i < this->config.networks.size(); i++)
{
char buff[25];
snprintf(buff, sizeof(buff), "%d_name", i);
bool networks_name_success = this->read(buff, this->config.networks[i].name);
snprintf(buff, sizeof(buff), "%d_ssid", i);
bool networks_ssid_success = this->read(buff, this->config.networks[i].ssid);
snprintf(buff, sizeof(buff), "%d_password", i);
bool networks_password_success = this->read(buff, this->config.networks[i].password);
snprintf(buff, sizeof(buff), "%d_channel", i);
bool networks_channel_success = this->read(buff, this->config.networks[i].channel);
network_info_success = networks_name_success && networks_ssid_success && networks_password_success && networks_channel_success;
}
if (!device_success || !camera_success || !network_info_success) if (!device_success || !camera_success || !network_info_success)
{ {
log_e("Failed to load project config"); log_e("Failed to load project config - Generating config and restarting");
save();
delay(1000);
ESP.restart();
return; return;
} }
@ -59,9 +96,28 @@ void ProjectConfig::load()
void ProjectConfig::save() void ProjectConfig::save()
{ {
log_d("Saving project config"); log_d("Saving project config");
this->write("device", this->config.device);
this->write("camera", this->config.camera); this->write("device_name", this->config.device.name);
this->write("network_info", this->config.networks); this->write("ota_pass", this->config.device.OTAPassword);
this->write("ota_port", this->config.device.OTAPort);
this->write("camera_vflip", this->config.camera.vflip);
this->write("cameraFrmsz", this->config.camera.framesize);
this->write("camera_href", this->config.camera.href);
this->write("camera_quality", this->config.camera.quality);
for (int i = 0; i < this->config.networks.size(); i++)
{
char buff[25];
snprintf(buff, sizeof(buff), "%d_name", i);
this->write(buff, this->config.networks[i].name);
snprintf(buff, sizeof(buff), "%d_ssid", i);
this->write(buff, this->config.networks[i].ssid);
snprintf(buff, sizeof(buff), "%d_password", i);
this->write(buff, this->config.networks[i].password);
snprintf(buff, sizeof(buff), "%d_channel", i);
this->write(buff, this->config.networks[i].channel);
}
} }
void ProjectConfig::reset() void ProjectConfig::reset()
@ -79,8 +135,8 @@ void ProjectConfig::setDeviceConfig(const char *name, const char *OTAPassword, i
{ {
log_d("Updating device config"); log_d("Updating device config");
this->config.device = { this->config.device = {
name, (char *)name,
OTAPassword, (char *)OTAPassword,
*OTAPort, *OTAPort,
}; };
if (shouldNotify) if (shouldNotify)
@ -105,13 +161,13 @@ void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t
} }
} }
void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, const char *password, bool shouldNotify) void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, const char *password, uint8_t *channel, bool shouldNotify)
{ {
WiFiConfig_t *networkToUpdate = nullptr; WiFiConfig_t *networkToUpdate = nullptr;
for (int i = 0; i < this->config.networks.size(); i++) for (int i = 0; i < this->config.networks.size(); i++)
{ {
if (strcmp(this->config.networks[i].name, networkName) == 0) if (strcmp(this->config.networks[i].name.c_str(), networkName) == 0)
networkToUpdate = &this->config.networks[i]; networkToUpdate = &this->config.networks[i];
} }
@ -119,13 +175,29 @@ void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, con
{ {
this->config.networks = { this->config.networks = {
{ {
networkName, (char *)networkName,
ssid, (char *)ssid,
password, (char *)password,
*channel,
}, },
}; };
if (shouldNotify) if (shouldNotify)
this->notify(ObserverEvent::networksConfigUpdated); this->notify(ObserverEvent::networksConfigUpdated);
} }
log_d("Updating wifi config"); log_d("Updating wifi config");
}
void ProjectConfig::setAPWifiConfig(const char *ssid, const char *password, uint8_t *channel, bool shouldNotify)
{
this->config.ap_network = {
(char *)ssid,
(char *)password,
*channel,
};
log_d("Updating access point config");
if (shouldNotify)
{
this->notify(ObserverEvent::networksConfigUpdated);
}
} }

View File

@ -4,6 +4,7 @@
#include <Arduino.h> #include <Arduino.h>
#include <preferencesAPI.hpp> #include <preferencesAPI.hpp>
#include <vector> #include <vector>
#include <string>
#include "data/utilities/Observer.hpp" #include "data/utilities/Observer.hpp"
@ -19,8 +20,8 @@ public:
struct DeviceConfig_t struct DeviceConfig_t
{ {
const char *name; std::string name;
const char *OTAPassword; std::string OTAPassword;
int OTAPort; int OTAPort;
bool data_json; bool data_json;
bool config_json; bool config_json;
@ -40,9 +41,17 @@ public:
struct WiFiConfig_t struct WiFiConfig_t
{ {
const char *name; std::string name;
const char *ssid; std::string ssid;
const char *password; std::string password;
uint8_t channel;
};
struct AP_WiFiConfig_t
{
std::string ssid;
std::string password;
uint8_t channel;
}; };
struct TrackerConfig_t struct TrackerConfig_t
@ -50,16 +59,19 @@ public:
DeviceConfig_t device; DeviceConfig_t device;
CameraConfig_t camera; CameraConfig_t camera;
std::vector<WiFiConfig_t> networks; std::vector<WiFiConfig_t> networks;
AP_WiFiConfig_t ap_network;
}; };
DeviceConfig_t *getDeviceConfig() { return &this->config.device; } DeviceConfig_t *getDeviceConfig() { return &this->config.device; }
CameraConfig_t *getCameraConfig() { return &this->config.camera; } CameraConfig_t *getCameraConfig() { return &this->config.camera; }
std::vector<WiFiConfig_t> *getWifiConfigs() { return &this->config.networks; } std::vector<WiFiConfig_t> *getWifiConfigs() { return &this->config.networks; }
AP_WiFiConfig_t *getAPWifiConfig() { return &this->config.ap_network; }
void setDeviceConfig(const char *name, const char *OTAPassword, int *OTAPort, bool shouldNotify); void setDeviceConfig(const char *name, const char *OTAPassword, int *OTAPort, bool shouldNotify);
void setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, bool shouldNotify); void setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, bool shouldNotify);
void setWifiConfig(const char *networkName, const char *ssid, const char *password, bool shouldNotify); void setWifiConfig(const char *networkName, const char *ssid, const char *password, uint8_t *channel, bool shouldNotify);
void setAPWifiConfig(const char *ssid, const char *password, uint8_t *channel, bool shouldNotify);
private: private:
const char *configFileName; const char *configFileName;
TrackerConfig_t config; TrackerConfig_t config;

View File

@ -1,20 +1,21 @@
#include "serialmanager.hpp" #include "serialmanager.hpp"
SerialManager::SerialManager(ProjectConfig *projectConfig) : projectConfig(projectConfig), SerialManager::SerialManager(ProjectConfig *projectConfig) : projectConfig(projectConfig),
serialManagerActive(false), serialManagerActive(false),
newData(false), newData(false),
tempBuffer{0}, tempBuffer{0},
serialBuffer{0}, serialBuffer{0},
device_config_name{0}, device_config_name{0},
device_config_OTAPassword{0}, device_config_OTAPassword{0},
device_config_OTAPort(0), device_config_OTAPort(0),
camera_config_vflip{0}, camera_config_vflip{0},
camera_config_href{0}, camera_config_href{0},
camera_config_framesize{0}, camera_config_framesize{0},
camera_config_quality{0}, camera_config_quality{0},
wifi_config_name{0}, wifi_config_name{0},
wifi_config_ssid{0}, wifi_config_ssid{0},
wifi_config_password{0} {} wifi_config_password{0},
wifi_config_channel(0) {}
SerialManager::~SerialManager() {} SerialManager::~SerialManager() {}
@ -104,6 +105,9 @@ void SerialManager::parseData()
strtokIndx = strtok(NULL, ","); strtokIndx = strtok(NULL, ",");
strcpy(wifi_config_password, strtokIndx); strcpy(wifi_config_password, strtokIndx);
strtokIndx = strtok(NULL, ",");
wifi_config_channel = atoi(strtokIndx);
} }
void SerialManager::handleSerial() void SerialManager::handleSerial()
@ -115,7 +119,7 @@ void SerialManager::handleSerial()
parseData(); // split the data into tokens and store them in the data structure parseData(); // split the data into tokens and store them in the data structure
projectConfig->setDeviceConfig(device_config_name, device_config_OTAPassword, &device_config_OTAPort, true); // set the values in the project config projectConfig->setDeviceConfig(device_config_name, device_config_OTAPassword, &device_config_OTAPort, true); // set the values in the project config
projectConfig->setCameraConfig(&camera_config_vflip, &camera_config_framesize, &camera_config_href, &camera_config_quality, true); // set the values in the project config projectConfig->setCameraConfig(&camera_config_vflip, &camera_config_framesize, &camera_config_href, &camera_config_quality, true); // set the values in the project config
projectConfig->setWifiConfig(wifi_config_name, wifi_config_ssid, wifi_config_password, true); // set the values in the project config projectConfig->setWifiConfig(wifi_config_name, wifi_config_ssid, wifi_config_password, &wifi_config_channel, true); // set the values in the project config
projectConfig->save(); // save the config to the EEPROM projectConfig->save(); // save the config to the EEPROM
newData = false; // reset new data newData = false; // reset new data
} }

View File

@ -30,6 +30,7 @@ public:
char wifi_config_name[32]; char wifi_config_name[32];
char wifi_config_ssid[100]; char wifi_config_ssid[100];
char wifi_config_password[100]; char wifi_config_password[100];
uint8_t wifi_config_channel;
private: private:

View File

@ -9,7 +9,7 @@ void OTA::SetupOTA()
log_e("Setting up OTA updates"); log_e("Setting up OTA updates");
auto localConfig = _deviceConfig->getDeviceConfig(); auto localConfig = _deviceConfig->getDeviceConfig();
if (strcmp(localConfig->OTAPassword, "") == 0) if (strcmp(localConfig->OTAPassword.c_str(), "") == 0)
{ {
log_e("THE PASSWORD IS REQUIRED, [[ABORTING]]"); log_e("THE PASSWORD IS REQUIRED, [[ABORTING]]");
return; return;

View File

@ -6,25 +6,17 @@
#include "data/StateManager/StateManager.hpp" #include "data/StateManager/StateManager.hpp"
#include "data/config/project_config.hpp" #include "data/config/project_config.hpp"
extern "C"
{
#include <esp_err.h>
#include <esp_wifi.h>
#include <esp_event.h>
}
class WiFiHandler class WiFiHandler
{ {
public: public:
WiFiHandler(ProjectConfig *configManager, StateManager<WiFiState_e> *stateManager); WiFiHandler(ProjectConfig *configManager, StateManager<WiFiState_e> *stateManager);
virtual ~WiFiHandler(); virtual ~WiFiHandler();
void setupWifi(); void setupWifi();
ProjectConfig *configManager;
StateManager<WiFiState_e> *stateManager;
private:
void setUpADHOC(); void setUpADHOC();
void adhoc(const char *ssid, const char *password, uint8_t channel); void adhoc(const char *ssid, const char *password, uint8_t channel);
void setWiFiConf(const char *value, uint8_t *location, wifi_config_t *conf); void iniSTA();
std::unique_ptr<wifi_config_t> conf;
ProjectConfig *configManager;
private:
StateManager<WiFiState_e> *stateManager;
}; };
#endif // WIFIHANDLER_HPP #endif // WIFIHANDLER_HPP

View File

@ -1,132 +1,153 @@
#include "WifiHandler.hpp" #include "WifiHandler.hpp"
#include <vector> #include <vector>
WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager<WiFiState_e> *stateManager) : conf(new wifi_config_t), WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager<WiFiState_e> *stateManager) : configManager(configManager),
configManager(configManager), stateManager(stateManager) {}
stateManager(stateManager) {}
WiFiHandler::~WiFiHandler() {} WiFiHandler::~WiFiHandler() {}
void WiFiHandler::setupWifi() void WiFiHandler::setupWifi()
{ {
if (ENABLE_ADHOC || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) if (ENABLE_ADHOC || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC)
{ {
this->setUpADHOC(); this->setUpADHOC();
return; return;
} }
log_i("Initializing connection to wifi"); log_i("Initializing connection to wifi");
stateManager->setState(WiFiState_e::WiFiState_Connecting); stateManager->setState(WiFiState_e::WiFiState_Connecting);
std::vector<ProjectConfig::WiFiConfig_t> *networks = configManager->getWifiConfigs(); std::vector<ProjectConfig::WiFiConfig_t> *networks = configManager->getWifiConfigs();
int connection_timeout = 30000; // 30 seconds int connection_timeout = 30000; // 30 seconds
int count = 0; int count = 0;
unsigned long currentMillis = millis(); unsigned long currentMillis = millis();
unsigned long _previousMillis = currentMillis; unsigned long _previousMillis = currentMillis;
for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator)
{ {
log_i("Trying to connect to the %s network", networkIterator->ssid); log_i("Trying to connect to the %s network", networkIterator->ssid);
WiFi.begin(networkIterator->ssid, networkIterator->password); WiFi.begin(networkIterator->ssid.c_str(), networkIterator->password.c_str());
count++; count++;
if (!WiFi.isConnected()) if (!WiFi.isConnected())
log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid); log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid);
else else
{ {
log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid); log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid);
stateManager->setState(WiFiState_e::WiFiState_Connected); stateManager->setState(WiFiState_e::WiFiState_Connected);
return; return;
} }
while (WiFi.status() != WL_CONNECTED) while (WiFi.status() != WL_CONNECTED)
{ {
stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting); stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting);
currentMillis = millis(); currentMillis = millis();
Serial.print("."); Serial.print(".");
delay(300); delay(300);
if (((currentMillis - _previousMillis) >= connection_timeout) && count >= networks->size()) if (((currentMillis - _previousMillis) >= connection_timeout) && count >= networks->size())
{ {
log_i("[INFO]: WiFi connection timed out.\n"); log_i("[INFO]: WiFi connection timed out.\n");
// we've tried all saved networks, none worked, let's error out // we've tried all saved networks, none worked, let's error out
log_e("Could not connect to any of the save networks, check your Wifi credentials"); log_e("Could not connect to any of the save networks, check your Wifi credentials");
stateManager->setState(WiFiState_e::WiFiState_Error); stateManager->setState(WiFiState_e::WiFiState_Error);
this->setUpADHOC(); this->iniSTA();
log_w("Setting up adhoc"); log_w("Setting up adhoc");
log_w("Please set your WiFi credentials and reboot the device"); log_w("Please set your WiFi credentials and reboot the device");
stateManager->setState(WiFiState_e::WiFiState_ADHOC); stateManager->setState(WiFiState_e::WiFiState_ADHOC);
return; return;
} }
} }
} }
} }
void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel)
{ {
log_i("[INFO]: Setting Access Point...\n"); log_i("[INFO]: Setting Access Point...\n");
log_i("[INFO]: Configuring access point...\n"); log_i("[INFO]: Configuring access point...\n");
WiFi.mode(WIFI_AP); WiFi.mode(WIFI_AP);
Serial.printf("\r\nStarting AP. \r\nAP IP address: "); Serial.printf("\r\nStarting AP. \r\nAP IP address: ");
IPAddress IP = WiFi.softAPIP(); IPAddress IP = WiFi.softAPIP();
Serial.printf("[INFO]: AP IP address: %s.\r\n", IP.toString().c_str()); Serial.printf("[INFO]: AP IP address: %s.\r\n", IP.toString().c_str());
// You can remove the password parameter if you want the AP to be open. // You can remove the password parameter if you want the AP to be open.
WiFi.softAP(ssid, password, channel, 0, 3); // AP mode with password WiFi.softAP(ssid, password, channel, 0, 3); // AP mode with password
WiFi.setTxPower(WIFI_POWER_11dBm); WiFi.setTxPower(WIFI_POWER_11dBm);
stateManager->setState(WiFiState_e::WiFiState_ADHOC); stateManager->setState(WiFiState_e::WiFiState_ADHOC);
} }
/*
* *
*/
void WiFiHandler::setUpADHOC() void WiFiHandler::setUpADHOC()
{ {
size_t ssidLen = strlen((char *)conf->ap.ssid); log_i("[INFO]: Setting Access Point...\n");
size_t passwordLen = strlen((char *)conf->ap.password); size_t ssidLen = strlen(configManager->getAPWifiConfig()->ssid.c_str());
char ap_ssid[ssidLen + 1]; size_t passwordLen = strlen(configManager->getAPWifiConfig()->password.c_str());
char ap_password[passwordLen + 1]; char ssid[ssidLen + 1];
auto ret = esp_wifi_get_config(WIFI_IF_STA, &*conf); char password[passwordLen + 1];
if (ret == ESP_OK) uint8_t channel = configManager->getAPWifiConfig()->channel;
{ if (ssidLen > 0 || passwordLen > 0)
memcpy(ap_ssid, conf->ap.ssid, ssidLen); {
memcpy(ap_password, conf->ap.password, passwordLen); strcpy(ssid, configManager->getAPWifiConfig()->ssid.c_str());
strcpy(password, configManager->getAPWifiConfig()->password.c_str());
channel = configManager->getAPWifiConfig()->channel;
}
else
{
strcpy(ssid, WIFI_AP_SSID);
strcpy(password, WIFI_AP_PASSWORD);
channel = ADHOC_CHANNEL;
}
ap_ssid[ssidLen] = '\0'; // Null-terminate the string this->adhoc(ssid, password, channel);
ap_password[passwordLen] = '\0'; // Null-terminate the string
return;
}
if (ssidLen == 0)
{
strcpy(ap_ssid, WIFI_SSID);
strcpy(ap_password, WIFI_PASSWORD);
conf->ap.channel = ADHOC_CHANNEL;
}
this->adhoc(ap_ssid, ap_password, conf->ap.channel); log_i("[INFO]: Configuring access point...\n");
log_d("[DEBUG]: ssid: %s\n", ssid);
log_d("[DEBUG]: password: %s\n", password);
log_d("[DEBUG]: channel: %d\n", channel);
} }
// we can't assign wifiManager.resetSettings(); to reset, somehow it gets called straight away. void WiFiHandler::iniSTA()
/**
* @brief Resets the wifi settings to the chosen settings.
*
* @param value - value to store - string.
* @param location - location to store the value. byte array - conf
*/
void WiFiHandler::setWiFiConf(const char *value, uint8_t *location, wifi_config_t *conf)
{ {
assert(conf != nullptr); log_i("[INFO]: Setting up station...\n");
#if defined(ESP32) int connection_timeout = 30000; // 30 seconds
if (WiFiGenericClass::getMode() != WIFI_MODE_NULL) unsigned long currentMillis = millis();
{ unsigned long _previousMillis = currentMillis;
esp_wifi_get_config(WIFI_IF_STA, conf);
memset(location, 0, sizeof(location)); log_i("Trying to connect to the %s network", WIFI_SSID);
for (int i = 0; i < sizeof(value) / sizeof(value[0]) && i < sizeof(location); i++)
location[i] = value[i];
esp_wifi_set_config(WIFI_IF_STA, conf); WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
}
#endif if (!WiFi.isConnected())
log_i("\n\rCould not connect to %s, please try another network\n\r", WIFI_SSID);
else
{
log_i("\n\rSuccessfully connected to %s\n\r", WIFI_SSID);
stateManager->setState(WiFiState_e::WiFiState_Connected);
return;
}
while (WiFi.status() != WL_CONNECTED)
{
stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting);
currentMillis = millis();
Serial.print(".");
delay(300);
if ((currentMillis - _previousMillis) >= connection_timeout)
{
log_i("[INFO]: WiFi connection timed out.\n");
// we've tried all saved networks, none worked, let's error out
log_e("Could not connect to any of the save networks, check your Wifi credentials");
stateManager->setState(WiFiState_e::WiFiState_Error);
this->iniSTA();
log_w("Setting up adhoc");
log_w("Please set your WiFi credentials and reboot the device");
stateManager->setState(WiFiState_e::WiFiState_ADHOC);
return;
}
}
} }

View File

@ -4,7 +4,7 @@ void MDNSHandler::startMDNS()
{ {
ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig(); ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig();
if (MDNS.begin(deviceConfig->name)) if (MDNS.begin(deviceConfig->name.c_str()))
{ {
stateManager->setState(MDNSState_e::MDNSState_Starting); stateManager->setState(MDNSState_e::MDNSState_Starting);
MDNS.addService("openIrisTracker", "tcp", 80); MDNS.addService("openIrisTracker", "tcp", 80);

View File

@ -10,114 +10,118 @@ const char *APIServer::MIMETYPE_HTML{"text/html"};
// const char *APIServer::MIMETYPE_ICO{"image/x-icon"}; // const char *APIServer::MIMETYPE_ICO{"image/x-icon"};
const char *APIServer::MIMETYPE_JSON{"application/json"}; const char *APIServer::MIMETYPE_JSON{"application/json"};
bool APIServer::ssid_write = false;
bool APIServer::pass_write = false;
bool APIServer::channel_write = false;
//********************************************************************************************* //*********************************************************************************************
//! API Server //! API Server
//********************************************************************************************* //*********************************************************************************************
APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network) : network(network), APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network) : network(network),
server(new AsyncWebServer(CONTROL_PORT)), server(new AsyncWebServer(CONTROL_PORT)),
cameraHandler(cameraHandler) {} cameraHandler(cameraHandler) {}
void APIServer::startAPIServer() void APIServer::startAPIServer()
{ {
begin(); begin();
/* this->server->on( /* this->server->on(
"/control", "/control",
HTTP_GET, HTTP_GET,
std::bind(&APIServer::command_handler, this, std::placeholders::_1)); */ std::bind(&APIServer::command_handler, this, std::placeholders::_1)); */
//! i have changed this to use lambdas instead of std::bind to avoid the overhead. Lambdas are always more preferable. //! i have changed this to use lambdas instead of std::bind to avoid the overhead. Lambdas are always more preferable.
server->on("/", HTTP_GET, [&](AsyncWebServerRequest *request) server->on("/", HTTP_GET, [&](AsyncWebServerRequest *request)
{ request->send(200); }); { request->send(200); });
// preflight cors check // preflight cors check
server->on("/", HTTP_OPTIONS, [&](AsyncWebServerRequest *request) server->on("/", HTTP_OPTIONS, [&](AsyncWebServerRequest *request)
{ {
AsyncWebServerResponse* response = request->beginResponse(204); AsyncWebServerResponse* response = request->beginResponse(204);
response->addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS"); response->addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS");
response->addHeader("Access-Control-Allow-Headers", "Accept, Content-Type, Authorization, FileSize"); response->addHeader("Access-Control-Allow-Headers", "Accept, Content-Type, Authorization, FileSize");
response->addHeader("Access-Control-Allow-Credentials", "true"); response->addHeader("Access-Control-Allow-Credentials", "true");
request->send(response); }); request->send(response); });
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
// std::bind(&APIServer::API_Utilities::notFound, &api_utilities, std::placeholders::_1); // std::bind(&APIServer::API_Utilities::notFound, &api_utilities, std::placeholders::_1);
server->onNotFound([&](AsyncWebServerRequest *request) server->onNotFound([&](AsyncWebServerRequest *request)
{ api_utilities.notFound(request); }); { api_utilities.notFound(request); });
// Hex value of BUTT_PLUG_CONTROLLER == 425554545f504c55475f434f4e54524f4c4c4552 // Hex value of BUTT_PLUG_CONTROLLER == 425554545f504c55475f434f4e54524f4c4c4552
this->server->on("/control", HTTP_GET, [&](AsyncWebServerRequest *request) this->server->on("/control", HTTP_GET, [&](AsyncWebServerRequest *request)
{ command_handler(request); }); { command_handler(request); });
log_d("Initializing REST API"); log_d("Initializing REST API");
this->server->begin(); this->server->begin();
} }
void APIServer::findParam(AsyncWebServerRequest *request, const char *param, String &value) void APIServer::findParam(AsyncWebServerRequest *request, const char *param, String &value)
{ {
if (request->hasParam(param)) if (request->hasParam(param))
{ {
value = request->getParam(param)->value(); value = request->getParam(param)->value();
} }
} }
void APIServer::begin() void APIServer::begin()
{ {
command_map_wifi_conf.emplace("ssid", [this](const char *value) -> void command_map_wifi_conf.emplace("ssid", [this](const char *value) -> void
{ setSSID(value); }); { setSSID(value); });
command_map_wifi_conf.emplace("password", [this](const char *value) -> void command_map_wifi_conf.emplace("password", [this](const char *value) -> void
{ setPass(value); }); { setPass(value); });
command_map_wifi_conf.emplace("channel", [this](const char *value) -> void command_map_wifi_conf.emplace("channel", [this](const char *value) -> void
{ setChannel(value); }); { setChannel(value); });
command_map_funct.emplace("reboot_device", [this](void) -> void command_map_funct.emplace("reboot_device", [this](void) -> void
{ rebootDevice(); }); { rebootDevice(); });
command_map_funct.emplace("reset_config", [this](void) -> void command_map_funct.emplace("reset_config", [this](void) -> void
{ factoryReset(); }); { factoryReset(); });
command_map_json.emplace("data_json", [this](AsyncWebServerRequest *request) -> void command_map_json.emplace("data_json", [this](AsyncWebServerRequest *request) -> void
{ setDataJson(request); }); { setDataJson(request); });
command_map_json.emplace("config_json", [this](AsyncWebServerRequest *request) -> void command_map_json.emplace("config_json", [this](AsyncWebServerRequest *request) -> void
{ setConfigJson(request); }); { setConfigJson(request); });
command_map_json.emplace("settings_json", [this](AsyncWebServerRequest *request) -> void command_map_json.emplace("settings_json", [this](AsyncWebServerRequest *request) -> void
{ setSettingsJson(request); }); { setSettingsJson(request); });
} }
void APIServer::command_handler(AsyncWebServerRequest *request) void APIServer::command_handler(AsyncWebServerRequest *request)
{ {
int params = request->params(); int params = request->params();
for (int i = 0; i < params; i++) for (int i = 0; i < params; i++)
{ {
AsyncWebParameter *param = request->getParam(i); AsyncWebParameter *param = request->getParam(i);
{ {
command_map_wifi_conf_t::const_iterator it_wifi_conf = command_map_wifi_conf.find(param->name().c_str()); command_map_wifi_conf_t::const_iterator it_wifi_conf = command_map_wifi_conf.find(param->name().c_str());
command_map_funct_t::const_iterator it_funct = command_map_funct.find(param->name().c_str()); command_map_funct_t::const_iterator it_funct = command_map_funct.find(param->name().c_str());
command_map_json_t::const_iterator it_json = command_map_json.find(param->name().c_str()); command_map_json_t::const_iterator it_json = command_map_json.find(param->name().c_str());
if (it_wifi_conf != command_map_wifi_conf.end()) if (it_wifi_conf != command_map_wifi_conf.end())
{ {
command_map_wifi_conf.at(param->name().c_str())(param->value().c_str()); command_map_wifi_conf.at(param->name().c_str())(param->value().c_str());
auto &key_it = it_wifi_conf->first; auto &key_it = it_wifi_conf->first;
log_i("Command %s executed", key_it.c_str()); log_i("Command %s executed", key_it.c_str());
} }
else if (it_funct != command_map_funct.end()) else if (it_funct != command_map_funct.end())
{ {
command_map_funct.at(param->name().c_str())(); command_map_funct.at(param->name().c_str())();
auto &key_it_funct = it_funct->first; auto &key_it_funct = it_funct->first;
log_i("Command %s executed", key_it_funct.c_str()); log_i("Command %s executed", key_it_funct.c_str());
} }
else if (it_json != command_map_json.end()) else if (it_json != command_map_json.end())
{ {
command_map_json.at(param->name().c_str())(request); command_map_json.at(param->name().c_str())(request);
auto &key_it_json = it_json->first; auto &key_it_json = it_json->first;
log_i("Command %s executed", key_it_json.c_str()); log_i("Command %s executed", key_it_json.c_str());
} }
else else
{ {
log_i("Command not found"); log_i("Command not found");
} }
} }
log_i("GET[%s]: %s\n", param->name().c_str(), param->value().c_str()); log_i("GET[%s]: %s\n", param->name().c_str(), param->value().c_str());
} }
} }
//********************************************************************************************* //*********************************************************************************************
@ -125,67 +129,86 @@ void APIServer::command_handler(AsyncWebServerRequest *request)
//********************************************************************************************* //*********************************************************************************************
void APIServer::setSSID(const char *value) void APIServer::setSSID(const char *value)
{ {
#if ENABLE_ADHOC if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC)
network->setWiFiConf(value, network->conf->ap.ssid, &*network->conf); this->wifiConfig.local_WifiConfig[0].ssid = value;
#else else
network->setWiFiConf(value, network->conf->sta.ssid, &*network->conf); this->wifiConfig.local_WifiConfig[1].ssid = value;
#endif // ENABLE_ADHOC ssid_write = true;
} }
void APIServer::setPass(const char *value) void APIServer::setPass(const char *value)
{ {
#if ENABLE_ADHOC if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC)
network->setWiFiConf(network->conf->ap.password, value, &*network->conf); this->wifiConfig.local_WifiConfig[0].pass = value;
#else else
network->setWiFiConf(value, network->conf->sta.password, &*network->conf); this->wifiConfig.local_WifiConfig[1].pass = value;
#endif // ENABLE_ADHOC pass_write = true;
} }
void APIServer::setChannel(const char *value) void APIServer::setChannel(const char *value)
{ {
#if ENABLE_ADHOC if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC)
network->setWiFiConf(value, network->conf->ap.channel, &*network->conf); this->wifiConfig.local_WifiConfig[0].channel = atoi(value);
#else else
network->setWiFiConf(value, &network->conf->sta.channel, &*network->conf); this->wifiConfig.local_WifiConfig[1].channel = atoi(value);
#endif // ENABLE_ADHOC channel_write = true;
}
/**
* * Trigger in main loop to save config to flash
* ? Should we force the users to update all config params before triggering a config write?
*/
void APIServer::triggerWifiConfigWrite()
{
if (ssid_write && pass_write && channel_write)
{
ssid_write = false;
pass_write = false;
channel_write = false;
if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC)
network->configManager->setWifiConfig(wifiConfig.local_WifiConfig[0].ssid.c_str(), wifiConfig.local_WifiConfig[0].ssid.c_str(), wifiConfig.local_WifiConfig[0].pass.c_str(), &wifiConfig.local_WifiConfig[0].channel, true);
else
network->configManager->setWifiConfig(wifiConfig.local_WifiConfig[1].ssid.c_str(), wifiConfig.local_WifiConfig[1].ssid.c_str(), wifiConfig.local_WifiConfig[1].pass.c_str(), &wifiConfig.local_WifiConfig[1].channel, true);
network->configManager->save();
}
} }
void APIServer::setDataJson(AsyncWebServerRequest *request) void APIServer::setDataJson(AsyncWebServerRequest *request)
{ {
network->configManager->getDeviceConfig()->data_json = true; network->configManager->getDeviceConfig()->data_json = true;
api_utilities.my_delay(1L); api_utilities.my_delay(1L);
String temp = network->configManager->getDeviceConfig()->data_json_string; String temp = network->configManager->getDeviceConfig()->data_json_string;
request->send(200, MIMETYPE_JSON, temp); request->send(200, MIMETYPE_JSON, temp);
temp = ""; temp = "";
} }
void APIServer::setConfigJson(AsyncWebServerRequest *request) void APIServer::setConfigJson(AsyncWebServerRequest *request)
{ {
network->configManager->getDeviceConfig()->config_json = true; network->configManager->getDeviceConfig()->config_json = true;
api_utilities.my_delay(1L); api_utilities.my_delay(1L);
String temp = network->configManager->getDeviceConfig()->config_json_string; String temp = network->configManager->getDeviceConfig()->config_json_string;
request->send(200, MIMETYPE_JSON, temp); request->send(200, MIMETYPE_JSON, temp);
temp = ""; temp = "";
} }
void APIServer::setSettingsJson(AsyncWebServerRequest *request) void APIServer::setSettingsJson(AsyncWebServerRequest *request)
{ {
network->configManager->getDeviceConfig()->settings_json = true; network->configManager->getDeviceConfig()->settings_json = true;
api_utilities.my_delay(1L); api_utilities.my_delay(1L);
String temp = network->configManager->getDeviceConfig()->settings_json_string; String temp = network->configManager->getDeviceConfig()->settings_json_string;
request->send(200, MIMETYPE_JSON, temp); request->send(200, MIMETYPE_JSON, temp);
temp = ""; temp = "";
} }
void APIServer::rebootDevice() void APIServer::rebootDevice()
{ {
delay(20000); delay(20000);
ESP.restart(); ESP.restart();
} }
void APIServer::factoryReset() void APIServer::factoryReset()
{ {
network->configManager->reset(); network->configManager->reset();
} }
//********************************************************************************************* //*********************************************************************************************
@ -194,56 +217,55 @@ void APIServer::factoryReset()
APIServer::API_Utilities::API_Utilities() {} APIServer::API_Utilities::API_Utilities() {}
std::string std::string APIServer::API_Utilities::shaEncoder(std::string data)
APIServer::API_Utilities::shaEncoder(std::string data)
{ {
const char *data_c = data.c_str(); const char *data_c = data.c_str();
int size = 20; int size = 20;
uint8_t hash[size]; uint8_t hash[size];
mbedtls_md_context_t ctx; mbedtls_md_context_t ctx;
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1; mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
const size_t len = strlen(data_c); const size_t len = strlen(data_c);
mbedtls_md_init(&ctx); mbedtls_md_init(&ctx);
mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0);
mbedtls_md_starts(&ctx); mbedtls_md_starts(&ctx);
mbedtls_md_update(&ctx, (const unsigned char *)data_c, len); mbedtls_md_update(&ctx, (const unsigned char *)data_c, len);
mbedtls_md_finish(&ctx, hash); mbedtls_md_finish(&ctx, hash);
mbedtls_md_free(&ctx); mbedtls_md_free(&ctx);
std::string hash_string = ""; std::string hash_string = "";
for (uint16_t i = 0; i < size; i++) for (uint16_t i = 0; i < size; i++)
{ {
std::string hex = String(hash[i], HEX).c_str(); std::string hex = String(hash[i], HEX).c_str();
if (hex.length() < 2) if (hex.length() < 2)
{ {
hex = "0" + hex; hex = "0" + hex;
} }
hash_string += hex; hash_string += hex;
} }
return hash_string; return hash_string;
} }
void APIServer::API_Utilities::notFound(AsyncWebServerRequest *request) void APIServer::API_Utilities::notFound(AsyncWebServerRequest *request)
{ {
try try
{ {
log_i("%s", _networkMethodsMap[request->method()]); log_i("%s", _networkMethodsMap[request->method()]);
} }
catch (const std::exception &e) catch (const std::exception &e)
{ {
log_i("UNKNOWN"); log_i("UNKNOWN");
} }
log_i(" http://%s%s/\n", request->host().c_str(), request->url().c_str()); log_i(" http://%s%s/\n", request->host().c_str(), request->url().c_str());
request->send(404, "text/plain", "Not found."); request->send(404, "text/plain", "Not found.");
} }
void APIServer::API_Utilities::my_delay(volatile long delay_time) void APIServer::API_Utilities::my_delay(volatile long delay_time)
{ {
delay_time = delay_time * 1e6L; delay_time = delay_time * 1e6L;
for (volatile long count = delay_time; count > 0L; count--) for (volatile long count = delay_time; count > 0L; count--)
; ;
} }
APIServer::API_Utilities api_utilities; APIServer::API_Utilities api_utilities;

View File

@ -21,7 +21,6 @@
#include "io/camera/cameraHandler.hpp" #include "io/camera/cameraHandler.hpp"
#include "network/WifiHandler/WifiHandler.hpp" #include "network/WifiHandler/WifiHandler.hpp"
class APIServer class APIServer
{ {
private: private:
@ -62,11 +61,29 @@ private:
/* static const char *MIMETYPE_JPG; */ /* static const char *MIMETYPE_JPG; */
/* static const char *MIMETYPE_ICO; */ /* static const char *MIMETYPE_ICO; */
static const char *MIMETYPE_JSON; static const char *MIMETYPE_JSON;
static bool ssid_write;
static bool pass_write;
static bool channel_write;
struct LocalWifiConfig
{
std::string ssid;
std::string pass;
uint8_t channel;
};
struct WifiConfig
{
std::vector<LocalWifiConfig> local_WifiConfig;
};
WifiConfig wifiConfig;
public: public:
APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network); APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network);
void begin(); void begin();
void startAPIServer(); void startAPIServer();
void triggerWifiConfigWrite();
void findParam(AsyncWebServerRequest *request, const char *param, String &value); void findParam(AsyncWebServerRequest *request, const char *param, String &value);
class API_Utilities class API_Utilities

View File

@ -14,8 +14,11 @@ default_envs = esp32Cam ; do not change this value
; The below options are available for all environments ; The below options are available for all environments
; The ssid and password are requried for the trackers to connect to your network!!! ; The ssid and password are requried for the trackers to connect to your network!!!
[wifi] [wifi]
ssid="EyeTrackVR" ; your wifi network name goes here ssid="" ; your wifi network name goes here
password="test" ; Place your Wifi password here password="" ; your wifi network password goes here
channel=10 ; wifi channel
ap_ssid="EyeTrackVR" ; your AP wifi network name goes here
ap_password="test" ; Place your AP Wifi password here
OTAPassword="" ; if empty, no password will be required OTAPassword="" ; if empty, no password will be required
OTAServerPort=3232 OTAServerPort=3232
enableADHOC=0 ; 0 = disable, 1 = enable enableADHOC=0 ; 0 = disable, 1 = enable
@ -80,6 +83,8 @@ build_flags =
-DENABLE_ADHOC=${wifi.enableADHOC} ; -DENABLE_ADHOC=${wifi.enableADHOC} ;
-DADHOC_CHANNEL=${wifi.adhocChannel} ; -DADHOC_CHANNEL=${wifi.adhocChannel} ;
-DWIFI_CHANNEL=${wifi.channel} ;
'-DMDNS_TRACKER_NAME="OpenIrisTracker"' ; Set the tracker name - The string literal tells platformio to include the quatations in the string - making sure that the compiler sees the string as a cstring '-DMDNS_TRACKER_NAME="OpenIrisTracker"' ; Set the tracker name - The string literal tells platformio to include the quatations in the string - making sure that the compiler sees the string as a cstring
@ -89,6 +94,10 @@ build_flags =
'-DWIFI_PASSWORD=${wifi.password}' ; Set the users wifi network password '-DWIFI_PASSWORD=${wifi.password}' ; Set the users wifi network password
'-DWIFI_AP_SSID=${wifi.ap_ssid}' ; Set the users wifi network name
'-DWIFI_AP_PASSWORD=${wifi.ap_password}' ; Set the users wifi network password
-DDEBUG_ESP_PORT=Serial -DDEBUG_ESP_PORT=Serial
-DCORE_DEBUG_LEVEL=4 -DCORE_DEBUG_LEVEL=4

View File

@ -77,5 +77,6 @@ void loop()
{ {
ota.HandleOTAUpdate(); ota.HandleOTAUpdate();
ledManager->displayStatus(); ledManager->displayStatus();
apiServer->triggerWifiConfigWrite();
// serialManager->handleSerial(); // serialManager->handleSerial();
} }