From 1529b8b335aaf717d980f607dd8f693dfcf50dec Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 24 Jul 2022 20:26:27 +0100 Subject: [PATCH 001/153] Co-authored-by: Zdzislaw Goik --- ESP/lib/src/data/config/project_config.cpp | 110 ++++++++++++++++++ ESP/lib/src/data/config/project_config.hpp | 61 ++++++++++ .../src/io/SerialManager/serialmanager.cpp | 103 ++++++++++++++++ .../src/io/SerialManager/serialmanager.hpp | 39 +++++++ ESP/lib/src/io/camera/cameraHandler.cpp | 12 ++ ESP/lib/src/io/camera/cameraHandler.hpp | 9 +- ESP/lib/src/network/OTA/OTA.hpp | 9 +- .../src/network/WifiHandler/WifiHandler.hpp | 5 +- .../src/network/WifiHandler/wifiHandler.cpp | 59 +++++----- ESP/lib/src/network/mDNS/MDNSManager.cpp | 20 +++- ESP/lib/src/network/mDNS/MDNSManager.hpp | 18 ++- ESP/platformio.ini | 1 + 12 files changed, 403 insertions(+), 43 deletions(-) create mode 100644 ESP/lib/src/data/config/project_config.cpp create mode 100644 ESP/lib/src/data/config/project_config.hpp create mode 100644 ESP/lib/src/io/SerialManager/serialmanager.cpp create mode 100644 ESP/lib/src/io/SerialManager/serialmanager.hpp diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp new file mode 100644 index 0000000..949dcc1 --- /dev/null +++ b/ESP/lib/src/data/config/project_config.cpp @@ -0,0 +1,110 @@ +#include "project_config.hpp" + +ProjectConfig::ProjectConfig() : Config("config", "nvs"), _already_loaded(false) {} + +ProjectConfig::~ProjectConfig() {} + +/** + *@brief Initializes the structures with blank data to prevent empty memory sectors and nullptr errors. + *@brief This is to be called in setup() before loading the config. + */ +void ProjectConfig::initStructures() +{ + this->config.device = { + "", + "", + 0, + }; + this->config.camera = { + 0, + 0, + 0, + 0, + }; + this->config.networks = { + { + "", + "", + "", + }, + }; +} + +void ProjectConfig::load() +{ + log_d("Loading project config"); + + this->notify(ObserverEvent::configLoaded); +} + +void ProjectConfig::save() +{ + log_d("Saving project config"); +} + +void ProjectConfig::reset() +{ + log_d("Resetting project config"); +} + +//********************************************************************************************************************** +//* +//* DeviceConfig +//* +//********************************************************************************************************************** +void ProjectConfig::setDeviceConfig(const char *name, const char *OTAPassword, int *OTAPort, bool shouldNotify) +{ + log_d("Updating device config"); + this->config.device = { + name, + OTAPassword, + *OTAPort, + }; + if (shouldNotify) + { + this->notify(ObserverEvent::deviceConfigUpdated); + } +} + +void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, bool shouldNotify) +{ + this->config.camera = { + *vflip, + *framesize, + *href, + *quality, + }; + + log_d("Updating camera config"); + if (shouldNotify) + { + this->notify(ObserverEvent::cameraConfigUpdated); + } +} + +void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, const char *password, bool shouldNotify) +{ + WiFiConfig_t *networkToUpdate = nullptr; + + for (int i = 0; i < this->config.networks.size(); i++) + { + if (strcmp(this->config.networks[i].name, networkName) == 0) + networkToUpdate = &this->config.networks[i]; + } + + if (networkToUpdate != nullptr) + { + this->config.networks = { + { + networkName, + ssid, + password, + }, + }; + if (shouldNotify) + this->notify(ObserverEvent::networksConfigUpdated); + } + log_d("Updating wifi config"); +} + +ProjectConfig projectConfig; \ No newline at end of file diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp new file mode 100644 index 0000000..849acca --- /dev/null +++ b/ESP/lib/src/data/config/project_config.hpp @@ -0,0 +1,61 @@ +#pragma once +#include +#include +#include + +#include "data/Observer/Observer.h" + +class ProjectConfig : public Config, public ISubject +{ +public: + ProjectConfig(); + virtual ~ProjectConfig(); + void load(); + void save(); + void reset(); + void initStructures(); + + struct DeviceConfig_t + { + const char *name; + const char *OTAPassword; + int OTAPort; + }; + + struct CameraConfig_t + { + uint8_t vflip; + uint8_t framesize; + uint8_t href; + uint8_t quality; + }; + + struct WiFiConfig_t + { + const char *name; + const char *ssid; + const char *password; + }; + + struct TrackerConfig_t + { + DeviceConfig_t device{}; + CameraConfig_t camera{}; + std::vector networks; + }; + + DeviceConfig_t *getDeviceConfig() { return &this->config.device; } + CameraConfig_t *getCameraConfig() { return &this->config.camera; } + std::vector *getWifiConfigs() { return &this->config.networks; } + + 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 setWifiConfig(const char *networkName, const char *ssid, const char *password, bool shouldNotify); + +private: + const char *configFileName; + TrackerConfig_t config; + bool _already_loaded; +}; + +extern ProjectConfig projectConfig; \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp new file mode 100644 index 0000000..9f97f7c --- /dev/null +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -0,0 +1,103 @@ +#include "serialmanager.hpp" + +SerialManager::SerialManager() : serialManagerActive(false), + newData(false), + tempBuffer{0}, + serialBuffer{0}, + device_config_name{0}, + device_config_OTAPassword{0}, + device_config_OTAPort(0) {} + +SerialManager::~SerialManager() {} + +void SerialManager::listenToSerial(int timeout) +{ + log_d("Listening to serial"); + serialManagerActive = true; + Serial.setTimeout(timeout); + + static boolean recvInProgress = false; + static byte index = 0; // index + char startDelimiter = '<'; + char endDelimiter = '>'; + char receivedChar; // to test for received data on the line + + while (serialManagerActive) + { + receivedChar = Serial.read(); + if (recvInProgress) + { + if (receivedChar != endDelimiter) + { + serialBuffer[index] = receivedChar; + index++; + if (index >= sizeof(serialBuffer)) + { + log_e("Serial buffer overflow"); + index = 0; + recvInProgress = false; + } + } + else + { + recvInProgress = false; + serialBuffer[index] = '\0'; + index = 0; + newData = true; + } + } + else + { + if (receivedChar == startDelimiter) + { + recvInProgress = true; + } + } + + if (Serial.available() > 0) + { + Serial.readBytesUntil('\n', this->serialBuffer, sizeof(this->serialBuffer)); + } + delay(timeout); + serialManagerActive = false; + } +} + +void SerialManager::parseData() +{ + log_d("Parsing data"); + char *strtokIndx; // this is used by strtok() as an index + + strtokIndx = strtok(tempBuffer, ","); // get the first part - the string + strcpy(device_config_name, strtokIndx); // copy it to buffer + + strtokIndx = strtok(NULL, ","); // get the second part - the string + strcpy(device_config_OTAPassword, strtokIndx); // copy it to buffer + + strtokIndx = strtok(NULL, ","); // get the first part - the string + device_config_OTAPort = atoi(strtokIndx); // convert this part to an integer + + projectConfig.setDeviceConfig( ); // get the second part - the value + if (newData) + { + log_d("New data"); + newData = false; + char *token = strtok(serialBuffer, ","); + while (token != NULL) + { + log_d("Token: %s", token); + token = strtok(NULL, ","); + } + } +} + +void SerialManager::moveData() +{ + listenToSerial(30000); // test for serial input for 30 seconds + if (newData) // input received + { + strcpy(tempBuffer, serialBuffer); // this temporary copy is necessary to protect the original data because strtok() used in parseData() replaces the commas with \0 + parseData(); // split the data into tokens and store them in the data structure + newData = false; // reset new data + } +} diff --git a/ESP/lib/src/io/SerialManager/serialmanager.hpp b/ESP/lib/src/io/SerialManager/serialmanager.hpp new file mode 100644 index 0000000..3a8b11a --- /dev/null +++ b/ESP/lib/src/io/SerialManager/serialmanager.hpp @@ -0,0 +1,39 @@ +#pragma once +#include + +#include "data/config/project_config.hpp" + +class SerialManager +{ +public: + SerialManager(); + virtual ~SerialManager(); + + void listenToSerial(int timeout); + void parseData(); + void moveData(); + + bool serialManagerActive; + + char device_config_name[32]; + char device_config_OTAPassword[100]; + int device_config_OTAPort; + +private: + enum DataTypes_e + { + DataType_Unknown, + DataType_Device, + DataType_Camera, + DataType_Wifi, + DataType_Error, + DataType_Debug + }; + + char tempBuffer[sizeof(serialBuffer) / sizeof(serialBuffer[0])]; + char serialBuffer[100000]; //! Need to find the appropriate size for this - count the maximum possible size of a message + bool newData; + +}; + +extern SerialManager serialManager; \ No newline at end of file diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index 8ef090a..1fea831 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -81,6 +81,18 @@ int CameraHandler::setupCamera() } } +void CameraHandler::update(ObserverEvent::Event event) +{ + if (event == ObserverEvent::cameraConfigUpdated) + { + ProjectConfig::CameraConfig_t *cameraConfig = configManager->getCameraConfig(); + this->setHFlip(cameraConfig->href); + this->setVFlip(cameraConfig->vflip); + this->setCameraResolution((framesize_t)cameraConfig->framesize); + camera_sensor->set_quality(camera_sensor, cameraConfig->quality); + } +} + int CameraHandler::setCameraResolution(framesize_t frameSize) { if (camera_sensor->pixformat == PIXFORMAT_JPEG) diff --git a/ESP/lib/src/io/camera/cameraHandler.hpp b/ESP/lib/src/io/camera/cameraHandler.hpp index e23df09..1a1efec 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -1,17 +1,22 @@ #pragma once -#include "esp_camera.h" #include +#include +#include "data/Observer/Observer.h" +#include "data/config/project_config.hpp" -class CameraHandler +class CameraHandler : IObserver { private: sensor_t *camera_sensor; camera_config_t config; + ProjectConfig *configManager; public: + CameraHandler(ProjectConfig *configManager) : configManager(configManager) {} int setupCamera(); int setCameraResolution(framesize_t frameSize); int setVFlip(int direction); int setHFlip(int direction); int setVieWindow(int offsetX, int offsetY, int outputX, int outputY); + void update(ObserverEvent::Event event); }; diff --git a/ESP/lib/src/network/OTA/OTA.hpp b/ESP/lib/src/network/OTA/OTA.hpp index bbc469d..7e22983 100644 --- a/ESP/lib/src/network/OTA/OTA.hpp +++ b/ESP/lib/src/network/OTA/OTA.hpp @@ -1,22 +1,23 @@ #pragma once #include - +#include "data/config/project_config.hpp" class OTA { private: bool isOTAEnabled = false; public: - void SetupOTA(const char *OTAPassword, uint16_t OTAServerPort) + void SetupOTA(ProjectConfig *configManager) { log_i("Setting up OTA updates"); + ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig(); - if (OTAPassword == nullptr) + if (deviceConfig->OTAPassword == nullptr) { log_e("THE PASSWORD IS REQUIRED, [[ABORTING]]"); return; } - ArduinoOTA.setPort(OTAServerPort); + ArduinoOTA.setPort(deviceConfig->OTAPort); isOTAEnabled = true; ArduinoOTA diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index d989d30..7ad6b0e 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -1,8 +1,9 @@ #pragma once #include -#include "../../data/StateManager/StateManager.hpp" +#include "data/StateManager/StateManager.hpp" +#include "data/config/project_config.hpp" namespace WiFiHandler { - void setupWifi(const char *ssid, const char *password, StateManager *stateManager); + void setupWifi(StateManager *stateManager, ProjectConfig *configManager); } diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index f389cce..5da4eb2 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -1,36 +1,41 @@ #include "WifiHandler.hpp" +#include -void WiFiHandler::setupWifi(const char *ssid, const char *password, StateManager *stateManager) +void WiFiHandler::setupWifi(StateManager *stateManager, ProjectConfig *configManager) { - log_d("Initializing connection to wifi"); + log_i("Initializing connection to wifi"); + stateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting)); - WiFi.begin(ssid, password); + std::vector *networks = configManager->getWifiConfigs(); + int connection_timeout = 3000; - log_d("connecting"); - int time_spent_connecting = 0; - int connection_timeout = 6400; - int wifi_status = WiFi.status(); - - while (time_spent_connecting < connection_timeout || wifi_status != WL_CONNECTED) + for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) { - wifi_status = WiFi.status(); - Serial.print("."); - stateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting)); - time_spent_connecting += 1600; - delay(1600); + log_i("Trying to connect to the %s network", networkIterator->ssid); + + int timeSpentConnecting = 0; + WiFi.begin(networkIterator->ssid, networkIterator->password); + int wifi_status = WiFi.status(); + + while (timeSpentConnecting < connection_timeout || wifi_status != WL_CONNECTED) + { + wifi_status = WiFi.status(); + log_i("."); + timeSpentConnecting += 300; + delay(300); + } + + if (!WiFi.isConnected()) + log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid); + else + { + log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid); + stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected); + return; + } } - if (wifi_status == WL_CONNECTED) - { - stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected); - delay(1600); - log_i("\n\rWiFi connected\n\r"); - log_i("ESP will be streaming under 'http://%s:80/\r\n", WiFi.localIP().toString().c_str()); - log_i("ESP will be accepting commands under 'http://%s:81/control\r\n", WiFi.localIP().toString().c_str()); - } - else - { - stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error); - return; - } + // 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(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error); } diff --git a/ESP/lib/src/network/mDNS/MDNSManager.cpp b/ESP/lib/src/network/mDNS/MDNSManager.cpp index d15cba1..ae1ee43 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.cpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.cpp @@ -1,17 +1,29 @@ #include "MDNSManager.hpp" -void MDNSHandler::setupMDNS(const char *trackerName, StateManager *stateManager) +void MDNSHandler::startMDNS() { - if (MDNS.begin(trackerName)) + ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig(); + + if (MDNS.begin(deviceConfig->name)) { - stateManager->setState(ProgramStates::DeviceStates::MDNSState_e::MDNSState_Started); + stateManager->setState(ProgramStates::DeviceStates::MDNSState_e::MDNSState_Starting); MDNS.addService("openIrisTracker", "tcp", 80); MDNS.addServiceTxt("openIrisTracker", "tcp", "stream_port", String(80)); - log_d("MDNS initialized!"); + log_i("MDNS initialized!"); + stateManager->setState(ProgramStates::DeviceStates::MDNSState_e::MDNSState_Started); } else { stateManager->setState(ProgramStates::DeviceStates::MDNSState_e::MDNSState_Error); log_e("Error initializing MDNS"); } +} + +void MDNSHandler::update(ObserverEvent::Event event) +{ + if (event == ObserverEvent::deviceConfigUpdated) + { + MDNS.end(); + startMDNS(); + } } \ No newline at end of file diff --git a/ESP/lib/src/network/mDNS/MDNSManager.hpp b/ESP/lib/src/network/mDNS/MDNSManager.hpp index 1a18e18..261726b 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.hpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.hpp @@ -1,7 +1,17 @@ #pragma once #include -#include "../../data/StateManager/StateManager.hpp" -namespace MDNSHandler +#include "data/StateManager/StateManager.hpp" +#include "data/Observer/Observer.h" +#include "data/config/project_config.hpp" + +class MDNSHandler : public IObserver { - void setupMDNS(const char *trackerName, StateManager *stateManager); -} +private: + StateManager *stateManager; + ProjectConfig *configManager; + +public: + MDNSHandler(StateManager *stateManager, Configuration *trackerConfig) : stateManager(stateManager), trackerConfig(trackerConfig) {} + void startMDNS(); + void update(ObserverEvent::Event event); +}; \ No newline at end of file diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 48fdc7b..a9db1e6 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -95,6 +95,7 @@ lib_deps = me-no-dev/AsyncTCP@^1.1.1 me-no-dev/ESP Async WebServer@^1.2.3 esp32-camera + https://github.com/ZanzyTHEbar/EasyPreferencesLibrary.git [env:debug] platform = ${common.platform} From 4a8ebffa82da544ceab1f0a30467f87970dae957 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 24 Jul 2022 21:52:30 +0100 Subject: [PATCH 002/153] update - Completed Serial Manager --- ESP/lib/src/data/config/project_config.hpp | 4 +- .../src/io/SerialManager/serialmanager.cpp | 81 +++++++++++++------ .../src/io/SerialManager/serialmanager.hpp | 21 ++++- 3 files changed, 75 insertions(+), 31 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 849acca..9c09207 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -39,8 +39,8 @@ public: struct TrackerConfig_t { - DeviceConfig_t device{}; - CameraConfig_t camera{}; + DeviceConfig_t device; + CameraConfig_t camera; std::vector networks; }; diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp index 9f97f7c..9ef75f8 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -6,24 +6,32 @@ SerialManager::SerialManager() : serialManagerActive(false), serialBuffer{0}, device_config_name{0}, device_config_OTAPassword{0}, - device_config_OTAPort(0) {} + device_config_OTAPort(0), + camera_config_vflip{0}, + camera_config_href{0}, + camera_config_framesize{0}, + camera_config_quality{0}, + wifi_config_name{0}, + wifi_config_ssid{0}, + wifi_config_password{0} {} SerialManager::~SerialManager() {} -void SerialManager::listenToSerial(int timeout) +void SerialManager::listenToSerial(unsigned long timeout) { log_d("Listening to serial"); serialManagerActive = true; Serial.setTimeout(timeout); - static boolean recvInProgress = false; - static byte index = 0; // index - char startDelimiter = '<'; - char endDelimiter = '>'; - char receivedChar; // to test for received data on the line + static bool recvInProgress = false; + static uint8_t index = 0; // index + char startDelimiter = '<'; //! we need to decide on a delimiter for the start of a message + char endDelimiter = '>'; //! we need to decide on a delimiter for the end of a message + char receivedChar; // to test for received data on the line - while (serialManagerActive) + while ((Serial.available() > 0) && !newData) { + serialManagerActive = true; receivedChar = Serial.read(); if (recvInProgress) { @@ -53,11 +61,6 @@ void SerialManager::listenToSerial(int timeout) recvInProgress = true; } } - - if (Serial.available() > 0) - { - Serial.readBytesUntil('\n', this->serialBuffer, sizeof(this->serialBuffer)); - } delay(timeout); serialManagerActive = false; } @@ -68,36 +71,64 @@ void SerialManager::parseData() log_d("Parsing data"); char *strtokIndx; // this is used by strtok() as an index - strtokIndx = strtok(tempBuffer, ","); // get the first part - the string + //! Parse the data + //* Device Config *// + strtokIndx = strtok(tempBuffer, ","); // get the first part strcpy(device_config_name, strtokIndx); // copy it to buffer - strtokIndx = strtok(NULL, ","); // get the second part - the string - strcpy(device_config_OTAPassword, strtokIndx); // copy it to buffer + strtokIndx = strtok(NULL, ","); // get the second part + strcpy(device_config_OTAPassword, strtokIndx); - strtokIndx = strtok(NULL, ","); // get the first part - the string - device_config_OTAPort = atoi(strtokIndx); // convert this part to an integer + strtokIndx = strtok(NULL, ","); + device_config_OTAPort = atoi(strtokIndx); - projectConfig.setDeviceConfig( ); // get the second part - the value - if (newData) + //* Camera Config *// + strtokIndx = strtok(NULL, ","); + camera_config_vflip = atoi(strtokIndx); + + strtokIndx = strtok(NULL, ","); + camera_config_framesize = atoi(strtokIndx); + + strtokIndx = strtok(NULL, ","); + camera_config_href = atoi(strtokIndx); + + strtokIndx = strtok(NULL, ","); + camera_config_quality = atoi(strtokIndx); + + //* Wifi Config *// + strtokIndx = strtok(tempBuffer, ","); + strcpy(wifi_config_name, strtokIndx); + + strtokIndx = strtok(NULL, ","); + strcpy(wifi_config_ssid, strtokIndx); + + strtokIndx = strtok(NULL, ","); + strcpy(wifi_config_password, strtokIndx); + + /* if (newData) { log_d("New data"); newData = false; - char *token = strtok(serialBuffer, ","); + char *token = strtok(tempBuffer, ","); while (token != NULL) { log_d("Token: %s", token); token = strtok(NULL, ","); } - } + } */ } -void SerialManager::moveData() +void SerialManager::handleSerial() { - listenToSerial(30000); // test for serial input for 30 seconds - if (newData) // input received + listenToSerial(30000L); // test for serial input for 30 seconds + if (newData) // input received { strcpy(tempBuffer, serialBuffer); // this temporary copy is necessary to protect the original data because strtok() used in parseData() replaces the commas with \0 parseData(); // split the data into tokens and store them in the data structure newData = false; // reset new data } + + 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.setWifiConfig(wifi_config_name, wifi_config_ssid, wifi_config_password, true); // set the values in the project config } diff --git a/ESP/lib/src/io/SerialManager/serialmanager.hpp b/ESP/lib/src/io/SerialManager/serialmanager.hpp index 3a8b11a..7549183 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.hpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.hpp @@ -9,17 +9,30 @@ public: SerialManager(); virtual ~SerialManager(); - void listenToSerial(int timeout); - void parseData(); - void moveData(); + void handleSerial(); bool serialManagerActive; + /* Device Config Variables */ char device_config_name[32]; char device_config_OTAPassword[100]; int device_config_OTAPort; + /* Camera Config Variables */ + uint8_t camera_config_vflip; + uint8_t camera_config_framesize; + uint8_t camera_config_href; + uint8_t camera_config_quality; + + /* Wifi Config Variables */ + char wifi_config_name[32]; + char wifi_config_ssid[100]; + char wifi_config_password[100]; + private: + + void listenToSerial(unsigned long timeout); + void parseData(); enum DataTypes_e { DataType_Unknown, @@ -30,8 +43,8 @@ private: DataType_Debug }; - char tempBuffer[sizeof(serialBuffer) / sizeof(serialBuffer[0])]; char serialBuffer[100000]; //! Need to find the appropriate size for this - count the maximum possible size of a message + char tempBuffer[sizeof(serialBuffer) / sizeof(serialBuffer[0])]; bool newData; }; From f3606676f98db48a41f569be9a585fe71b3b0991 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 24 Jul 2022 21:58:13 +0100 Subject: [PATCH 003/153] implemented: - save, load, reset functions for config --- ESP/lib/src/data/config/project_config.cpp | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 949dcc1..ad117e1 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -33,18 +33,36 @@ void ProjectConfig::initStructures() void ProjectConfig::load() { log_d("Loading project config"); - + if (this->_already_loaded) + { + log_d("Project config already loaded"); + return; + } + bool device_success = this->read("device", this->config.device); + bool camera_success = this->read("camera", this->config.camera); + bool network_info_success = this->read("network_info", this->config.networks); + if (!device_success || !camera_success || !network_info_success) + { + log_e("Failed to load project config"); + this->_already_loaded = false; + return; + } + this->_already_loaded = false; this->notify(ObserverEvent::configLoaded); } void ProjectConfig::save() { log_d("Saving project config"); + this->write("device", this->config.device); + this->write("camera", this->config.camera); + this->write("network_info", this->config.networks); } void ProjectConfig::reset() { - log_d("Resetting project config"); + log_w("Resetting project config"); + this->clear(); } //********************************************************************************************************************** From aebe2ae870ce77e0a4b3d0c833d267222383bf4e Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 24 Jul 2022 22:00:37 +0100 Subject: [PATCH 004/153] formatting --- ESP/lib/src/data/config/project_config.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index ad117e1..0a07131 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -35,18 +35,20 @@ void ProjectConfig::load() log_d("Loading project config"); if (this->_already_loaded) { - log_d("Project config already loaded"); + log_w("Project config already loaded"); return; } + bool device_success = this->read("device", this->config.device); bool camera_success = this->read("camera", this->config.camera); bool network_info_success = this->read("network_info", this->config.networks); + if (!device_success || !camera_success || !network_info_success) { log_e("Failed to load project config"); - this->_already_loaded = false; return; } + this->_already_loaded = false; this->notify(ObserverEvent::configLoaded); } From 496e4f31a2f359106d0e3cb003e281f14986ad40 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 28 Jul 2022 05:14:25 +0100 Subject: [PATCH 005/153] create library.json --- ESP/lib/library.json | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/ESP/lib/library.json b/ESP/lib/library.json index e69de29..dbcf95b 100644 --- a/ESP/lib/library.json +++ b/ESP/lib/library.json @@ -0,0 +1,26 @@ +{ + "name": "OpenIris", + "keywords": "esp32S, openiris, openiris-esp32s, webcam, streaming server", + "description": "openiris library", + "authors": [ + { + "name": "lorow", + "url": "https://github.com/lorow" + }, + { + "name": "ZanzyTHEbar", + "url": "https://github.com/ZanzyTHEbar" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/lorow/OpenIris.git" + }, + "export": { + "include": "/lib/src" + }, + "dependencies": {}, + "version": "0.0.1", + "frameworks": "arduino", + "platforms": "espressif32" +} \ No newline at end of file From 1d998b28d1267a559c23385562c4283651008bc7 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 28 Jul 2022 05:41:52 +0100 Subject: [PATCH 006/153] update - Fix paths for includes - Set _already_loaded to true at end of load method. --- ESP/lib/src/data/config/project_config.cpp | 2 +- ESP/lib/src/network/webserver/webserverHandler.hpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 0a07131..d487189 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -49,7 +49,7 @@ void ProjectConfig::load() return; } - this->_already_loaded = false; + this->_already_loaded = true; this->notify(ObserverEvent::configLoaded); } diff --git a/ESP/lib/src/network/webserver/webserverHandler.hpp b/ESP/lib/src/network/webserver/webserverHandler.hpp index 0d0ac97..31959e3 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.hpp +++ b/ESP/lib/src/network/webserver/webserverHandler.hpp @@ -1,5 +1,5 @@ #pragma once -#include "../../io/camera/cameraHandler.hpp" +#include "io/camera/cameraHandler.hpp" #define WEBSERVER_H #define HTTP_ANY 0b01111111 #define HTTP_GET 0b00000001 From 2524102da584c43c9f587166db6b64fed04990bf Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 28 Jul 2022 05:58:10 +0100 Subject: [PATCH 007/153] added comments in webserver + example on unique_ptr --- .../network/webserver/webserverHandler.cpp | 5 +++++ .../network/webserver/webserverHandler.hpp | 19 ++++++++++++------- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/ESP/lib/src/network/webserver/webserverHandler.cpp b/ESP/lib/src/network/webserver/webserverHandler.cpp index 36e4a93..cb9aed0 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.cpp +++ b/ESP/lib/src/network/webserver/webserverHandler.cpp @@ -1,5 +1,10 @@ #include "webserverHandler.hpp" +/* Constructor with unique_ptr */ +/* +APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler) : server(new AsyncWebServer(CONTROL_PORT)), cameraHandler(cameraHandler) {} +*/ + APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler) { this->server = new AsyncWebServer(CONTROL_PORT); diff --git a/ESP/lib/src/network/webserver/webserverHandler.hpp b/ESP/lib/src/network/webserver/webserverHandler.hpp index 31959e3..a838f08 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.hpp +++ b/ESP/lib/src/network/webserver/webserverHandler.hpp @@ -1,19 +1,24 @@ #pragma once +#include +#include #include "io/camera/cameraHandler.hpp" + #define WEBSERVER_H #define HTTP_ANY 0b01111111 #define HTTP_GET 0b00000001 -#include -#include class APIServer { private: - void command_handler(AsyncWebServerRequest *request); - AsyncWebServer *server; - CameraHandler *cameraHandler; + void command_handler(AsyncWebServerRequest *request); + + /* I think we should make these unique_ptr */ + //std::unique_ptr server; + //std::unique_ptr cameraHandler; + AsyncWebServer *server; + CameraHandler *cameraHandler; public: - APIServer(int CONTROL_PORT, CameraHandler *cameraHandler); - void startAPIServer(); + APIServer(int CONTROL_PORT, CameraHandler *cameraHandler); + void startAPIServer(); }; From 19e0a66a46c88674008aabf75d2fd0e5c4113c51 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 30 Jul 2022 17:32:37 +0100 Subject: [PATCH 008/153] successfully compiles --- ESP/lib/src/io/camera/cameraHandler.hpp | 1 + ESP/lib/src/network/mDNS/MDNSManager.hpp | 2 +- ESP/lib/src/network/webserver/webserverHandler.hpp | 5 +++-- ESP/platformio.ini | 4 ++-- ESP/src/main.cpp | 9 +++++---- 5 files changed, 12 insertions(+), 9 deletions(-) diff --git a/ESP/lib/src/io/camera/cameraHandler.hpp b/ESP/lib/src/io/camera/cameraHandler.hpp index 1a1efec..37fbc07 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -12,6 +12,7 @@ private: ProjectConfig *configManager; public: + CameraHandler(ProjectConfig *configManager) : configManager(configManager) {} int setupCamera(); int setCameraResolution(framesize_t frameSize); diff --git a/ESP/lib/src/network/mDNS/MDNSManager.hpp b/ESP/lib/src/network/mDNS/MDNSManager.hpp index 261726b..5fb2d04 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.hpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.hpp @@ -11,7 +11,7 @@ private: ProjectConfig *configManager; public: - MDNSHandler(StateManager *stateManager, Configuration *trackerConfig) : stateManager(stateManager), trackerConfig(trackerConfig) {} + MDNSHandler(StateManager *stateManager, ProjectConfig *configManager) : stateManager(stateManager), configManager(configManager) {} void startMDNS(); void update(ObserverEvent::Event event); }; \ No newline at end of file diff --git a/ESP/lib/src/network/webserver/webserverHandler.hpp b/ESP/lib/src/network/webserver/webserverHandler.hpp index a838f08..f3bb15e 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.hpp +++ b/ESP/lib/src/network/webserver/webserverHandler.hpp @@ -1,12 +1,13 @@ #pragma once -#include -#include #include "io/camera/cameraHandler.hpp" #define WEBSERVER_H #define HTTP_ANY 0b01111111 #define HTTP_GET 0b00000001 +#include +#include + class APIServer { private: diff --git a/ESP/platformio.ini b/ESP/platformio.ini index a9db1e6..d762dcf 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -92,10 +92,10 @@ lib_ldf_mode = deep+ upload_speed = 921600 release_version = 0.0.1 ; increase this value every release build lib_deps = - me-no-dev/AsyncTCP@^1.1.1 - me-no-dev/ESP Async WebServer@^1.2.3 esp32-camera https://github.com/ZanzyTHEbar/EasyPreferencesLibrary.git + https://github.com/me-no-dev/ESPAsyncWebServer.git + https://github.com/me-no-dev/AsyncTCP.git [env:debug] platform = ${common.platform} diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 185131e..3324f2c 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include @@ -13,9 +14,10 @@ int CONTROL_SERVER_PORT = 81; OTA ota; LEDManager ledManager(33); -CameraHandler cameraHandler; +CameraHandler cameraHandler(&projectConfig); APIServer apiServer(CONTROL_SERVER_PORT, &cameraHandler); StreamServer streamServer(STREAM_SERVER_PORT); +MDNSHandler mdnsHandler(&mdnsStateManager, &projectConfig); void setup() { @@ -24,8 +26,7 @@ void setup() ledManager.begin(); cameraHandler.setupCamera(); - WiFiHandler::setupWifi(WIFI_SSID, WIFI_PASSWORD, &wifiStateManager); - MDNSHandler::setupMDNS(MDNS_TRACKER_NAME, &mdnsStateManager); + WiFiHandler::setupWifi(&wifiStateManager, &projectConfig); if (wifiStateManager.getCurrentState() == ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected) { @@ -35,7 +36,7 @@ void setup() ledManager.onOff(true); - ota.SetupOTA(OTA_PASSWORD, OTA_SERVER_PORT); + ota.SetupOTA(&projectConfig); } void loop() From 151b01251e034058ca508be0c007397edeb06c54 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 30 Jul 2022 17:50:21 +0100 Subject: [PATCH 009/153] update - Changed SerialManager to only set the config on newData - Changed serial manager to save to flash after all configs set - Changed main init config structs and load config --- .../src/io/SerialManager/serialmanager.cpp | 20 ++++--------------- ESP/src/main.cpp | 5 ++--- 2 files changed, 6 insertions(+), 19 deletions(-) diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp index 9ef75f8..d3e948e 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -104,18 +104,6 @@ void SerialManager::parseData() strtokIndx = strtok(NULL, ","); strcpy(wifi_config_password, strtokIndx); - - /* if (newData) - { - log_d("New data"); - newData = false; - char *token = strtok(tempBuffer, ","); - while (token != NULL) - { - log_d("Token: %s", token); - token = strtok(NULL, ","); - } - } */ } void SerialManager::handleSerial() @@ -125,10 +113,10 @@ void SerialManager::handleSerial() { strcpy(tempBuffer, serialBuffer); // this temporary copy is necessary to protect the original data because strtok() used in parseData() replaces the commas with \0 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.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.save(); // save the config to the EEPROM newData = false; // reset new data } - - 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.setWifiConfig(wifi_config_name, wifi_config_ssid, wifi_config_password, true); // set the values in the project config } diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 3324f2c..5be5f95 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -24,6 +24,8 @@ void setup() Serial.begin(115200); Serial.setDebugOutput(true); ledManager.begin(); + projectConfig.initStructures(); + projectConfig.load(); cameraHandler.setupCamera(); WiFiHandler::setupWifi(&wifiStateManager, &projectConfig); @@ -33,9 +35,6 @@ void setup() apiServer.startAPIServer(); streamServer.startStreamServer(); } - - ledManager.onOff(true); - ota.SetupOTA(&projectConfig); } From 7f21952cf29bc0d3ad2d7328bcf5fb120eb28c70 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 30 Jul 2022 18:27:18 +0100 Subject: [PATCH 010/153] update - add better more flushed out serialmanager class - move mdns object initialisation call above the streamserer call --- .../SerialManager2/serialmanager.cpp | 317 ++++++++++++++++++ .../SerialManager2/serialmanager.hpp | 151 +++++++++ ESP/src/main.cpp | 3 +- 3 files changed, 470 insertions(+), 1 deletion(-) create mode 100644 ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp create mode 100644 ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp diff --git a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp new file mode 100644 index 0000000..12b62cd --- /dev/null +++ b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp @@ -0,0 +1,317 @@ +#include "serialmanager.hpp" + +#if SERIAL_CMD_DBG_EN + +static void printHex(Stream &port, uint8_t *data, uint8_t length); +static void printHex(Stream &port, uint16_t *data, uint8_t length); + +void printHex(Stream &port, uint8_t *data, uint8_t length) // prints 8-bit data in hex with leading zeroes +{ + for (int i = 0; i < length; i++) + { + // port.print("0x"); + if (data[i] < 0x10) + { + port.print("0"); + } + port.print(data[i], HEX); + port.print(" "); + } +} + +void printHex(Stream &port, uint16_t *data, uint8_t length) // prints 16-bit data in hex with leading zeroes +{ + for (int i = 0; i < length; i++) + { + // port.print("0x"); + uint8_t MSB = byte(data[i] >> 8); + uint8_t LSB = byte(data[i]); + if (MSB < 0x10) + { + port.print("0"); + } + port.print(MSB, HEX); + if (LSB < 0x10) + { + port.print("0"); + } + port.print(LSB, HEX); + port.print(" "); + } +} +#endif + +SerialManager::SerialManager() : userErrorHandler(NULL), _serial(NULL), ManagerCount(0) +{ + clear(); +} + +void SerialManager::begin(Stream &serialPort) +{ + /* Save Serial Port configurations */ + _serial = &serialPort; +} + +// This checks the Serial stream for characters, and assembles them into a buffer. +// When the terminator character (defined by EOL constant) is seen, it starts parsing the +// buffer for a prefix Manager, and calls handlers setup by addManager() method +void SerialManager::loop(void) +{ + char c; + while (available() > 0) + { + c = read(); + bufferHandler(c); + } +} + +/* Clear buffer */ +void SerialManager::clear(void) +{ + memset(buffer, 0, SERIAL_CMD_BUFF_LEN); + pBuff = buffer; +} + +/* + * Send error response + * NOTE: Will execute user defined callback (defined using addDefault method), + * if no user defined callback it will send the ERROR message (sendERROR method). + */ +void SerialManager::error(void) +{ + if (NULL != userErrorHandler) + { + (*userErrorHandler)(); + } + + clear(); /* Clear buffer */ +} + +// Retrieve the next token ("word" or "argument") from the Manager buffer. +// returns a NULL if no more tokens exist. +char *SerialManager::next(void) +{ + return strtok_r(NULL, delimiters, &last); +} + +void SerialManager::bufferHandler(char c) +{ + int len; + char *lastChars = NULL; + + if ((pBuff - buffer) > (SERIAL_CMD_BUFF_LEN - 2)) /* Check buffer overflow */ + { + error(); /* Send ERROR, Buffer overflow */ + } + + *pBuff++ = c; /* Put character into buffer */ + *pBuff = '\0'; /* Always null terminate strings */ + + if ((pBuff - buffer) > 2) /* Check buffer length */ + { + /* Get EOL */ + len = strlen(buffer); + lastChars = buffer + len - 2; + + /* Compare last chars to EOL */ + if (0 == strcmp(lastChars, EOL)) + { + + // *lastChars = '\0'; /* Replace EOL with NULL terminator */ + +#if (SERIAL_CMD_DBG_EN == 1) + print("Received: "); + println(buffer); +#endif + + if (ManagerHandler()) + { + clear(); + } + else + { + error(); + } + } + } +} + +/* Return true if match was found */ +bool SerialManager::ManagerHandler(void) +{ + int i; + bool ret = false; + char *token = NULL; + char *offset = NULL; + char userInput[SERIAL_CMD_BUFF_LEN]; + + memcpy(userInput, buffer, SERIAL_CMD_BUFF_LEN); + + /* Search for Manager at start of buffer */ + token = strtok_r(buffer, delimiters, &last); + +#if SERIAL_CMD_DBG_EN + print("User input: ("); + printHex(Serial, (uint8_t *)userInput, SERIAL_CMD_BUFF_LEN); + println(")"); +#endif + + if (NULL != token) + { + +#if SERIAL_CMD_DBG_EN + print("Token: \""); + print(token); + println("\""); +#endif + + for (i = 0; (i < ManagerCount); i++) + { + +#if SERIAL_CMD_DBG_EN + print("Case: \""); + print(ManagerList[i].Manager); + print("\" "); +#endif + + /* Compare the token against the list of known Managers */ + if (0 == strncmp(token, ManagerList[i].Manager, SERIAL_CMD_BUFF_LEN)) + { + +#if SERIAL_CMD_DBG_EN + println("- Match Found!"); +#endif + offset = (char *)(userInput + strlen(token)); + + /* Check for query Manager */ + if (0 == strncmp(offset, "=?", 2)) + { +#if SERIAL_CMD_DBG_EN + println("Run test callback"); +#endif + if (NULL != *ManagerList[i].test) + { + /* Run test callback */ + (*ManagerList[i].test)(); + } + } + else if (('?' == *offset) && (NULL != *ManagerList[i].read)) + { +#if SERIAL_CMD_DBG_EN + println("Run read callback"); +#endif + /* Run read callback */ + (*ManagerList[i].read)(); + } + else if (('=' == *offset) && (NULL != *ManagerList[i].write)) + { +#if (SERIAL_CMD_DBG_EN == 1) + println("Run write callback"); +#endif + /* Run write callback */ + (*ManagerList[i].write)(); + } + else if (NULL != *ManagerList[i].execute) + { +#if SERIAL_CMD_DBG_EN + println("Run execute callback"); +#endif + /* Run execute callback */ + (*ManagerList[i].execute)(); + } + else + { + println("INVALID"); + ret = false; + break; + } + + ret = true; + break; + } + +#if SERIAL_CMD_DBG_EN + else + { + println("- Not a match!"); + } +#endif + } + } + + return ret; +} + +// Adds a "Manager" and a handler function to the list of available Managers. +// This is used for matching a found token in the buffer, and gives the pointer +// to the handler function to deal with it. +void SerialManager::addManager(char *cmd, void (*test)(), void (*read)(), void (*write)(), void (*execute)()) +{ + +#if SERIAL_CMD_DBG_EN + print("["); + print(ManagerCount); + print("] New Manager: "); + println(cmd); +#endif + + ManagerList = (serialManagerCallback *)realloc(ManagerList, (ManagerCount + 1) * sizeof(serialManagerCallback)); + strncpy(ManagerList[ManagerCount].Manager, cmd, SERIAL_CMD_BUFF_LEN); + ManagerList[ManagerCount].test = test; + ManagerList[ManagerCount].read = read; + ManagerList[ManagerCount].write = write; + ManagerList[ManagerCount].execute = execute; + ManagerCount++; +} + +/* Optional user-defined function to call when an error occurs, default is NULL */ +void SerialManager::addError(void (*callback)()) +{ + userErrorHandler = callback; +} + +int SerialManager::available() +{ + int bytes = 0; + if (NULL != _serial) + { + bytes = _serial->available(); + } + return bytes; +} + +int SerialManager::read() +{ + int bytes = 0; + if (NULL != _serial) + { + bytes = _serial->read(); + } + return bytes; +} + +int SerialManager::peek() +{ + int bytes = 0; + if (NULL != _serial) + { + bytes = _serial->peek(); + } + return bytes; +} + +void SerialManager::flush() +{ + if (NULL != _serial) + { + _serial->flush(); + } +} + +size_t SerialManager::write(uint8_t x) +{ + (void)x; + return 0; +} + +SerialManager serialManager; \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp new file mode 100644 index 0000000..b9a25a4 --- /dev/null +++ b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp @@ -0,0 +1,151 @@ +#ifndef SERIALMANAGER_HPP +#define SERIALMANAGER_HPP +#include +#include + +#define SERIAL_CMD_DBG_EN 0 +#define SERIAL_CMD_BUFF_LEN 64 /* Max length for each serial Manager */ + +/* Data structure to hold Manager/Handler function key-value pairs */ +typedef struct +{ + char Manager[SERIAL_CMD_BUFF_LEN]; + void (*test)(); + void (*read)(); + void (*write)(); + void (*execute)(); +} serialManagerCallback; + +/* + * Token delimiters (setup '=', query '?', separator ',') + */ +const char delimiters[] = "=,?\r\n"; + +/* + * End Of Line: + * = + * = + */ +const char EOL[] = "\r\n"; + +class SerialManager : public Stream +{ +public: + SerialManager(); + virtual ~SerialManager(); + + /** + * Start connection to serial port + * + * @param serialPort - Serial port to listen for Managers + * @param baud - Baud rate + */ + void begin(Stream &serialPort); + + /** + * Execute this function inside Arduino's loop function. + */ + void loop(void); + + /** + * Add a new Manager + * + * @param cmd - Manager to listen + * @param test - Test Manager callback + * @param read - Read Manager callback + * @param write - Write Manager callback + * @param execute - Execute Manager callback + */ + void addManager(char *cmd, void (*test)(), void (*read)(), void (*write)(), void (*execute)()); + + /** + * Add a read-only Manager + * + * @param cmd - Manager to listen + * @param callback - Read Manager callback + */ + void addTestManager(char *cmd, void (*callback)()) + { + addManager(cmd, callback, NULL, NULL, NULL); + } + + /** + * Add a read-only Manager + * + * @param cmd - Manager to listen + * @param callback - Read Manager callback + */ + void addReadManager(char *cmd, void (*callback)()) + { + addManager(cmd, NULL, callback, NULL, NULL); + } + + /** + * Add a write-only Manager + * + * @param cmd - Manager to listen + * @param callback - Write Manager callback + */ + void addWriteManager(char *cmd, void (*callback)()) + { + addManager(cmd, NULL, NULL, callback, NULL); + } + + /** + * Add a execute-only Manager + * + * @param cmd - Manager to listen + * @param callback - Execute Manager callback + */ + void addExecuteManager(char *cmd, void (*callback)()) + { + addManager(cmd, NULL, NULL, NULL, callback); + } + + /** + * Default function to execute when no match is found + * + * @param callback - Function to execute when Manager is received + */ + void addError(void (*callback)()); + + /* Return next argument found in Manager buffer */ + char *next(void); + + /* + * Virtual methods to match Stream class + */ + size_t write(uint8_t); + int available(); + int read(); + int peek(); + void flush(); + +private: + /* Setup serial port */ + void setup(unsigned long baud); + /* Sets the Manager buffer to all '\0' (nulls) */ + void clear(void); + /* Send error message and clear buffer */ + void error(); + /* Process buffer */ + void bufferHandler(char c); + /* Check for Manager instances and handle callbacks and queries */ + bool ManagerHandler(void); + /* User defined error handler */ + void (*userErrorHandler)(); + /* Serial Port handler */ + Stream *_serial; + /* Actual definition for Manager/handler array */ + serialManagerCallback *ManagerList; + /* Buffer of stored characters while waiting for terminator character */ + char buffer[SERIAL_CMD_BUFF_LEN]; + /* Pointer to buffer, used to store data in the buffer */ + char *pBuff; + /* State variable used by strtok_r during processing */ + char *last; + /* Number of available Managers registered by new() */ + uint8_t ManagerCount; +}; +extern SerialManager serialManager; +#endif // SerialManager_h \ No newline at end of file diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 5be5f95..0e4e1f1 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -16,8 +16,8 @@ OTA ota; LEDManager ledManager(33); CameraHandler cameraHandler(&projectConfig); APIServer apiServer(CONTROL_SERVER_PORT, &cameraHandler); -StreamServer streamServer(STREAM_SERVER_PORT); MDNSHandler mdnsHandler(&mdnsStateManager, &projectConfig); +StreamServer streamServer(STREAM_SERVER_PORT); void setup() { @@ -29,6 +29,7 @@ void setup() cameraHandler.setupCamera(); WiFiHandler::setupWifi(&wifiStateManager, &projectConfig); + mdnsHandler.startMDNS(); if (wifiStateManager.getCurrentState() == ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected) { From 67ca634f976b4e6146a28ba0f781a79f81b86a72 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 31 Jul 2022 13:41:48 +0100 Subject: [PATCH 011/153] update - Added basic serial manager functionality --- .../SerialManager2/serialmanager.cpp | 55 +++++++++++++------ .../SerialManager2/serialmanager.hpp | 11 +++- .../src/io/SerialManager/serialmanager.cpp | 10 ++-- ESP/src/main.cpp | 4 ++ 4 files changed, 57 insertions(+), 23 deletions(-) diff --git a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp index 12b62cd..8f93d61 100644 --- a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp @@ -41,7 +41,7 @@ void printHex(Stream &port, uint16_t *data, uint8_t length) // prints 16-bit dat } #endif -SerialManager::SerialManager() : userErrorHandler(NULL), _serial(NULL), ManagerCount(0) +SerialManager::SerialManager() : userErrorHandler(NULL), _serial(NULL), ManagerCount(0), _serialManagerActive(false), newData(false) { clear(); } @@ -55,14 +55,40 @@ void SerialManager::begin(Stream &serialPort) // This checks the Serial stream for characters, and assembles them into a buffer. // When the terminator character (defined by EOL constant) is seen, it starts parsing the // buffer for a prefix Manager, and calls handlers setup by addManager() method -void SerialManager::loop(void) +void SerialManager::loop(unsigned long timeout) { + log_d("Listening to serial"); + _serialManagerActive = true; + Serial.setTimeout(timeout); + static bool recvInProgress = false; + char startDelimiter = '<'; //! we need to decide on a delimiter for the start of a message + char endDelimiter = '>'; //! we need to decide on a delimiter for the end of a message char c; - while (available() > 0) + while ((available() > 0) && !newData) { c = read(); - bufferHandler(c); + if (recvInProgress) + { + if (c != endDelimiter) + { + bufferHandler(c); + } + else + { + recvInProgress = false; + newData = true; + } + } + else + { + if (c == startDelimiter) + { + recvInProgress = true; + } + } } + delay(timeout); + _serialManagerActive = false; } /* Clear buffer */ @@ -120,8 +146,7 @@ void SerialManager::bufferHandler(char c) // *lastChars = '\0'; /* Replace EOL with NULL terminator */ #if (SERIAL_CMD_DBG_EN == 1) - print("Received: "); - println(buffer); + log_d("Received: %s", buffer); #endif if (ManagerHandler()) @@ -160,9 +185,7 @@ bool SerialManager::ManagerHandler(void) { #if SERIAL_CMD_DBG_EN - print("Token: \""); - print(token); - println("\""); + log_d("Token: %s", token); #endif for (i = 0; (i < ManagerCount); i++) @@ -179,7 +202,7 @@ bool SerialManager::ManagerHandler(void) { #if SERIAL_CMD_DBG_EN - println("- Match Found!"); + log_d("- Match Found!"); #endif offset = (char *)(userInput + strlen(token)); @@ -187,7 +210,7 @@ bool SerialManager::ManagerHandler(void) if (0 == strncmp(offset, "=?", 2)) { #if SERIAL_CMD_DBG_EN - println("Run test callback"); + log_d("Run test callback"); #endif if (NULL != *ManagerList[i].test) { @@ -198,7 +221,7 @@ bool SerialManager::ManagerHandler(void) else if (('?' == *offset) && (NULL != *ManagerList[i].read)) { #if SERIAL_CMD_DBG_EN - println("Run read callback"); + log_d("Run read callback"); #endif /* Run read callback */ (*ManagerList[i].read)(); @@ -206,7 +229,7 @@ bool SerialManager::ManagerHandler(void) else if (('=' == *offset) && (NULL != *ManagerList[i].write)) { #if (SERIAL_CMD_DBG_EN == 1) - println("Run write callback"); + log_d("Run write callback"); #endif /* Run write callback */ (*ManagerList[i].write)(); @@ -214,14 +237,14 @@ bool SerialManager::ManagerHandler(void) else if (NULL != *ManagerList[i].execute) { #if SERIAL_CMD_DBG_EN - println("Run execute callback"); + log_d("Run execute callback"); #endif /* Run execute callback */ (*ManagerList[i].execute)(); } else { - println("INVALID"); + log_e("INVALID"); ret = false; break; } @@ -233,7 +256,7 @@ bool SerialManager::ManagerHandler(void) #if SERIAL_CMD_DBG_EN else { - println("- Not a match!"); + log_e("- Not a match!"); } #endif } diff --git a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp index b9a25a4..b04f428 100644 --- a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp +++ b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp @@ -4,7 +4,7 @@ #include #define SERIAL_CMD_DBG_EN 0 -#define SERIAL_CMD_BUFF_LEN 64 /* Max length for each serial Manager */ +#define SERIAL_CMD_BUFF_LEN 100 /* Max length for each serial Manager */ /* Data structure to hold Manager/Handler function key-value pairs */ typedef struct @@ -45,7 +45,7 @@ public: /** * Execute this function inside Arduino's loop function. */ - void loop(void); + void loop(unsigned long timeout); /** * Add a new Manager @@ -112,6 +112,9 @@ public: /* Return next argument found in Manager buffer */ char *next(void); + /* variable to track state of newdata in the buffer */ + bool newData; + /* * Virtual methods to match Stream class */ @@ -121,6 +124,7 @@ public: int peek(); void flush(); + private: /* Setup serial port */ void setup(unsigned long baud); @@ -146,6 +150,9 @@ private: char *last; /* Number of available Managers registered by new() */ uint8_t ManagerCount; + + bool _serialManagerActive; + }; extern SerialManager serialManager; #endif // SerialManager_h \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp index d3e948e..b906abc 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -61,9 +61,9 @@ void SerialManager::listenToSerial(unsigned long timeout) recvInProgress = true; } } - delay(timeout); - serialManagerActive = false; } + delay(timeout); + serialManagerActive = false; } void SerialManager::parseData() @@ -111,12 +111,12 @@ void SerialManager::handleSerial() listenToSerial(30000L); // test for serial input for 30 seconds if (newData) // input received { - strcpy(tempBuffer, serialBuffer); // this temporary copy is necessary to protect the original data because strtok() used in parseData() replaces the commas with \0 - parseData(); // split the data into tokens and store them in the data structure + strcpy(tempBuffer, serialBuffer); // this temporary copy is necessary to protect the original data because strtok() used in parseData() replaces the commas with \0 + 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.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.save(); // save the config to the EEPROM - newData = false; // reset new data + newData = false; // reset new data } } diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 0e4e1f1..faf22de 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -6,6 +6,8 @@ #include #include #include +#include +//#include //! Finish this to update the serial manager #include @@ -37,10 +39,12 @@ void setup() streamServer.startStreamServer(); } ota.SetupOTA(&projectConfig); + } void loop() { ota.HandleOTAUpdate(); ledManager.displayStatus(); + serialManager.handleSerial(); } \ No newline at end of file From 849a4741f587fd402dc2c90a50122eeb080e7b82 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 31 Jul 2022 13:42:33 +0100 Subject: [PATCH 012/153] update - Added serial manager include notations --- ESP/src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index faf22de..706732b 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -6,8 +6,8 @@ #include #include #include -#include -//#include //! Finish this to update the serial manager +#include // Basic Serial Manager +//#include // Advanced Serial MAnager //! Finish this to update the serial manager #include From a414581113a02ff0bf7a900164da686d222b11de Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 31 Jul 2022 13:44:01 +0100 Subject: [PATCH 013/153] update - remove blocking delay --- ESP/lib/src/io/SerialManager/serialmanager.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp index b906abc..ebf39e7 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -62,7 +62,6 @@ void SerialManager::listenToSerial(unsigned long timeout) } } } - delay(timeout); serialManagerActive = false; } From ada9dfd9cfcbe0a830f72e5628b07c4f9f838f46 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 31 Jul 2022 13:51:33 +0100 Subject: [PATCH 014/153] update - remove uneeded enum in serial manager class --- ESP/lib/src/io/SerialManager/serialmanager.cpp | 2 +- ESP/lib/src/io/SerialManager/serialmanager.hpp | 9 --------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp index ebf39e7..9a4a127 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -107,7 +107,7 @@ void SerialManager::parseData() void SerialManager::handleSerial() { - listenToSerial(30000L); // test for serial input for 30 seconds + listenToSerial(30000L); // test for serial input every 30 seconds if (newData) // input received { strcpy(tempBuffer, serialBuffer); // this temporary copy is necessary to protect the original data because strtok() used in parseData() replaces the commas with \0 diff --git a/ESP/lib/src/io/SerialManager/serialmanager.hpp b/ESP/lib/src/io/SerialManager/serialmanager.hpp index 7549183..261aaba 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.hpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.hpp @@ -33,15 +33,6 @@ private: void listenToSerial(unsigned long timeout); void parseData(); - enum DataTypes_e - { - DataType_Unknown, - DataType_Device, - DataType_Camera, - DataType_Wifi, - DataType_Error, - DataType_Debug - }; char serialBuffer[100000]; //! Need to find the appropriate size for this - count the maximum possible size of a message char tempBuffer[sizeof(serialBuffer) / sizeof(serialBuffer[0])]; From 6ad444c866a1dd7f5967c66b70f42b7ef17a105f Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 31 Jul 2022 13:57:05 +0100 Subject: [PATCH 015/153] update - fix some formatting - reduce the size of the serial buffer to 1000 --- ESP/lib/src/io/SerialManager/serialmanager.hpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ESP/lib/src/io/SerialManager/serialmanager.hpp b/ESP/lib/src/io/SerialManager/serialmanager.hpp index 261aaba..0bc96fb 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.hpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.hpp @@ -34,10 +34,9 @@ private: void listenToSerial(unsigned long timeout); void parseData(); - char serialBuffer[100000]; //! Need to find the appropriate size for this - count the maximum possible size of a message + char serialBuffer[1000]; //! Need to find the appropriate size for this - count the maximum possible size of a message char tempBuffer[sizeof(serialBuffer) / sizeof(serialBuffer[0])]; bool newData; - }; extern SerialManager serialManager; \ No newline at end of file From 1bfb67ca4007c06edaffc0c4ef922a628d858d59 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 1 Aug 2022 18:50:04 +0100 Subject: [PATCH 016/153] big update - renamed observers folder to utilities - created a make_unique function in the utilities namespace - migrated the main.cpp object creations to unique pointers --- ESP/lib/src/data/config/project_config.hpp | 2 +- .../Observer.h => utilities/Observer.hpp} | 0 ESP/lib/src/data/utilities/makeunique.hpp | 10 ++++++ ESP/lib/src/io/camera/cameraHandler.hpp | 2 +- ESP/lib/src/network/mDNS/MDNSManager.hpp | 2 +- ESP/src/main.cpp | 36 ++++++++++--------- 6 files changed, 33 insertions(+), 19 deletions(-) rename ESP/lib/src/data/{Observer/Observer.h => utilities/Observer.hpp} (100%) create mode 100644 ESP/lib/src/data/utilities/makeunique.hpp diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 9c09207..d77760f 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -3,7 +3,7 @@ #include #include -#include "data/Observer/Observer.h" +#include "data/utilities/Observer.hpp" class ProjectConfig : public Config, public ISubject { diff --git a/ESP/lib/src/data/Observer/Observer.h b/ESP/lib/src/data/utilities/Observer.hpp similarity index 100% rename from ESP/lib/src/data/Observer/Observer.h rename to ESP/lib/src/data/utilities/Observer.hpp diff --git a/ESP/lib/src/data/utilities/makeunique.hpp b/ESP/lib/src/data/utilities/makeunique.hpp new file mode 100644 index 0000000..58d4891 --- /dev/null +++ b/ESP/lib/src/data/utilities/makeunique.hpp @@ -0,0 +1,10 @@ +#pragma once +#include +namespace Utilities +{ + template + std::unique_ptr make_unique(Args &&...args) + { + return std::unique_ptr(new T(std::forward(args)...)); + } +} \ No newline at end of file diff --git a/ESP/lib/src/io/camera/cameraHandler.hpp b/ESP/lib/src/io/camera/cameraHandler.hpp index 37fbc07..908cdec 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -1,7 +1,7 @@ #pragma once #include #include -#include "data/Observer/Observer.h" +#include "data/utilities/Observer.hpp" #include "data/config/project_config.hpp" class CameraHandler : IObserver diff --git a/ESP/lib/src/network/mDNS/MDNSManager.hpp b/ESP/lib/src/network/mDNS/MDNSManager.hpp index 5fb2d04..40c0d27 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.hpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.hpp @@ -1,7 +1,7 @@ #pragma once #include #include "data/StateManager/StateManager.hpp" -#include "data/Observer/Observer.h" +#include "data/utilities/Observer.hpp" #include "data/config/project_config.hpp" class MDNSHandler : public IObserver diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 706732b..39ddac8 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -11,40 +12,43 @@ #include -int STREAM_SERVER_PORT = 80; -int CONTROL_SERVER_PORT = 81; +uint8_t STREAM_SERVER_PORT = 80; +uint8_t CONTROL_SERVER_PORT = 81; -OTA ota; -LEDManager ledManager(33); -CameraHandler cameraHandler(&projectConfig); -APIServer apiServer(CONTROL_SERVER_PORT, &cameraHandler); -MDNSHandler mdnsHandler(&mdnsStateManager, &projectConfig); -StreamServer streamServer(STREAM_SERVER_PORT); +// Create smart pointers to the various classes that will be used in the program to make sure that they are deleted when the program ends +// This is done to make sure that the memory is freed when the program ends and we are not left with dangling pointers to memory that is no longer in use +// Make unique is a templated function that takes a class and returns a unique pointer to that class - it is used to create a unique pointer to a class and ensure exception safety +std::unique_ptr ota = Utilities::make_unique(); +std::unique_ptr ledManager = Utilities::make_unique(33); +std::unique_ptr cameraHandler = Utilities::make_unique(&projectConfig); +std::unique_ptr apiServer = Utilities::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); +std::unique_ptr mdnsHandler = Utilities::make_unique(&mdnsStateManager, &projectConfig); +std::unique_ptr streamServer = Utilities::make_unique(STREAM_SERVER_PORT); void setup() { Serial.begin(115200); Serial.setDebugOutput(true); - ledManager.begin(); + ledManager->begin(); projectConfig.initStructures(); projectConfig.load(); - cameraHandler.setupCamera(); + cameraHandler->setupCamera(); WiFiHandler::setupWifi(&wifiStateManager, &projectConfig); - mdnsHandler.startMDNS(); + mdnsHandler->startMDNS(); if (wifiStateManager.getCurrentState() == ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected) { - apiServer.startAPIServer(); - streamServer.startStreamServer(); + apiServer->startAPIServer(); + streamServer->startStreamServer(); } - ota.SetupOTA(&projectConfig); + ota->SetupOTA(&projectConfig); } void loop() { - ota.HandleOTAUpdate(); - ledManager.displayStatus(); + ota->HandleOTAUpdate(); + ledManager->displayStatus(); serialManager.handleSerial(); } \ No newline at end of file From 5e1321515a84c4ff298fc1227c69ec36e1f602cb Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 1 Aug 2022 19:07:06 +0100 Subject: [PATCH 017/153] big update::FIX - Fixed serialManager undefiend error - Moved the make_unique function into an override of std namespace - properly implemented the make_unique function --- ESP/lib/src/data/utilities/makeunique.hpp | 52 +++++++++++++++++-- .../SerialManager2/serialmanager.cpp | 38 +++++++------- .../SerialManager2/serialmanager.hpp | 20 +++---- .../src/io/SerialManager/serialmanager.cpp | 2 + ESP/src/main.cpp | 12 ++--- 5 files changed, 86 insertions(+), 38 deletions(-) diff --git a/ESP/lib/src/data/utilities/makeunique.hpp b/ESP/lib/src/data/utilities/makeunique.hpp index 58d4891..9ffca8d 100644 --- a/ESP/lib/src/data/utilities/makeunique.hpp +++ b/ESP/lib/src/data/utilities/makeunique.hpp @@ -1,10 +1,56 @@ #pragma once #include +#include +#include +#include namespace Utilities { - template - std::unique_ptr make_unique(Args &&...args) + +} + +/** + * @brief override the STD namespace to add make_unique function + * + * @tparam T + * @tparam Args + * @return std::unique_ptr + */ +namespace std +{ + template + struct _Unique_if { - return std::unique_ptr(new T(std::forward(args)...)); + typedef unique_ptr _Single_object; + }; + + template + struct _Unique_if + { + typedef unique_ptr _Unknown_bound; + }; + + template + struct _Unique_if + { + typedef void _Known_bound; + }; + + template + typename _Unique_if::_Single_object + make_unique(Args &&...args) + { + return unique_ptr(new T(std::forward(args)...)); } + + template + typename _Unique_if::_Unknown_bound + make_unique(size_t n) + { + typedef typename remove_extent::type U; + return unique_ptr(new U[n]()); + } + + template + typename _Unique_if::_Known_bound + make_unique(Args &&...) = delete; } \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp index 8f93d61..f47fb80 100644 --- a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp @@ -41,12 +41,12 @@ void printHex(Stream &port, uint16_t *data, uint8_t length) // prints 16-bit dat } #endif -SerialManager::SerialManager() : userErrorHandler(NULL), _serial(NULL), ManagerCount(0), _serialManagerActive(false), newData(false) +SerialManager2::SerialManager2() : userErrorHandler(NULL), _serial(NULL), ManagerCount(0), _serialManager2Active(false), newData(false) { clear(); } -void SerialManager::begin(Stream &serialPort) +void SerialManager2::begin(Stream &serialPort) { /* Save Serial Port configurations */ _serial = &serialPort; @@ -55,10 +55,10 @@ void SerialManager::begin(Stream &serialPort) // This checks the Serial stream for characters, and assembles them into a buffer. // When the terminator character (defined by EOL constant) is seen, it starts parsing the // buffer for a prefix Manager, and calls handlers setup by addManager() method -void SerialManager::loop(unsigned long timeout) +void SerialManager2::loop(unsigned long timeout) { log_d("Listening to serial"); - _serialManagerActive = true; + _serialManager2Active = true; Serial.setTimeout(timeout); static bool recvInProgress = false; char startDelimiter = '<'; //! we need to decide on a delimiter for the start of a message @@ -88,11 +88,11 @@ void SerialManager::loop(unsigned long timeout) } } delay(timeout); - _serialManagerActive = false; + _serialManager2Active = false; } /* Clear buffer */ -void SerialManager::clear(void) +void SerialManager2::clear(void) { memset(buffer, 0, SERIAL_CMD_BUFF_LEN); pBuff = buffer; @@ -103,7 +103,7 @@ void SerialManager::clear(void) * NOTE: Will execute user defined callback (defined using addDefault method), * if no user defined callback it will send the ERROR message (sendERROR method). */ -void SerialManager::error(void) +void SerialManager2::error(void) { if (NULL != userErrorHandler) { @@ -115,12 +115,12 @@ void SerialManager::error(void) // Retrieve the next token ("word" or "argument") from the Manager buffer. // returns a NULL if no more tokens exist. -char *SerialManager::next(void) +char *SerialManager2::next(void) { return strtok_r(NULL, delimiters, &last); } -void SerialManager::bufferHandler(char c) +void SerialManager2::bufferHandler(char c) { int len; char *lastChars = NULL; @@ -162,7 +162,7 @@ void SerialManager::bufferHandler(char c) } /* Return true if match was found */ -bool SerialManager::ManagerHandler(void) +bool SerialManager2::ManagerHandler(void) { int i; bool ret = false; @@ -268,7 +268,7 @@ bool SerialManager::ManagerHandler(void) // Adds a "Manager" and a handler function to the list of available Managers. // This is used for matching a found token in the buffer, and gives the pointer // to the handler function to deal with it. -void SerialManager::addManager(char *cmd, void (*test)(), void (*read)(), void (*write)(), void (*execute)()) +void SerialManager2::addManager(char *cmd, void (*test)(), void (*read)(), void (*write)(), void (*execute)()) { #if SERIAL_CMD_DBG_EN @@ -278,7 +278,7 @@ void SerialManager::addManager(char *cmd, void (*test)(), void (*read)(), void ( println(cmd); #endif - ManagerList = (serialManagerCallback *)realloc(ManagerList, (ManagerCount + 1) * sizeof(serialManagerCallback)); + ManagerList = (serialManager2Callback *)realloc(ManagerList, (ManagerCount + 1) * sizeof(serialManager2Callback)); strncpy(ManagerList[ManagerCount].Manager, cmd, SERIAL_CMD_BUFF_LEN); ManagerList[ManagerCount].test = test; ManagerList[ManagerCount].read = read; @@ -288,12 +288,12 @@ void SerialManager::addManager(char *cmd, void (*test)(), void (*read)(), void ( } /* Optional user-defined function to call when an error occurs, default is NULL */ -void SerialManager::addError(void (*callback)()) +void SerialManager2::addError(void (*callback)()) { userErrorHandler = callback; } -int SerialManager::available() +int SerialManager2::available() { int bytes = 0; if (NULL != _serial) @@ -303,7 +303,7 @@ int SerialManager::available() return bytes; } -int SerialManager::read() +int SerialManager2::read() { int bytes = 0; if (NULL != _serial) @@ -313,7 +313,7 @@ int SerialManager::read() return bytes; } -int SerialManager::peek() +int SerialManager2::peek() { int bytes = 0; if (NULL != _serial) @@ -323,7 +323,7 @@ int SerialManager::peek() return bytes; } -void SerialManager::flush() +void SerialManager2::flush() { if (NULL != _serial) { @@ -331,10 +331,10 @@ void SerialManager::flush() } } -size_t SerialManager::write(uint8_t x) +size_t SerialManager2::write(uint8_t x) { (void)x; return 0; } -SerialManager serialManager; \ No newline at end of file +SerialManager2 serialManager2; \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp index b04f428..1ca6b76 100644 --- a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp +++ b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp @@ -1,5 +1,5 @@ -#ifndef SERIALMANAGER_HPP -#define SERIALMANAGER_HPP +#ifndef SERIALMANAGER2_HPP +#define SERIALMANAGER2_HPP #include #include @@ -14,7 +14,7 @@ typedef struct void (*read)(); void (*write)(); void (*execute)(); -} serialManagerCallback; +} serialManager2Callback; /* * Token delimiters (setup '=', query '?', separator ',') @@ -28,11 +28,11 @@ const char delimiters[] = "=,?\r\n"; */ const char EOL[] = "\r\n"; -class SerialManager : public Stream +class SerialManager2 : public Stream { public: - SerialManager(); - virtual ~SerialManager(); + SerialManager2(); + virtual ~SerialManager2(); /** * Start connection to serial port @@ -141,7 +141,7 @@ private: /* Serial Port handler */ Stream *_serial; /* Actual definition for Manager/handler array */ - serialManagerCallback *ManagerList; + serialManager2Callback *ManagerList; /* Buffer of stored characters while waiting for terminator character */ char buffer[SERIAL_CMD_BUFF_LEN]; /* Pointer to buffer, used to store data in the buffer */ @@ -151,8 +151,8 @@ private: /* Number of available Managers registered by new() */ uint8_t ManagerCount; - bool _serialManagerActive; + bool _serialManager2Active; }; -extern SerialManager serialManager; -#endif // SerialManager_h \ No newline at end of file +extern SerialManager2 serialManager2; +#endif // SerialManager2_h \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp index 9a4a127..ffe2174 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -119,3 +119,5 @@ void SerialManager::handleSerial() newData = false; // reset new data } } + +SerialManager serialManager; \ No newline at end of file diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 39ddac8..323c745 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -18,12 +18,12 @@ uint8_t CONTROL_SERVER_PORT = 81; // Create smart pointers to the various classes that will be used in the program to make sure that they are deleted when the program ends // This is done to make sure that the memory is freed when the program ends and we are not left with dangling pointers to memory that is no longer in use // Make unique is a templated function that takes a class and returns a unique pointer to that class - it is used to create a unique pointer to a class and ensure exception safety -std::unique_ptr ota = Utilities::make_unique(); -std::unique_ptr ledManager = Utilities::make_unique(33); -std::unique_ptr cameraHandler = Utilities::make_unique(&projectConfig); -std::unique_ptr apiServer = Utilities::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); -std::unique_ptr mdnsHandler = Utilities::make_unique(&mdnsStateManager, &projectConfig); -std::unique_ptr streamServer = Utilities::make_unique(STREAM_SERVER_PORT); +std::unique_ptr ota = std::make_unique(); +std::unique_ptr ledManager = std::make_unique(33); +std::unique_ptr cameraHandler = std::make_unique(&projectConfig); +std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); +std::unique_ptr mdnsHandler = std::make_unique(&mdnsStateManager, &projectConfig); +std::unique_ptr streamServer = std::make_unique(STREAM_SERVER_PORT); void setup() { From c29d502aeb3da342dd1ab539ea0c78b0ab76cff8 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 1 Aug 2022 19:09:50 +0100 Subject: [PATCH 018/153] add comment about dereferencing the cameraHandler --- ESP/src/main.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 323c745..94f58b0 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -17,11 +17,12 @@ uint8_t CONTROL_SERVER_PORT = 81; // Create smart pointers to the various classes that will be used in the program to make sure that they are deleted when the program ends // This is done to make sure that the memory is freed when the program ends and we are not left with dangling pointers to memory that is no longer in use -// Make unique is a templated function that takes a class and returns a unique pointer to that class - it is used to create a unique pointer to a class and ensure exception safety +// Make unique is a templated function that takes a class and returns a unique pointer to that class - +//it is used to create a unique pointer to a class and ensure exception safety std::unique_ptr ota = std::make_unique(); std::unique_ptr ledManager = std::make_unique(33); std::unique_ptr cameraHandler = std::make_unique(&projectConfig); -std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); +std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); // dereference the pointer to get the address of the cameraHandler object std::unique_ptr mdnsHandler = std::make_unique(&mdnsStateManager, &projectConfig); std::unique_ptr streamServer = std::make_unique(STREAM_SERVER_PORT); From 44bd70fc2371cb20c8dc94d30f3c04b327854e28 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 1 Aug 2022 19:20:05 +0100 Subject: [PATCH 019/153] update - Change the camera handler to a shared pointer --- ESP/src/main.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 94f58b0..80dc873 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -17,12 +17,12 @@ uint8_t CONTROL_SERVER_PORT = 81; // Create smart pointers to the various classes that will be used in the program to make sure that they are deleted when the program ends // This is done to make sure that the memory is freed when the program ends and we are not left with dangling pointers to memory that is no longer in use -// Make unique is a templated function that takes a class and returns a unique pointer to that class - -//it is used to create a unique pointer to a class and ensure exception safety +// Make unique is a templated function that takes a class and returns a unique pointer to that class - +// it is used to create a unique pointer to a class and ensure exception safety std::unique_ptr ota = std::make_unique(); std::unique_ptr ledManager = std::make_unique(33); -std::unique_ptr cameraHandler = std::make_unique(&projectConfig); -std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); // dereference the pointer to get the address of the cameraHandler object +std::shared_ptr cameraHandler = std::make_shared(&projectConfig); //! Create a shared pointer to the camera handler +std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); //! Dereference the shared pointer to get the address of the camera handler std::unique_ptr mdnsHandler = std::make_unique(&mdnsStateManager, &projectConfig); std::unique_ptr streamServer = std::make_unique(STREAM_SERVER_PORT); @@ -44,12 +44,11 @@ void setup() streamServer->startStreamServer(); } ota->SetupOTA(&projectConfig); - } void loop() { ota->HandleOTAUpdate(); ledManager->displayStatus(); - serialManager.handleSerial(); + serialManager.handleSerial(); } \ No newline at end of file From 32b077472f7a708c913f3c73c7f3220218e08f01 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 11 Aug 2022 17:12:38 +0100 Subject: [PATCH 020/153] experimental update - Started to migrate the project to smart pointer - Added ADHOC support --- .../src/data/StateManager/StateManager.hpp | 1 + ESP/lib/src/network/OTA/OTA.cpp | 73 +++++++++++++++++++ ESP/lib/src/network/OTA/OTA.hpp | 61 ++++------------ .../src/network/WifiHandler/WifiHandler.hpp | 24 +++++- .../src/network/WifiHandler/wifiHandler.cpp | 62 +++++++++++++++- ESP/platformio.ini | 9 ++- ESP/src/main.cpp | 13 ++-- 7 files changed, 183 insertions(+), 60 deletions(-) create mode 100644 ESP/lib/src/network/OTA/OTA.cpp diff --git a/ESP/lib/src/data/StateManager/StateManager.hpp b/ESP/lib/src/data/StateManager/StateManager.hpp index 9fc7e6b..5fef403 100644 --- a/ESP/lib/src/data/StateManager/StateManager.hpp +++ b/ESP/lib/src/data/StateManager/StateManager.hpp @@ -28,6 +28,7 @@ public: WiFiState_Connected, WiFiState_Disconnected, WiFiState_Disconnecting, + WiFiState_ADHOC, WiFiState_Error }; diff --git a/ESP/lib/src/network/OTA/OTA.cpp b/ESP/lib/src/network/OTA/OTA.cpp new file mode 100644 index 0000000..2fcde6f --- /dev/null +++ b/ESP/lib/src/network/OTA/OTA.cpp @@ -0,0 +1,73 @@ +#include "OTA.hpp" + +OTA::OTA(ProjectConfig *_deviceConfig) : _deviceConfig(_deviceConfig) {} + +OTA::~OTA() {} + +void OTA::SetupOTA() +{ + log_e("Setting up OTA updates"); + auto localConfig = _deviceConfig->getDeviceConfig(); + + if (strcmp(localConfig->OTAPassword, "") == 0) + { + log_e("THE PASSWORD IS REQUIRED, [[ABORTING]]"); + return; + } + + ArduinoOTA.setPort(localConfig->OTAPort); + + ArduinoOTA + .onStart([]() + { + String type; + if (ArduinoOTA.getCommand() == U_FLASH) + type = "sketch"; + else // U_SPIFFS + type = "filesystem"; }) + .onEnd([]() + { Serial.println("OTA updated finished successfully!"); }) + .onProgress([](unsigned int progress, unsigned int total) + { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }) + .onError([](ota_error_t error) + { + log_e("Error[%u]: ", error); + switch (error) + { + case OTA_AUTH_ERROR: + log_e("Auth Failed"); + break; + case OTA_BEGIN_ERROR: + log_e("Begin Failed"); + break; + case OTA_CONNECT_ERROR: + log_e("Connect Failed"); + break; + case OTA_RECEIVE_ERROR: + log_e("Receive Failed"); + break; + case OTA_END_ERROR: + log_e("End Failed"); + break; + } }); + + log_i("Starting up basic OTA server"); + log_i("OTA will be live for 30s, after which it will be disabled until restart"); + ArduinoOTA.begin(); + _bootTimestamp = millis(); +} + +void OTA::HandleOTAUpdate() +{ + if (_isOtaEnabled) + { + if (_bootTimestamp + 30000 < millis()) + { + // we're disabling ota after first 30sec so that nothing bad happens during runtime + _isOtaEnabled = false; + log_i("From now on, OTA is disabled"); + return; + } + ArduinoOTA.handle(); + } +} \ No newline at end of file diff --git a/ESP/lib/src/network/OTA/OTA.hpp b/ESP/lib/src/network/OTA/OTA.hpp index 7e22983..f4cdbbe 100644 --- a/ESP/lib/src/network/OTA/OTA.hpp +++ b/ESP/lib/src/network/OTA/OTA.hpp @@ -1,55 +1,22 @@ -#pragma once +#ifndef OTA_HPP +#define OTA_HPP #include -#include "data/config/project_config.hpp" +#include +#include "data/Config/project_config.hpp" + class OTA { -private: - bool isOTAEnabled = false; - public: - void SetupOTA(ProjectConfig *configManager) - { - log_i("Setting up OTA updates"); - ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig(); + OTA(ProjectConfig *_deviceConfig); + virtual ~OTA(); - if (deviceConfig->OTAPassword == nullptr) - { - log_e("THE PASSWORD IS REQUIRED, [[ABORTING]]"); - return; - } - ArduinoOTA.setPort(deviceConfig->OTAPort); - isOTAEnabled = true; + void SetupOTA(); - ArduinoOTA - .onStart([]() - { - String type; - if (ArduinoOTA.getCommand() == U_FLASH) - type = "sketch"; - else // U_SPIFFS - type = "filesystem"; }) - .onEnd([]() - { log_i("OTA updated finished successfully!"); }) - .onProgress([](unsigned int progress, unsigned int total) - { log_i("Progress: %u%%\r", (progress / (total / 100))); }) - .onError([](ota_error_t error) - { - log_e("Error[%u]: ", error); - if (error == OTA_AUTH_ERROR) log_e("Auth Failed"); - else if (error == OTA_BEGIN_ERROR) log_e("Begin Failed"); - else if (error == OTA_CONNECT_ERROR) log_e("Connect Failed"); - else if (error == OTA_RECEIVE_ERROR) log_e("Receive Failed"); - else if (error == OTA_END_ERROR) log_e("End Failed"); }); - log_i("Starting up basic OTA server"); - log_i("OTA will be live for 30s, after which it will be disabled until restart"); - ArduinoOTA.begin(); - } + void HandleOTAUpdate(); - void HandleOTAUpdate() - { - if (isOTAEnabled) - { - ArduinoOTA.handle(); - } - } +private: + unsigned long _bootTimestamp = 0; + bool _isOtaEnabled = true; + ProjectConfig *_deviceConfig; }; +#endif // OTA_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 7ad6b0e..71d9926 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -1,9 +1,29 @@ #pragma once +#ifndef WIFIHANDLER_HPP +#define WIFIHANDLER_HPP +#include #include #include "data/StateManager/StateManager.hpp" #include "data/config/project_config.hpp" -namespace WiFiHandler +extern "C" { - void setupWifi(StateManager *stateManager, ProjectConfig *configManager); +#include +#include +#include } + +class WiFiHandler +{ +public: + WiFiHandler(); + virtual ~WiFiHandler(); + void setupWifi(); + void setUpADHOC(); + void setWiFiConf(const char *value, uint8_t *location); + std::unique_ptr conf; + std::shared_ptr> wifiStateManager; + std::shared_ptr configManager; +}; +extern WiFiHandler wifiHandler; +#endif // WIFIHANDLER_HPP diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 5da4eb2..192d7c1 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -1,10 +1,21 @@ #include "WifiHandler.hpp" #include -void WiFiHandler::setupWifi(StateManager *stateManager, ProjectConfig *configManager) +WiFiHandler::WiFiHandler() : conf(new wifi_config_t), + wifiStateManager{std::make_shared>()}, + configManager{std::make_shared()} {} + +WiFiHandler::~WiFiHandler() {} + +void WiFiHandler::setupWifi() { + if (ENABLE_ADHOC) + { + this->setUpADHOC(); + return; + } log_i("Initializing connection to wifi"); - stateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting)); + wifiStateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting)); std::vector *networks = configManager->getWifiConfigs(); int connection_timeout = 3000; @@ -30,12 +41,55 @@ void WiFiHandler::setupWifi(StateManagerssid); - stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected); + wifiStateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected); return; } } // 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(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error); + wifiStateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error); } + +void WiFiHandler::setUpADHOC() +{ + log_i("[INFO]: Setting Access Point...\n"); + + log_i("[INFO]: Configuring access point...\n"); + WiFi.mode(WIFI_AP); + + // You can remove the password parameter if you want the AP to be open. + log_i("Wifi Connection Failed. \r\nStarting AP. \r\nAP IP address: "); + IPAddress IP = WiFi.softAPIP(); + log_i("[INFO]: AP IP address: %s.\r\n", IP.toString().c_str()); + + WiFi.softAP(WIFI_SSID, WIFI_PASSWORD, ADHOC_CHANNEL, 0, 3); // AP mode with password + + WiFi.setTxPower(WIFI_POWER_11dBm); + wifiStateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC)); +} + +// we can't assign wifiManager.resetSettings(); to reset, somehow it gets called straight away. +/** + * @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) +{ +#if defined(ESP32) + if (WiFiGenericClass::getMode() != WIFI_MODE_NULL) + { + esp_wifi_get_config(WIFI_IF_STA, &*conf); + + memset(location, 0, sizeof(location)); + 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); + } +#endif +} + +WiFiHandler wifiHandler; \ No newline at end of file diff --git a/ESP/platformio.ini b/ESP/platformio.ini index d762dcf..234b2f8 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -18,6 +18,8 @@ ssid="your_ssid_goes_here" ; your wifi network name goes here password="your_password_goes_here" ; Place your Wifi password here OTAPassword="" ; if empty, no password will be required OTAServerPort=3232 +enableADHOC=0 ; 0 = disable, 1 = enable +adhocChannel=10 ; channel to use for adhoc network ; DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING [pinouts] @@ -47,9 +49,14 @@ monitor_speed = 115200 monitor_rts = 0 monitor_dtr = 0 build_flags = - '-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 -DOTA_SERVER_PORT=${wifi.OTAServerPort} ; Set the OTA server + + -DENABLE_ADHOC=${wifi.enableADHOC} ; + + -DADHOC_CHANNEL=${wifi.adhocChannel} ; + + '-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 '-DOTA_PASSWORD=${wifi.OTAPassword}' ; Set the OTA password diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 80dc873..185ea22 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -19,11 +19,12 @@ uint8_t CONTROL_SERVER_PORT = 81; // This is done to make sure that the memory is freed when the program ends and we are not left with dangling pointers to memory that is no longer in use // Make unique is a templated function that takes a class and returns a unique pointer to that class - // it is used to create a unique pointer to a class and ensure exception safety -std::unique_ptr ota = std::make_unique(); +std::unique_ptr deviceConfig = std::make_unique(); +OTA ota(&*deviceConfig); std::unique_ptr ledManager = std::make_unique(33); -std::shared_ptr cameraHandler = std::make_shared(&projectConfig); //! Create a shared pointer to the camera handler +std::shared_ptr cameraHandler = std::make_shared(&*deviceConfig); //! Create a shared pointer to the camera handler std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); //! Dereference the shared pointer to get the address of the camera handler -std::unique_ptr mdnsHandler = std::make_unique(&mdnsStateManager, &projectConfig); +std::unique_ptr mdnsHandler = std::make_unique(&mdnsStateManager, &*deviceConfig); std::unique_ptr streamServer = std::make_unique(STREAM_SERVER_PORT); void setup() @@ -35,7 +36,7 @@ void setup() projectConfig.load(); cameraHandler->setupCamera(); - WiFiHandler::setupWifi(&wifiStateManager, &projectConfig); + wifiHandler.setupWifi(); mdnsHandler->startMDNS(); if (wifiStateManager.getCurrentState() == ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected) @@ -43,12 +44,12 @@ void setup() apiServer->startAPIServer(); streamServer->startStreamServer(); } - ota->SetupOTA(&projectConfig); + ota.SetupOTA(); } void loop() { - ota->HandleOTAUpdate(); + ota.HandleOTAUpdate(); ledManager->displayStatus(); serialManager.handleSerial(); } \ No newline at end of file From 746b6ff13380ac51390adb6ac01013d1f068e291 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 11 Aug 2022 17:37:15 +0100 Subject: [PATCH 021/153] experimental update - Started to migrate the project to smart pointer - Added ADHOC support --- ESP/lib/src/data/config/project_config.cpp | 7 +++++-- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 4 ++-- ESP/src/main.cpp | 4 ++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index d487189..beb8219 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -1,6 +1,9 @@ #include "project_config.hpp" -ProjectConfig::ProjectConfig() : Config("config", "nvs"), _already_loaded(false) {} +ProjectConfig::ProjectConfig() : Config("config", NULL), _already_loaded(false) +{ + Config::begin(); +} ProjectConfig::~ProjectConfig() {} @@ -42,7 +45,7 @@ void ProjectConfig::load() bool device_success = this->read("device", this->config.device); bool camera_success = this->read("camera", this->config.camera); bool network_info_success = this->read("network_info", this->config.networks); - + if (!device_success || !camera_success || !network_info_success) { log_e("Failed to load project config"); diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 192d7c1..e4d67d4 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -59,9 +59,9 @@ void WiFiHandler::setUpADHOC() WiFi.mode(WIFI_AP); // You can remove the password parameter if you want the AP to be open. - log_i("Wifi Connection Failed. \r\nStarting AP. \r\nAP IP address: "); + Serial.printf("\r\nStarting AP. \r\nAP IP address: "); IPAddress IP = WiFi.softAPIP(); - log_i("[INFO]: AP IP address: %s.\r\n", IP.toString().c_str()); + Serial.printf("[INFO]: AP IP address: %s.\r\n", IP.toString().c_str()); WiFi.softAP(WIFI_SSID, WIFI_PASSWORD, ADHOC_CHANNEL, 0, 3); // AP mode with password diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 185ea22..32ed596 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -32,8 +32,8 @@ void setup() Serial.begin(115200); Serial.setDebugOutput(true); ledManager->begin(); - projectConfig.initStructures(); - projectConfig.load(); + deviceConfig->initStructures(); + deviceConfig->load(); cameraHandler->setupCamera(); wifiHandler.setupWifi(); From ed5bf79ffd131dd8f7d8e1d545e0d5fad0b8bd6c Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 11 Aug 2022 18:39:02 +0100 Subject: [PATCH 022/153] update - fixed ADHOC stream server not starting --- ESP/src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 32ed596..46b2aac 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -39,7 +39,7 @@ void setup() wifiHandler.setupWifi(); mdnsHandler->startMDNS(); - if (wifiStateManager.getCurrentState() == ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected) + if (wifiStateManager.getCurrentState() == ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected || wifiStateManager.getCurrentState() == ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC) { apiServer->startAPIServer(); streamServer->startStreamServer(); From ac8a38d6b48e625895519339f1c5f01a49554de7 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 11 Aug 2022 19:22:31 +0100 Subject: [PATCH 023/153] update - fixed ADHOC stream server not starting --- ESP/lib/src/data/config/project_config.cpp | 4 ++-- ESP/src/main.cpp | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index beb8219..ed08abe 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -1,8 +1,8 @@ #include "project_config.hpp" -ProjectConfig::ProjectConfig() : Config("config", NULL), _already_loaded(false) +ProjectConfig::ProjectConfig() : Config("config"), _already_loaded(false) { - Config::begin(); + begin(); } ProjectConfig::~ProjectConfig() {} diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 46b2aac..f271715 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -39,11 +39,28 @@ void setup() wifiHandler.setupWifi(); mdnsHandler->startMDNS(); - if (wifiStateManager.getCurrentState() == ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected || wifiStateManager.getCurrentState() == ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC) + switch (wifiStateManager.getCurrentState()) { + case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Disconnected: + break; + case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Disconnecting: + break; + case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected: apiServer->startAPIServer(); streamServer->startStreamServer(); + log_d("[SETUP]: Starting Stream Server"); + break; + case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting: + break; + case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error: + break; + case ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC: + apiServer->startAPIServer(); + streamServer->startStreamServer(); + log_d("[SETUP]: Starting Stream Server"); + break; } + ota.SetupOTA(); } From 35d47f1d736c2d733c4078ad164c6a529d4f9253 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 11 Aug 2022 19:29:51 +0100 Subject: [PATCH 024/153] added fallthrough case logic for switch --- ESP/src/main.cpp | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index f271715..4c6ac11 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -22,7 +22,7 @@ uint8_t CONTROL_SERVER_PORT = 81; std::unique_ptr deviceConfig = std::make_unique(); OTA ota(&*deviceConfig); std::unique_ptr ledManager = std::make_unique(33); -std::shared_ptr cameraHandler = std::make_shared(&*deviceConfig); //! Create a shared pointer to the camera handler +std::shared_ptr cameraHandler = std::make_shared(&*deviceConfig); //! Create a shared pointer to the camera handler std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); //! Dereference the shared pointer to get the address of the camera handler std::unique_ptr mdnsHandler = std::make_unique(&mdnsStateManager, &*deviceConfig); std::unique_ptr streamServer = std::make_unique(STREAM_SERVER_PORT); @@ -42,25 +42,32 @@ void setup() switch (wifiStateManager.getCurrentState()) { case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Disconnected: + { break; + } case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Disconnecting: + { break; - case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected: - apiServer->startAPIServer(); - streamServer->startStreamServer(); - log_d("[SETUP]: Starting Stream Server"); - break; - case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting: - break; - case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error: - break; + } case ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC: + { + } + case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected: + { apiServer->startAPIServer(); streamServer->startStreamServer(); log_d("[SETUP]: Starting Stream Server"); break; } - + case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting: + { + break; + } + case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error: + { + break; + } + } ota.SetupOTA(); } From a775e849b4648bc8b0595e09040b74f05ce70839 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 11 Aug 2022 19:37:37 +0100 Subject: [PATCH 025/153] remove copy constructor error --- .../src/network/WifiHandler/WifiHandler.hpp | 9 +++++---- .../src/network/WifiHandler/wifiHandler.cpp | 18 ++++++++---------- ESP/src/main.cpp | 3 ++- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 71d9926..24d2fd0 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -16,14 +16,15 @@ extern "C" class WiFiHandler { public: - WiFiHandler(); + WiFiHandler(ProjectConfig *configManager, StateManager *stateManager); virtual ~WiFiHandler(); void setupWifi(); void setUpADHOC(); void setWiFiConf(const char *value, uint8_t *location); std::unique_ptr conf; - std::shared_ptr> wifiStateManager; - std::shared_ptr configManager; + +private: + ProjectConfig *configManager; + StateManager *stateManager; }; -extern WiFiHandler wifiHandler; #endif // WIFIHANDLER_HPP diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index e4d67d4..c8e6aa8 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -1,9 +1,9 @@ #include "WifiHandler.hpp" #include -WiFiHandler::WiFiHandler() : conf(new wifi_config_t), - wifiStateManager{std::make_shared>()}, - configManager{std::make_shared()} {} +WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager) : conf(new wifi_config_t), + configManager(configManager), + stateManager(stateManager) {} WiFiHandler::~WiFiHandler() {} @@ -15,7 +15,7 @@ void WiFiHandler::setupWifi() return; } log_i("Initializing connection to wifi"); - wifiStateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting)); + stateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting)); std::vector *networks = configManager->getWifiConfigs(); int connection_timeout = 3000; @@ -41,14 +41,14 @@ void WiFiHandler::setupWifi() else { log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid); - wifiStateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected); + stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected); return; } } // 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"); - wifiStateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error); + stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error); } void WiFiHandler::setUpADHOC() @@ -66,7 +66,7 @@ void WiFiHandler::setUpADHOC() WiFi.softAP(WIFI_SSID, WIFI_PASSWORD, ADHOC_CHANNEL, 0, 3); // AP mode with password WiFi.setTxPower(WIFI_POWER_11dBm); - wifiStateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC)); + stateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC)); } // we can't assign wifiManager.resetSettings(); to reset, somehow it gets called straight away. @@ -90,6 +90,4 @@ void WiFiHandler::setWiFiConf(const char *value, uint8_t *location) esp_wifi_set_config(WIFI_IF_STA, &*conf); } #endif -} - -WiFiHandler wifiHandler; \ No newline at end of file +} \ No newline at end of file diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 4c6ac11..bb3cbfb 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -21,6 +21,7 @@ uint8_t CONTROL_SERVER_PORT = 81; // it is used to create a unique pointer to a class and ensure exception safety std::unique_ptr deviceConfig = std::make_unique(); OTA ota(&*deviceConfig); +std::unique_ptr wifiHandler = std::make_unique(&*deviceConfig, &stateManager); std::unique_ptr ledManager = std::make_unique(33); std::shared_ptr cameraHandler = std::make_shared(&*deviceConfig); //! Create a shared pointer to the camera handler std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); //! Dereference the shared pointer to get the address of the camera handler @@ -36,7 +37,7 @@ void setup() deviceConfig->load(); cameraHandler->setupCamera(); - wifiHandler.setupWifi(); + wifiHandler->setupWifi(); mdnsHandler->startMDNS(); switch (wifiStateManager.getCurrentState()) From b2e43c80e9fba6bc781085d5b51b8b4ce28b5146 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 11 Aug 2022 19:43:07 +0100 Subject: [PATCH 026/153] remove copy constructor error --- ESP/src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index bb3cbfb..fdd37c2 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -21,7 +21,7 @@ uint8_t CONTROL_SERVER_PORT = 81; // it is used to create a unique pointer to a class and ensure exception safety std::unique_ptr deviceConfig = std::make_unique(); OTA ota(&*deviceConfig); -std::unique_ptr wifiHandler = std::make_unique(&*deviceConfig, &stateManager); +std::unique_ptr wifiHandler = std::make_unique(&*deviceConfig, &wifiStateManager); std::unique_ptr ledManager = std::make_unique(33); std::shared_ptr cameraHandler = std::make_shared(&*deviceConfig); //! Create a shared pointer to the camera handler std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); //! Dereference the shared pointer to get the address of the camera handler From f685a464e56fb654d983eeb9b59641d3246eb533 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 11 Aug 2022 20:55:25 +0100 Subject: [PATCH 027/153] update - Attempt to fix NVS_OPEN error --- ESP/lib/src/data/config/project_config.cpp | 14 +++---- ESP/lib/src/data/config/project_config.hpp | 6 ++- .../src/io/SerialManager/serialmanager.cpp | 41 +++++++++---------- .../src/io/SerialManager/serialmanager.hpp | 7 +++- .../src/network/WifiHandler/wifiHandler.cpp | 4 +- ESP/src/main.cpp | 5 ++- 6 files changed, 40 insertions(+), 37 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index ed08abe..8a2d368 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -1,9 +1,8 @@ #include "project_config.hpp" -ProjectConfig::ProjectConfig() : Config("config"), _already_loaded(false) -{ - begin(); -} +Preferences preferences; + +ProjectConfig::ProjectConfig() : Config(&preferences ,"config"), _already_loaded(false) {} ProjectConfig::~ProjectConfig() {} @@ -11,8 +10,9 @@ ProjectConfig::~ProjectConfig() {} *@brief Initializes the structures with blank data to prevent empty memory sectors and nullptr errors. *@brief This is to be called in setup() before loading the config. */ -void ProjectConfig::initStructures() +void ProjectConfig::initConfig() { + begin(); this->config.device = { "", "", @@ -128,6 +128,4 @@ void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, con this->notify(ObserverEvent::networksConfigUpdated); } log_d("Updating wifi config"); -} - -ProjectConfig projectConfig; \ No newline at end of file +} \ No newline at end of file diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index d77760f..4471d3f 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -1,4 +1,6 @@ #pragma once +#ifndef PROJECT_CONFIG_HPP +#define PROJECT_CONFIG_HPP #include #include #include @@ -13,7 +15,7 @@ public: void load(); void save(); void reset(); - void initStructures(); + void initConfig(); struct DeviceConfig_t { @@ -58,4 +60,4 @@ private: bool _already_loaded; }; -extern ProjectConfig projectConfig; \ No newline at end of file +#endif // PROJECT_CONFIG_HPP \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp index ffe2174..54db530 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -1,19 +1,20 @@ #include "serialmanager.hpp" -SerialManager::SerialManager() : serialManagerActive(false), - newData(false), - tempBuffer{0}, - serialBuffer{0}, - device_config_name{0}, - device_config_OTAPassword{0}, - device_config_OTAPort(0), - camera_config_vflip{0}, - camera_config_href{0}, - camera_config_framesize{0}, - camera_config_quality{0}, - wifi_config_name{0}, - wifi_config_ssid{0}, - wifi_config_password{0} {} +SerialManager::SerialManager(ProjectConfig *projectConfig) : projectConfig(projectConfig), + serialManagerActive(false), + newData(false), + tempBuffer{0}, + serialBuffer{0}, + device_config_name{0}, + device_config_OTAPassword{0}, + device_config_OTAPort(0), + camera_config_vflip{0}, + camera_config_href{0}, + camera_config_framesize{0}, + camera_config_quality{0}, + wifi_config_name{0}, + wifi_config_ssid{0}, + wifi_config_password{0} {} SerialManager::~SerialManager() {} @@ -112,12 +113,10 @@ void SerialManager::handleSerial() { strcpy(tempBuffer, serialBuffer); // this temporary copy is necessary to protect the original data because strtok() used in parseData() replaces the commas with \0 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.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.save(); // save the config to the EEPROM + 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->setWifiConfig(wifi_config_name, wifi_config_ssid, wifi_config_password, true); // set the values in the project config + projectConfig->save(); // save the config to the EEPROM newData = false; // reset new data } -} - -SerialManager serialManager; \ No newline at end of file +} \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/serialmanager.hpp b/ESP/lib/src/io/SerialManager/serialmanager.hpp index 0bc96fb..3ab5659 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.hpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.hpp @@ -1,4 +1,6 @@ #pragma once +#ifndef SERIAL_MANAGER_HPP +#define SERIAL_MANAGER_HPP #include #include "data/config/project_config.hpp" @@ -6,7 +8,7 @@ class SerialManager { public: - SerialManager(); + SerialManager(ProjectConfig *projectConfig); virtual ~SerialManager(); void handleSerial(); @@ -37,6 +39,7 @@ private: char serialBuffer[1000]; //! Need to find the appropriate size for this - count the maximum possible size of a message char tempBuffer[sizeof(serialBuffer) / sizeof(serialBuffer[0])]; bool newData; + ProjectConfig *projectConfig; }; -extern SerialManager serialManager; \ No newline at end of file +#endif // SERIAL_MANAGER_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index c8e6aa8..1fe88c8 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -58,15 +58,15 @@ void WiFiHandler::setUpADHOC() log_i("[INFO]: Configuring access point...\n"); WiFi.mode(WIFI_AP); - // You can remove the password parameter if you want the AP to be open. Serial.printf("\r\nStarting AP. \r\nAP IP address: "); IPAddress IP = WiFi.softAPIP(); 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. WiFi.softAP(WIFI_SSID, WIFI_PASSWORD, ADHOC_CHANNEL, 0, 3); // AP mode with password WiFi.setTxPower(WIFI_POWER_11dBm); - stateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC)); + stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC); } // we can't assign wifiManager.resetSettings(); to reset, somehow it gets called straight away. diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index fdd37c2..ce080d6 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -21,6 +21,7 @@ uint8_t CONTROL_SERVER_PORT = 81; // it is used to create a unique pointer to a class and ensure exception safety std::unique_ptr deviceConfig = std::make_unique(); OTA ota(&*deviceConfig); +std::unique_ptr serialManager = std::make_unique(&*deviceConfig); std::unique_ptr wifiHandler = std::make_unique(&*deviceConfig, &wifiStateManager); std::unique_ptr ledManager = std::make_unique(33); std::shared_ptr cameraHandler = std::make_shared(&*deviceConfig); //! Create a shared pointer to the camera handler @@ -33,7 +34,7 @@ void setup() Serial.begin(115200); Serial.setDebugOutput(true); ledManager->begin(); - deviceConfig->initStructures(); + deviceConfig->initConfig(); deviceConfig->load(); cameraHandler->setupCamera(); @@ -76,5 +77,5 @@ void loop() { ota.HandleOTAUpdate(); ledManager->displayStatus(); - serialManager.handleSerial(); + serialManager->handleSerial(); } \ No newline at end of file From e0ddf4697d62bbdf73727ce04f73c359dcd3fa45 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 13 Aug 2022 00:37:36 +0100 Subject: [PATCH 028/153] update - implement full ADHOC - implement WiFi class config usage with ADHOC - implement API usage with WiFi class config struct --- .../src/network/WifiHandler/WifiHandler.hpp | 4 +- .../src/network/WifiHandler/wifiHandler.cpp | 42 ++++++++++++-- .../network/webserver/webserverHandler.cpp | 57 +++++++++++++++---- .../network/webserver/webserverHandler.hpp | 8 ++- ESP/src/main.cpp | 2 +- 5 files changed, 90 insertions(+), 23 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 24d2fd0..4ccc509 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -20,11 +20,13 @@ public: virtual ~WiFiHandler(); void setupWifi(); void setUpADHOC(); - void setWiFiConf(const char *value, uint8_t *location); + void adhoc(const char *ssid, const char *password); + void setWiFiConf(const char *value, uint8_t *location, wifi_config_t *conf); std::unique_ptr conf; private: ProjectConfig *configManager; StateManager *stateManager; + typedef ProgramStates::DeviceStates::WiFiState_e WiFiState_e; }; #endif // WIFIHANDLER_HPP diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 1fe88c8..f64cb31 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -9,7 +9,7 @@ WiFiHandler::~WiFiHandler() {} void WiFiHandler::setupWifi() { - if (ENABLE_ADHOC) + if (ENABLE_ADHOC || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { this->setUpADHOC(); return; @@ -51,7 +51,7 @@ void WiFiHandler::setupWifi() stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error); } -void WiFiHandler::setUpADHOC() +void WiFiHandler::adhoc(const char *ssid, const char *password) { log_i("[INFO]: Setting Access Point...\n"); @@ -63,12 +63,41 @@ void WiFiHandler::setUpADHOC() 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. - WiFi.softAP(WIFI_SSID, WIFI_PASSWORD, ADHOC_CHANNEL, 0, 3); // AP mode with password + WiFi.softAP(ssid, password, ADHOC_CHANNEL, 0, 3); // AP mode with password WiFi.setTxPower(WIFI_POWER_11dBm); stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC); } +void WiFiHandler::setUpADHOC() +{ + unsigned int ap_ssid_length = sizeof(conf->ap.ssid); + unsigned int ap_password_length = sizeof(conf->ap.password); + + char ap_ssid[ap_ssid_length + 1]; + char ap_password[ap_ssid_length + 1]; + memcpy(ap_ssid, conf->ap.ssid, ap_ssid_length); + memcpy(ap_password, conf->ap.password, ap_password_length); + + ap_ssid[ap_ssid_length] = '\0'; // Null-terminate the string + ap_password[ap_password_length] = '\0'; // Null-terminate the string + if (ap_ssid[0] == '\0' || NULL) + { + log_i("[INFO]: No SSID or password has been set.\n"); + log_i("[INFO]: USing the default value.\r\n"); + strcpy(ap_ssid, WIFI_SSID); + } + + if (ap_password[0] == '\0' || NULL) + { + log_i("[INFO]: No Password has been set.\n"); + log_i("[INFO]: Using the default value.\r\n"); + strcpy(ap_password, WIFI_PASSWORD); + } + + this->adhoc(ap_ssid, ap_password); +} + // we can't assign wifiManager.resetSettings(); to reset, somehow it gets called straight away. /** * @brief Resets the wifi settings to the chosen settings. @@ -76,18 +105,19 @@ void WiFiHandler::setUpADHOC() * @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) +void WiFiHandler::setWiFiConf(const char *value, uint8_t *location, wifi_config_t *conf) { + assert(conf != nullptr); #if defined(ESP32) if (WiFiGenericClass::getMode() != WIFI_MODE_NULL) { - esp_wifi_get_config(WIFI_IF_STA, &*conf); + esp_wifi_get_config(WIFI_IF_STA, conf); memset(location, 0, sizeof(location)); 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); + esp_wifi_set_config(WIFI_IF_STA, conf); } #endif } \ No newline at end of file diff --git a/ESP/lib/src/network/webserver/webserverHandler.cpp b/ESP/lib/src/network/webserver/webserverHandler.cpp index cb9aed0..0d0a8ec 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.cpp +++ b/ESP/lib/src/network/webserver/webserverHandler.cpp @@ -1,22 +1,24 @@ #include "webserverHandler.hpp" /* Constructor with unique_ptr */ -/* -APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler) : server(new AsyncWebServer(CONTROL_PORT)), cameraHandler(cameraHandler) {} -*/ -APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler) -{ - this->server = new AsyncWebServer(CONTROL_PORT); - this->cameraHandler = cameraHandler; -} +APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network) : network(network), + server(new AsyncWebServer(CONTROL_PORT)), + cameraHandler(cameraHandler) {} void APIServer::startAPIServer() { - this->server->on( + /* this->server->on( "/control", HTTP_GET, - std::bind(&APIServer::command_handler, this, std::placeholders::_1)); + std::bind(&APIServer::command_handler, this, std::placeholders::_1)); */ + + //! use lambdas instead of std::bind to avoid the overhead. + this->server->on( + "/control", + HTTP_GET, [&](AsyncWebServerRequest *request) + { command_handler(request); + request->send(200); }); log_d("Initializing web server"); this->server->begin(); @@ -39,6 +41,37 @@ void APIServer::command_handler(AsyncWebServerRequest *request) AsyncWebParameter *vflip_param = request->getParam("vflip"); cameraHandler->setVFlip(atoi(vflip_param->value().c_str())); } - - request->send(200); +#if ENABLE_ADHOC + if (request->hasParam("ap_ssid")) + { + AsyncWebParameter *ap_ssid_param = request->getParam("ap_ssid"); + network->setWiFiConf(ap_ssid_param->value().c_str(), network->conf->ap.ssid, &*network->conf); + } + if (request->hasParam("ap_password")) + { + AsyncWebParameter *ap_password_param = request->getParam("ap_password"); + network->setWiFiConf(ap_password_param->value().c_str(), network->conf->ap.password, &*network->conf); + } + if (request->hasParam("ap_channel")) + { + AsyncWebParameter *ap_channel_param = request->getParam("ap_channel"); + network->setWiFiConf(ap_channel_param->value().c_str(), &network->conf->ap.channel, &*network->conf); + } +#else + if (request->hasParam("ssid")) + { + AsyncWebParameter *ssid_param = request->getParam("ssid"); + network->setWiFiConf(ssid_param->value().c_str(), network->conf->sta.ssid, &*network->conf); + } + if (request->hasParam("password")) + { + AsyncWebParameter *password_param = request->getParam("password"); + network->setWiFiConf(password_param->value().c_str(), network->conf->sta.password, &*network->conf); + } + if (request->hasParam("channel")) + { + AsyncWebParameter *channel_param = request->getParam("channel"); + network->setWiFiConf(channel_param->value().c_str(), &network->conf->sta.channel, &*network->conf); + } +#endif // ENABLE_ADHOC } \ No newline at end of file diff --git a/ESP/lib/src/network/webserver/webserverHandler.hpp b/ESP/lib/src/network/webserver/webserverHandler.hpp index f3bb15e..528fd7c 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.hpp +++ b/ESP/lib/src/network/webserver/webserverHandler.hpp @@ -7,6 +7,7 @@ #include #include +#include "network/WifiHandler/WifiHandler.hpp" class APIServer { @@ -14,12 +15,13 @@ private: void command_handler(AsyncWebServerRequest *request); /* I think we should make these unique_ptr */ - //std::unique_ptr server; - //std::unique_ptr cameraHandler; + // std::unique_ptr server; + // std::unique_ptr cameraHandler; AsyncWebServer *server; CameraHandler *cameraHandler; + WiFiHandler *network; public: - APIServer(int CONTROL_PORT, CameraHandler *cameraHandler); + APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network); void startAPIServer(); }; diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index ce080d6..b076684 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -25,7 +25,7 @@ std::unique_ptr serialManager = std::make_unique(& std::unique_ptr wifiHandler = std::make_unique(&*deviceConfig, &wifiStateManager); std::unique_ptr ledManager = std::make_unique(33); std::shared_ptr cameraHandler = std::make_shared(&*deviceConfig); //! Create a shared pointer to the camera handler -std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler); //! Dereference the shared pointer to get the address of the camera handler +std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler, &*wifiHandler); //! Dereference the shared pointer to get the address of the camera handler std::unique_ptr mdnsHandler = std::make_unique(&mdnsStateManager, &*deviceConfig); std::unique_ptr streamServer = std::make_unique(STREAM_SERVER_PORT); From 61cf177f15b9fa02322dbc230ad02c99b8b4794b Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 13 Aug 2022 00:40:13 +0100 Subject: [PATCH 029/153] update - add some useful comments --- ESP/lib/src/network/webserver/webserverHandler.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/network/webserver/webserverHandler.cpp b/ESP/lib/src/network/webserver/webserverHandler.cpp index 0d0a8ec..25c6ddc 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.cpp +++ b/ESP/lib/src/network/webserver/webserverHandler.cpp @@ -1,7 +1,6 @@ #include "webserverHandler.hpp" /* Constructor with unique_ptr */ - APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network) : network(network), server(new AsyncWebServer(CONTROL_PORT)), cameraHandler(cameraHandler) {} @@ -13,7 +12,7 @@ void APIServer::startAPIServer() HTTP_GET, std::bind(&APIServer::command_handler, this, std::placeholders::_1)); */ - //! use lambdas instead of std::bind to avoid the overhead. + //! i have changed this to use lambdas instead of std::bind to avoid the overhead. Lambdas are always more preferable. this->server->on( "/control", HTTP_GET, [&](AsyncWebServerRequest *request) @@ -24,6 +23,7 @@ void APIServer::startAPIServer() this->server->begin(); } +//! To do - change this to use proper Hash Map to remove overhead of conditionals. void APIServer::command_handler(AsyncWebServerRequest *request) { if (request->hasParam("framesize")) From 6fe7bbce2f62085dd5d22fc2aad1315e0abebb32 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 13 Aug 2022 00:43:50 +0100 Subject: [PATCH 030/153] update - Add ADHOC channel support --- ESP/lib/src/network/WifiHandler/WifiHandler.hpp | 2 +- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 4ccc509..e024407 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -20,7 +20,7 @@ public: virtual ~WiFiHandler(); void setupWifi(); void setUpADHOC(); - void adhoc(const char *ssid, const char *password); + void adhoc(const char *ssid, const char *password, uint8_t channel); void setWiFiConf(const char *value, uint8_t *location, wifi_config_t *conf); std::unique_ptr conf; diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index f64cb31..f000e31 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -51,7 +51,7 @@ void WiFiHandler::setupWifi() stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error); } -void WiFiHandler::adhoc(const char *ssid, const char *password) +void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) { log_i("[INFO]: Setting Access Point...\n"); @@ -63,7 +63,7 @@ void WiFiHandler::adhoc(const char *ssid, const char *password) 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. - WiFi.softAP(ssid, password, ADHOC_CHANNEL, 0, 3); // AP mode with password + WiFi.softAP(ssid, password, channel, 0, 3); // AP mode with password WiFi.setTxPower(WIFI_POWER_11dBm); stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC); @@ -95,7 +95,14 @@ void WiFiHandler::setUpADHOC() strcpy(ap_password, WIFI_PASSWORD); } - this->adhoc(ap_ssid, ap_password); + if (conf->ap.channel == 0 || NULL) + { + log_i("[INFO]: No channel has been set.\n"); + log_i("[INFO]: Using the default value.\r\n"); + conf->ap.channel = ADHOC_CHANNEL; + } + + this->adhoc(ap_ssid, ap_password, conf->ap.channel); } // we can't assign wifiManager.resetSettings(); to reset, somehow it gets called straight away. From 652a1775b375739438360f27f7273ceed8382344 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 13 Aug 2022 01:36:47 +0100 Subject: [PATCH 031/153] update - Create typedefs for the StateManager --- .../src/data/StateManager/StateManager.cpp | 14 +++++------ .../src/data/StateManager/StateManager.hpp | 23 +++++++++++++------ .../src/network/WifiHandler/WifiHandler.hpp | 6 ++--- .../src/network/WifiHandler/wifiHandler.cpp | 10 ++++---- ESP/lib/src/network/mDNS/MDNSManager.cpp | 6 ++--- ESP/src/main.cpp | 12 +++++----- 6 files changed, 39 insertions(+), 32 deletions(-) diff --git a/ESP/lib/src/data/StateManager/StateManager.cpp b/ESP/lib/src/data/StateManager/StateManager.cpp index d1fae57..ba17b52 100644 --- a/ESP/lib/src/data/StateManager/StateManager.cpp +++ b/ESP/lib/src/data/StateManager/StateManager.cpp @@ -1,9 +1,9 @@ #include "StateManager.hpp" -StateManager stateManager; -StateManager wifiStateManager; -StateManager webServerStateManager; -StateManager mdnsStateManager; -StateManager cameraStateManager; -StateManager buttonStateManager; -StateManager streamStateManager; \ No newline at end of file +StateManager stateManager; +StateManager wifiStateManager; +StateManager webServerStateManager; +StateManager mdnsStateManager; +StateManager cameraStateManager; +StateManager buttonStateManager; +StateManager streamStateManager; \ No newline at end of file diff --git a/ESP/lib/src/data/StateManager/StateManager.hpp b/ESP/lib/src/data/StateManager/StateManager.hpp index 5fef403..e21128f 100644 --- a/ESP/lib/src/data/StateManager/StateManager.hpp +++ b/ESP/lib/src/data/StateManager/StateManager.hpp @@ -108,12 +108,21 @@ private: T _current_state; }; -extern StateManager stateManager; -extern StateManager wifiStateManager; -extern StateManager webServerStateManager; -extern StateManager mdnsStateManager; -extern StateManager cameraStateManager; -extern StateManager buttonStateManager; -extern StateManager streamStateManager; +typedef ProgramStates::DeviceStates::State_e State_e; +typedef ProgramStates::DeviceStates::WiFiState_e WiFiState_e; +typedef ProgramStates::DeviceStates::WebServerState_e WebServerState_e; +typedef ProgramStates::DeviceStates::MDNSState_e MDNSState_e; +typedef ProgramStates::DeviceStates::CameraState_e CameraState_e; +typedef ProgramStates::DeviceStates::ButtonState_e ButtonState_e; +typedef ProgramStates::DeviceStates::StreamState_e StreamState_e; + +extern StateManager stateManager; +extern StateManager wifiStateManager; +extern StateManager webServerStateManager; +extern StateManager mdnsStateManager; +extern StateManager cameraStateManager; +extern StateManager buttonStateManager; +extern StateManager streamStateManager; + #endif // STATEMANAGER_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index e024407..40a2f96 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -16,17 +16,15 @@ extern "C" class WiFiHandler { public: - WiFiHandler(ProjectConfig *configManager, StateManager *stateManager); + WiFiHandler(ProjectConfig *configManager, StateManager *stateManager); virtual ~WiFiHandler(); void setupWifi(); void setUpADHOC(); void adhoc(const char *ssid, const char *password, uint8_t channel); void setWiFiConf(const char *value, uint8_t *location, wifi_config_t *conf); std::unique_ptr conf; - private: ProjectConfig *configManager; - StateManager *stateManager; - typedef ProgramStates::DeviceStates::WiFiState_e WiFiState_e; + StateManager *stateManager; }; #endif // WIFIHANDLER_HPP diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index f000e31..7f490ec 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -1,7 +1,7 @@ #include "WifiHandler.hpp" #include -WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager) : conf(new wifi_config_t), +WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager) : conf(new wifi_config_t), configManager(configManager), stateManager(stateManager) {} @@ -15,7 +15,7 @@ void WiFiHandler::setupWifi() return; } log_i("Initializing connection to wifi"); - stateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting)); + stateManager->setState(WiFiState_e::WiFiState_Connecting); std::vector *networks = configManager->getWifiConfigs(); int connection_timeout = 3000; @@ -41,14 +41,14 @@ void WiFiHandler::setupWifi() else { log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid); - stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected); + stateManager->setState(WiFiState_e::WiFiState_Connected); return; } } // 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(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error); + stateManager->setState(WiFiState_e::WiFiState_Error); } void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) @@ -66,7 +66,7 @@ void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) WiFi.softAP(ssid, password, channel, 0, 3); // AP mode with password WiFi.setTxPower(WIFI_POWER_11dBm); - stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC); + stateManager->setState(WiFiState_e::WiFiState_ADHOC); } void WiFiHandler::setUpADHOC() diff --git a/ESP/lib/src/network/mDNS/MDNSManager.cpp b/ESP/lib/src/network/mDNS/MDNSManager.cpp index ae1ee43..7c5ad13 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.cpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.cpp @@ -6,15 +6,15 @@ void MDNSHandler::startMDNS() if (MDNS.begin(deviceConfig->name)) { - stateManager->setState(ProgramStates::DeviceStates::MDNSState_e::MDNSState_Starting); + stateManager->setState(MDNSState_e::MDNSState_Starting); MDNS.addService("openIrisTracker", "tcp", 80); MDNS.addServiceTxt("openIrisTracker", "tcp", "stream_port", String(80)); log_i("MDNS initialized!"); - stateManager->setState(ProgramStates::DeviceStates::MDNSState_e::MDNSState_Started); + stateManager->setState(MDNSState_e::MDNSState_Started); } else { - stateManager->setState(ProgramStates::DeviceStates::MDNSState_e::MDNSState_Error); + stateManager->setState(MDNSState_e::MDNSState_Error); log_e("Error initializing MDNS"); } } diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index b076684..21af4d7 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -43,29 +43,29 @@ void setup() switch (wifiStateManager.getCurrentState()) { - case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Disconnected: + case WiFiState_e::WiFiState_Disconnected: { break; } - case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Disconnecting: + case WiFiState_e::WiFiState_Disconnecting: { break; } - case ProgramStates::DeviceStates::WiFiState_e::WiFiState_ADHOC: + case WiFiState_e::WiFiState_ADHOC: { } - case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected: + case WiFiState_e::WiFiState_Connected: { apiServer->startAPIServer(); streamServer->startStreamServer(); log_d("[SETUP]: Starting Stream Server"); break; } - case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting: + case WiFiState_e::WiFiState_Connecting: { break; } - case ProgramStates::DeviceStates::WiFiState_e::WiFiState_Error: + case WiFiState_e::WiFiState_Error: { break; } From 5258f165133d9e3275e470d096191994dfc0b0b9 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 13 Aug 2022 03:12:30 +0100 Subject: [PATCH 032/153] update - Changed API to use unordered map and switchcase This improves performance, condences the code, and makes the code more portable --- .../network/webserver/webserverHandler.cpp | 114 +++++++++++------- .../network/webserver/webserverHandler.hpp | 30 ++++- 2 files changed, 95 insertions(+), 49 deletions(-) diff --git a/ESP/lib/src/network/webserver/webserverHandler.cpp b/ESP/lib/src/network/webserver/webserverHandler.cpp index 25c6ddc..32ac01a 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.cpp +++ b/ESP/lib/src/network/webserver/webserverHandler.cpp @@ -1,5 +1,9 @@ #include "webserverHandler.hpp" +//! This has to be called before the constructor of the class because it is static +//! C++ 11 does not have inline variables, sadly. So we have to do this. +std::unordered_map APIServer::command_map(0); + /* Constructor with unique_ptr */ APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network) : network(network), server(new AsyncWebServer(CONTROL_PORT)), @@ -7,6 +11,7 @@ APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler void APIServer::startAPIServer() { + begin(); /* this->server->on( "/control", HTTP_GET, @@ -23,55 +28,74 @@ void APIServer::startAPIServer() this->server->begin(); } -//! To do - change this to use proper Hash Map to remove overhead of conditionals. +void APIServer::findParam(AsyncWebServerRequest *request, const char *param, String &value) +{ + if (request->hasParam(param)) + { + value = request->getParam(param)->value(); + } +} + +void APIServer::begin() +{ + command_map.emplace("framesize", FRAME_SIZE); + command_map.emplace("hmirror", HMIRROR); + command_map.emplace("vflip", VFLIP); +#if ENABLE_ADHOC + command_map.emplace("ap_ssid", AP_SSID); + command_map.emplace("ap_password", AP_PASSWORD); + command_map.emplace("ap_channel", AP_CHANNEL); +#else + command_map.emplace("ssid", SSID); + command_map.emplace("password", PASSWORD); + command_map.emplace("channel", CHANNEL); +#endif // ENABLE_ADHOC +} + void APIServer::command_handler(AsyncWebServerRequest *request) { - if (request->hasParam("framesize")) + int params = request->params(); + for (int i = 0; i < params; i++) { - AsyncWebParameter *framesize_param = request->getParam("framesize"); - cameraHandler->setCameraResolution((framesize_t)atoi(framesize_param->value().c_str())); - } - if (request->hasParam("hmirror")) - { - AsyncWebParameter *hmirror_param = request->getParam("hmirror"); - cameraHandler->setHFlip(atoi(hmirror_param->value().c_str())); - } - if (request->hasParam("vflip")) - { - AsyncWebParameter *vflip_param = request->getParam("vflip"); - cameraHandler->setVFlip(atoi(vflip_param->value().c_str())); - } + AsyncWebParameter *param = request->getParam(i); + // HTTP POST Relay Value + { + switch (command_map[param->name().c_str()]) + { + case FRAME_SIZE: + cameraHandler->setCameraResolution((framesize_t)atoi(param->value().c_str())); + break; + case HMIRROR: + cameraHandler->setHFlip(atoi(param->value().c_str())); + break; + case VFLIP: + cameraHandler->setVFlip(atoi(param->value().c_str())); + break; #if ENABLE_ADHOC - if (request->hasParam("ap_ssid")) - { - AsyncWebParameter *ap_ssid_param = request->getParam("ap_ssid"); - network->setWiFiConf(ap_ssid_param->value().c_str(), network->conf->ap.ssid, &*network->conf); - } - if (request->hasParam("ap_password")) - { - AsyncWebParameter *ap_password_param = request->getParam("ap_password"); - network->setWiFiConf(ap_password_param->value().c_str(), network->conf->ap.password, &*network->conf); - } - if (request->hasParam("ap_channel")) - { - AsyncWebParameter *ap_channel_param = request->getParam("ap_channel"); - network->setWiFiConf(ap_channel_param->value().c_str(), &network->conf->ap.channel, &*network->conf); - } + case AP_SSID: + network->setWiFiConf(param->value().c_str(), network->conf->ap.ssid, &*network->conf); + break; + case AP_PASSWORD: + network->setWiFiConf(param->value().c_str(), network->conf->ap.password, &*network->conf); + break; + case AP_CHANNEL: + network->setWiFiConf(param->value().c_str(), &network->conf->ap.channel, &*network->conf); + break; #else - if (request->hasParam("ssid")) - { - AsyncWebParameter *ssid_param = request->getParam("ssid"); - network->setWiFiConf(ssid_param->value().c_str(), network->conf->sta.ssid, &*network->conf); - } - if (request->hasParam("password")) - { - AsyncWebParameter *password_param = request->getParam("password"); - network->setWiFiConf(password_param->value().c_str(), network->conf->sta.password, &*network->conf); - } - if (request->hasParam("channel")) - { - AsyncWebParameter *channel_param = request->getParam("channel"); - network->setWiFiConf(channel_param->value().c_str(), &network->conf->sta.channel, &*network->conf); - } + case SSID: + network->setWiFiConf(param->value().c_str(), network->conf->sta.ssid, &*network->conf); + break; + case PASSWORD: + network->setWiFiConf(param->value().c_str(), network->conf->sta.password, &*network->conf); + case CHANNEL: + network->setWiFiConf(param->value().c_str(), &network->conf->sta.channel, &*network->conf); + break; #endif // ENABLE_ADHOC + default: + log_d("Command not found"); + break; + } + } + log_i("GET[%s]: %s\n", param->name().c_str(), param->value().c_str()); + } } \ No newline at end of file diff --git a/ESP/lib/src/network/webserver/webserverHandler.hpp b/ESP/lib/src/network/webserver/webserverHandler.hpp index 528fd7c..f7dec52 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.hpp +++ b/ESP/lib/src/network/webserver/webserverHandler.hpp @@ -1,4 +1,8 @@ -#pragma once +#pragma onc +#ifndef WEBSERVERHANDLER_HPP +#define WEBSERVERHANDLER_HPP +#include +#include #include "io/camera/cameraHandler.hpp" #define WEBSERVER_H @@ -14,14 +18,32 @@ class APIServer private: void command_handler(AsyncWebServerRequest *request); - /* I think we should make these unique_ptr */ - // std::unique_ptr server; - // std::unique_ptr cameraHandler; AsyncWebServer *server; CameraHandler *cameraHandler; WiFiHandler *network; + enum command_func + { + FRAME_SIZE, + HMIRROR, + VFLIP, +#if ENABLE_ADHOC + AP_SSID, + AP_PASSWORD, + AP_CHANNEL, +#else + SSID, + PASSWORD, + CHANNEL, +#endif // ENABLE_ADHOC + }; + + static std::unordered_map command_map; + public: APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network); + void begin(); void startAPIServer(); + void findParam(AsyncWebServerRequest *request, const char *param, String &value); }; +#endif // WEBSERVERHANDLER_HPP From 1f6064a811a3f259ab499f601f2f195770f10ef8 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 13 Aug 2022 03:22:19 +0100 Subject: [PATCH 033/153] small update - changed log_d in command_handler to log_e --- ESP/lib/src/network/webserver/webserverHandler.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ESP/lib/src/network/webserver/webserverHandler.cpp b/ESP/lib/src/network/webserver/webserverHandler.cpp index 32ac01a..5fa9df3 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.cpp +++ b/ESP/lib/src/network/webserver/webserverHandler.cpp @@ -58,7 +58,6 @@ void APIServer::command_handler(AsyncWebServerRequest *request) for (int i = 0; i < params; i++) { AsyncWebParameter *param = request->getParam(i); - // HTTP POST Relay Value { switch (command_map[param->name().c_str()]) { @@ -92,7 +91,7 @@ void APIServer::command_handler(AsyncWebServerRequest *request) break; #endif // ENABLE_ADHOC default: - log_d("Command not found"); + log_e("Command not found"); break; } } From 72ece2617adafefdb2613e4d15890e7358e7d58b Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 13 Aug 2022 03:40:55 +0100 Subject: [PATCH 034/153] update --- .../src/data/utilities/enuminheritance.hpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 ESP/lib/src/data/utilities/enuminheritance.hpp diff --git a/ESP/lib/src/data/utilities/enuminheritance.hpp b/ESP/lib/src/data/utilities/enuminheritance.hpp new file mode 100644 index 0000000..75ef21e --- /dev/null +++ b/ESP/lib/src/data/utilities/enuminheritance.hpp @@ -0,0 +1,52 @@ +#pragma once +#ifndef ENUMINHERITANCE_HPP +#define ENUMINHERITANCE_HPP +template +class InheritEnum +{ +public: + InheritEnum() {} + InheritEnum(EnumT e) + : enum_(e) + { + } + + InheritEnum(BaseEnumT e) + : baseEnum_(e) + { + } + + explicit InheritEnum(int val) + : enum_(static_cast(val)) + { + } + + operator EnumT() const { return enum_; } + +private: + // Note - the value is declared as a union mainly for a debugging aid. If + // the union is undesired and you have other methods of debugging, change it + // to either of EnumT and do a cast for the constructor that accepts BaseEnumT. + union + { + EnumT enum_; + BaseEnumT baseEnum_; + }; +}; +#endif // ENUMINHERITANCE_HPP + +/* Example Usage */ +//enum Fruit +//{ +// Orange, +// Mango, +// Banana +//}; +//enum NewFruits +//{ +// Apple, +// Pear +//}; +//typedef InheritEnum MyFruit; +// +//void consume(MyFruit myfruit); From eca62867f4eddcd4aeaa6b282c7bce96bb05ce94 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 13 Aug 2022 21:35:18 +0100 Subject: [PATCH 035/153] major update - Changed command handler for API to Hash Map - removed switch case functionality - began addition of JSON handling in API --- ESP/lib/src/data/config/project_config.hpp | 6 + .../src/network/WifiHandler/WifiHandler.hpp | 2 +- .../network/webserver/webserverHandler.cpp | 258 ++++++++++++++---- .../network/webserver/webserverHandler.hpp | 87 ++++-- 4 files changed, 274 insertions(+), 79 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 4471d3f..9b56d23 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -22,6 +22,12 @@ public: const char *name; const char *OTAPassword; int OTAPort; + bool data_json; + bool config_json; + bool settings_json; + String data_json_string; + String config_json_string; + String settings_json_string; }; struct CameraConfig_t diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 40a2f96..46aadc0 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -23,8 +23,8 @@ public: void adhoc(const char *ssid, const char *password, uint8_t channel); void setWiFiConf(const char *value, uint8_t *location, wifi_config_t *conf); std::unique_ptr conf; -private: ProjectConfig *configManager; +private: StateManager *stateManager; }; #endif // WIFIHANDLER_HPP diff --git a/ESP/lib/src/network/webserver/webserverHandler.cpp b/ESP/lib/src/network/webserver/webserverHandler.cpp index 5fa9df3..9e652a6 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.cpp +++ b/ESP/lib/src/network/webserver/webserverHandler.cpp @@ -1,10 +1,19 @@ #include "webserverHandler.hpp" -//! This has to be called before the constructor of the class because it is static +//! These have to be called before the constructor of the class because they are static //! C++ 11 does not have inline variables, sadly. So we have to do this. -std::unordered_map APIServer::command_map(0); +const char *APIServer::MIMETYPE_HTML{"text/html"}; +// const char *APIServer::MIMETYPE_CSS{"text/css"}; +// const char *APIServer::MIMETYPE_JS{"application/javascript"}; +// const char *APIServer::MIMETYPE_PNG{"image/png"}; +// const char *APIServer::MIMETYPE_JPG{"image/jpeg"}; +// const char *APIServer::MIMETYPE_ICO{"image/x-icon"}; +const char *APIServer::MIMETYPE_JSON{"application/json"}; + +//********************************************************************************************* +//! API Server +//********************************************************************************************* -/* Constructor with unique_ptr */ APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network) : network(network), server(new AsyncWebServer(CONTROL_PORT)), cameraHandler(cameraHandler) {} @@ -18,13 +27,28 @@ void APIServer::startAPIServer() 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. - this->server->on( - "/control", - HTTP_GET, [&](AsyncWebServerRequest *request) - { command_handler(request); - request->send(200); }); + server->on("/", HTTP_GET, [&](AsyncWebServerRequest *request) + { request->send(200); }); - log_d("Initializing web server"); + // preflight cors check + server->on("/", HTTP_OPTIONS, [&](AsyncWebServerRequest *request) + { + AsyncWebServerResponse* response = request->beginResponse(204); + 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-Credentials", "true"); + request->send(response); }); + + DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); + + // std::bind(&APIServer::API_Utilities::notFound, &api_utilities, std::placeholders::_1); + server->onNotFound([&](AsyncWebServerRequest *request) + { api_utilities.notFound(request); }); + // Hex value of BUTT_PLUG_CONTROLLER == 425554545f504c55475f434f4e54524f4c4c4552 + this->server->on("/control", HTTP_GET, [&](AsyncWebServerRequest *request) + { command_handler(request); }); + + log_d("Initializing REST API"); this->server->begin(); } @@ -38,18 +62,24 @@ void APIServer::findParam(AsyncWebServerRequest *request, const char *param, Str void APIServer::begin() { - command_map.emplace("framesize", FRAME_SIZE); - command_map.emplace("hmirror", HMIRROR); - command_map.emplace("vflip", VFLIP); -#if ENABLE_ADHOC - command_map.emplace("ap_ssid", AP_SSID); - command_map.emplace("ap_password", AP_PASSWORD); - command_map.emplace("ap_channel", AP_CHANNEL); -#else - command_map.emplace("ssid", SSID); - command_map.emplace("password", PASSWORD); - command_map.emplace("channel", CHANNEL); -#endif // ENABLE_ADHOC + command_map_wifi_conf.emplace("ssid", [this](const char *value) -> void + { setSSID(value); }); + command_map_wifi_conf.emplace("password", [this](const char *value) -> void + { setPass(value); }); + command_map_wifi_conf.emplace("channel", [this](const char *value) -> void + { setChannel(value); }); + + command_map_funct.emplace("reboot_device", [this](void) -> void + { rebootDevice(); }); + command_map_funct.emplace("reset_config", [this](void) -> void + { factoryReset(); }); + + command_map_json.emplace("data_json", [this](AsyncWebServerRequest *request) -> void + { setDataJson(request); }); + command_map_json.emplace("config_json", [this](AsyncWebServerRequest *request) -> void + { setConfigJson(request); }); + command_map_json.emplace("settings_json", [this](AsyncWebServerRequest *request) -> void + { setSettingsJson(request); }); } void APIServer::command_handler(AsyncWebServerRequest *request) @@ -59,42 +89,160 @@ void APIServer::command_handler(AsyncWebServerRequest *request) { AsyncWebParameter *param = request->getParam(i); { - switch (command_map[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_json_t::const_iterator it_json = command_map_json.find(param->name().c_str()); + + if (it_wifi_conf != command_map_wifi_conf.end()) { - case FRAME_SIZE: - cameraHandler->setCameraResolution((framesize_t)atoi(param->value().c_str())); - break; - case HMIRROR: - cameraHandler->setHFlip(atoi(param->value().c_str())); - break; - case VFLIP: - cameraHandler->setVFlip(atoi(param->value().c_str())); - break; -#if ENABLE_ADHOC - case AP_SSID: - network->setWiFiConf(param->value().c_str(), network->conf->ap.ssid, &*network->conf); - break; - case AP_PASSWORD: - network->setWiFiConf(param->value().c_str(), network->conf->ap.password, &*network->conf); - break; - case AP_CHANNEL: - network->setWiFiConf(param->value().c_str(), &network->conf->ap.channel, &*network->conf); - break; -#else - case SSID: - network->setWiFiConf(param->value().c_str(), network->conf->sta.ssid, &*network->conf); - break; - case PASSWORD: - network->setWiFiConf(param->value().c_str(), network->conf->sta.password, &*network->conf); - case CHANNEL: - network->setWiFiConf(param->value().c_str(), &network->conf->sta.channel, &*network->conf); - break; -#endif // ENABLE_ADHOC - default: - log_e("Command not found"); - break; + command_map_wifi_conf.at(param->name().c_str())(param->value().c_str()); + auto &key_it = it_wifi_conf->first; + log_i("Command %s executed", key_it.c_str()); + } + else if (it_funct != command_map_funct.end()) + { + command_map_funct.at(param->name().c_str())(); + auto &key_it_funct = it_funct->first; + log_i("Command %s executed", key_it_funct.c_str()); + } + else if (it_json != command_map_json.end()) + { + command_map_json.at(param->name().c_str())(request); + auto &key_it_json = it_json->first; + log_i("Command %s executed", key_it_json.c_str()); + } + else + { + log_i("Command not found"); } } log_i("GET[%s]: %s\n", param->name().c_str(), param->value().c_str()); } -} \ No newline at end of file +} + +//********************************************************************************************* +//! Command Functions +//********************************************************************************************* +void APIServer::setSSID(const char *value) +{ +#if ENABLE_ADHOC + network->setWiFiConf(value, network->conf->ap.ssid, &*network->conf); +#else + network->setWiFiConf(value, network->conf->sta.ssid, &*network->conf); +#endif // ENABLE_ADHOC +} + +void APIServer::setPass(const char *value) +{ +#if ENABLE_ADHOC + network->setWiFiConf(network->conf->ap.password, value, &*network->conf); +#else + network->setWiFiConf(value, network->conf->sta.password, &*network->conf); +#endif // ENABLE_ADHOC +} + +void APIServer::setChannel(const char *value) +{ +#if ENABLE_ADHOC + network->setWiFiConf(value, network->conf->ap.channel, &*network->conf); +#else + network->setWiFiConf(value, &network->conf->sta.channel, &*network->conf); +#endif // ENABLE_ADHOC +} + +void APIServer::setDataJson(AsyncWebServerRequest *request) +{ + network->configManager->getDeviceConfig()->data_json = true; + api_utilities.my_delay(1L); + String temp = network->configManager->getDeviceConfig()->data_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; +} + +void APIServer::setConfigJson(AsyncWebServerRequest *request) +{ + network->configManager->getDeviceConfig()->config_json = true; + api_utilities.my_delay(1L); + String temp = network->configManager->getDeviceConfig()->config_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; +} + +void APIServer::setSettingsJson(AsyncWebServerRequest *request) +{ + network->configManager->getDeviceConfig()->settings_json = true; + api_utilities.my_delay(1L); + String temp = network->configManager->getDeviceConfig()->settings_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; +} + +void APIServer::rebootDevice() +{ + delay(20000); + ESP.restart(); +} +void APIServer::factoryReset() +{ + network->configManager->reset(); +} + +//********************************************************************************************* +//! API Utilities +//********************************************************************************************* + +APIServer::API_Utilities::API_Utilities() {} + +std::string +APIServer::API_Utilities::shaEncoder(std::string data) +{ + const char *data_c = data.c_str(); + int size = 20; + uint8_t hash[size]; + mbedtls_md_context_t ctx; + mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1; + + const size_t len = strlen(data_c); + mbedtls_md_init(&ctx); + mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); + mbedtls_md_starts(&ctx); + mbedtls_md_update(&ctx, (const unsigned char *)data_c, len); + mbedtls_md_finish(&ctx, hash); + mbedtls_md_free(&ctx); + + std::string hash_string = ""; + for (uint16_t i = 0; i < size; i++) + { + std::string hex = String(hash[i], HEX).c_str(); + if (hex.length() < 2) + { + hex = "0" + hex; + } + hash_string += hex; + } + return hash_string; +} + +void APIServer::API_Utilities::notFound(AsyncWebServerRequest *request) +{ + try + { + log_i("%s", _networkMethodsMap[request->method()]); + } + catch (const std::exception &e) + { + log_i("UNKNOWN"); + } + + log_i(" http://%s%s/\n", request->host().c_str(), request->url().c_str()); + request->send(404, "text/plain", "Not found."); +} + +void APIServer::API_Utilities::my_delay(volatile long delay_time) +{ + delay_time = delay_time * 1e6L; + for (volatile long count = delay_time; count > 0L; count--) + ; +} + +APIServer::API_Utilities api_utilities; \ No newline at end of file diff --git a/ESP/lib/src/network/webserver/webserverHandler.hpp b/ESP/lib/src/network/webserver/webserverHandler.hpp index f7dec52..75673ff 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.hpp +++ b/ESP/lib/src/network/webserver/webserverHandler.hpp @@ -1,18 +1,27 @@ -#pragma onc -#ifndef WEBSERVERHANDLER_HPP -#define WEBSERVERHANDLER_HPP +#pragma once +#ifndef XWEBSERVERHANDLER_HPP +#define XWEBSERVERHANDLER_HPP #include #include -#include "io/camera/cameraHandler.hpp" #define WEBSERVER_H -#define HTTP_ANY 0b01111111 -#define HTTP_GET 0b00000001 -#include +#define HTTP_GET 0b00000001 +#define HTTP_POST 0b00000010 +#define HTTP_DELETE 0b00000100 +#define HTTP_PUT 0b00001000 +#define HTTP_PATCH 0b00010000 +#define HTTP_HEAD 0b00100000 +#define HTTP_OPTIONS 0b01000000 +#define HTTP_ANY 0b01111111 + #include +#include +#include "mbedtls/md.h" +#include "io/camera/cameraHandler.hpp" #include "network/WifiHandler/WifiHandler.hpp" + class APIServer { private: @@ -22,28 +31,60 @@ private: CameraHandler *cameraHandler; WiFiHandler *network; - enum command_func - { - FRAME_SIZE, - HMIRROR, - VFLIP, -#if ENABLE_ADHOC - AP_SSID, - AP_PASSWORD, - AP_CHANNEL, -#else - SSID, - PASSWORD, - CHANNEL, -#endif // ENABLE_ADHOC - }; + /* Commands */ + void setSSID(const char *value); + void setPass(const char *value); + void setChannel(const char *value); - static std::unordered_map command_map; + void setDataJson(AsyncWebServerRequest *request); + void setConfigJson(AsyncWebServerRequest *request); + void setSettingsJson(AsyncWebServerRequest *request); + + void factoryReset(); + void rebootDevice(); + + typedef std::function wifi_conf_function; + typedef std::function function; + typedef std::function function_w_request; + + typedef std::unordered_map command_map_funct_t; + typedef std::unordered_map command_map_wifi_conf_t; + typedef std::unordered_map command_map_json_t; + + command_map_funct_t command_map_funct; + command_map_wifi_conf_t command_map_wifi_conf; + command_map_json_t command_map_json; + + static const char *MIMETYPE_HTML; + /* static const char *MIMETYPE_CSS; */ + /* static const char *MIMETYPE_JS; */ + /* static const char *MIMETYPE_PNG; */ + /* static const char *MIMETYPE_JPG; */ + /* static const char *MIMETYPE_ICO; */ + static const char *MIMETYPE_JSON; public: APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network); void begin(); void startAPIServer(); void findParam(AsyncWebServerRequest *request, const char *param, String &value); + + class API_Utilities + { + public: + API_Utilities(); + void notFound(AsyncWebServerRequest *request); + void my_delay(volatile long delay_time); + std::string shaEncoder(std::string data); + std::unordered_map _networkMethodsMap = { + {HTTP_GET, "GET"}, + {HTTP_POST, "POST"}, + {HTTP_PUT, "PUT"}, + {HTTP_DELETE, "DELETE"}, + {HTTP_PATCH, "PATCH"}, + {HTTP_OPTIONS, "OPTIONS"}, + }; + }; }; +extern APIServer::API_Utilities api_utilities; #endif // WEBSERVERHANDLER_HPP From b55e25971c80fb310f870bddb8b5ed425c902be2 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 14 Aug 2022 11:38:39 +0100 Subject: [PATCH 036/153] minor update - add official support for the ESPWRover boards (i tested it on mine - it works) --- .../src/network/WifiHandler/wifiHandler.cpp | 4 +- .../network/webserver/webserverHandler.cpp | 1 + ESP/platformio.ini | 107 ++++++++++++++---- 3 files changed, 88 insertions(+), 24 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 7f490ec..19116c8 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -2,8 +2,8 @@ #include WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager) : conf(new wifi_config_t), - configManager(configManager), - stateManager(stateManager) {} + configManager(configManager), + stateManager(stateManager) {} WiFiHandler::~WiFiHandler() {} diff --git a/ESP/lib/src/network/webserver/webserverHandler.cpp b/ESP/lib/src/network/webserver/webserverHandler.cpp index 9e652a6..1f2651a 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.cpp +++ b/ESP/lib/src/network/webserver/webserverHandler.cpp @@ -182,6 +182,7 @@ void APIServer::rebootDevice() delay(20000); ESP.restart(); } + void APIServer::factoryReset() { network->configManager->reset(); diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 234b2f8..459c81e 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -14,15 +14,15 @@ default_envs = debug ; do not change this value ; The below options are available for all environments ; The ssid and password are requried for the trackers to connect to your network!!! [wifi] -ssid="your_ssid_goes_here" ; your wifi network name goes here -password="your_password_goes_here" ; Place your Wifi password here +ssid="LoveHouse2G" ; your wifi network name goes here +password="vxwby2Gwtswp" ; Place your Wifi password here OTAPassword="" ; if empty, no password will be required OTAServerPort=3232 enableADHOC=0 ; 0 = disable, 1 = enable adhocChannel=10 ; channel to use for adhoc network ; DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING -[pinouts] +[pinoutsESPCAM] ; AI Tinker camera, the ov2650 PWDN_GPIO_NUM = 32 RESET_GPIO_NUM = -1 @@ -41,6 +41,25 @@ VSYNC_GPIO_NUM = 25 HREF_GPIO_NUM = 23 PCLK_GPIO_NUM = 22 +[pinoutsESPWROVER] +; CAMERA_MODEL_WROVER_KIT +PWDN_GPIO_NUM = -1 +RESET_GPIO_NUM = -1 +XCLK_GPIO_NUM = 21 +SIOD_GPIO_NUM = 26 +SIOC_GPIO_NUM = 27 +Y9_GPIO_NUM = 35 +Y8_GPIO_NUM = 34 +Y7_GPIO_NUM = 39 +Y6_GPIO_NUM = 36 +Y5_GPIO_NUM = 19 +Y4_GPIO_NUM = 18 +Y3_GPIO_NUM = 5 +Y2_GPIO_NUM = 4 +VSYNC_GPIO_NUM = 25 +HREF_GPIO_NUM = 23 +PCLK_GPIO_NUM = 22 + [common] platform = espressif32 board = esp32cam @@ -74,27 +93,12 @@ build_flags = ;-include "pinout.h" ; this has been added for future movement to a proper library structure ;-include "credentials.h" ; this has been added for future movement to a proper library structure - ; CAMERA PINOUT DEFINITIONS - -DPWDN_GPIO_NUM=${pinouts.PWDN_GPIO_NUM} ; Set the PWDN pin - -DRESET_GPIO_NUM=${pinouts.RESET_GPIO_NUM} ; Set the RESET pin - -DXCLK_GPIO_NUM=${pinouts.XCLK_GPIO_NUM} ; Set the XCLK pin - -DSIOD_GPIO_NUM=${pinouts.SIOD_GPIO_NUM} ; Set the SIOD pin - -DSIOC_GPIO_NUM=${pinouts.SIOC_GPIO_NUM} ; Set the SIOC pin - -DY9_GPIO_NUM=${pinouts.Y9_GPIO_NUM} ; Set the Y9 pin - -DY8_GPIO_NUM=${pinouts.Y8_GPIO_NUM} ; Set the Y8 pin - -DY7_GPIO_NUM=${pinouts.Y7_GPIO_NUM} ; Set the Y7 pin - -DY6_GPIO_NUM=${pinouts.Y6_GPIO_NUM} ; Set the Y6 pin - -DY5_GPIO_NUM=${pinouts.Y5_GPIO_NUM} ; Set the Y5 pin - -DY4_GPIO_NUM=${pinouts.Y4_GPIO_NUM} ; Set the Y4 pin - -DY3_GPIO_NUM=${pinouts.Y3_GPIO_NUM} ; Set the Y3 pin - -DY2_GPIO_NUM=${pinouts.Y2_GPIO_NUM} ; Set the Y2 pin - -DVSYNC_GPIO_NUM=${pinouts.VSYNC_GPIO_NUM} ; Set the VSYNC pin - -DHREF_GPIO_NUM=${pinouts.HREF_GPIO_NUM} ; Set the HREF pin - -DPCLK_GPIO_NUM=${pinouts.PCLK_GPIO_NUM} ; Set the PCLK pin + build_unflags = -Os -board_build.partitions = min_spiffs.csv +; board_build.partitions = min_spiffs.csv +board_build.partitions = huge_app.csv lib_ldf_mode = deep+ upload_speed = 921600 release_version = 0.0.1 ; increase this value every release build @@ -121,6 +125,25 @@ build_flags = ${common.build_flags} -DCORE_DEBUG_LEVEL=4 -DVERSION=0 + + ; CAMERA PINOUT DEFINITIONS + -DPWDN_GPIO_NUM=${pinoutsESPCAM.PWDN_GPIO_NUM} ; Set the PWDN pin + -DRESET_GPIO_NUM=${pinoutsESPCAM.RESET_GPIO_NUM} ; Set the RESET pin + -DXCLK_GPIO_NUM=${pinoutsESPCAM.XCLK_GPIO_NUM} ; Set the XCLK pin + -DSIOD_GPIO_NUM=${pinoutsESPCAM.SIOD_GPIO_NUM} ; Set the SIOD pin + -DSIOC_GPIO_NUM=${pinoutsESPCAM.SIOC_GPIO_NUM} ; Set the SIOC pin + -DY9_GPIO_NUM=${pinoutsESPCAM.Y9_GPIO_NUM} ; Set the Y9 pin + -DY8_GPIO_NUM=${pinoutsESPCAM.Y8_GPIO_NUM} ; Set the Y8 pin + -DY7_GPIO_NUM=${pinoutsESPCAM.Y7_GPIO_NUM} ; Set the Y7 pin + -DY6_GPIO_NUM=${pinoutsESPCAM.Y6_GPIO_NUM} ; Set the Y6 pin + -DY5_GPIO_NUM=${pinoutsESPCAM.Y5_GPIO_NUM} ; Set the Y5 pin + -DY4_GPIO_NUM=${pinoutsESPCAM.Y4_GPIO_NUM} ; Set the Y4 pin + -DY3_GPIO_NUM=${pinoutsESPCAM.Y3_GPIO_NUM} ; Set the Y3 pin + -DY2_GPIO_NUM=${pinoutsESPCAM.Y2_GPIO_NUM} ; Set the Y2 pin + -DVSYNC_GPIO_NUM=${pinoutsESPCAM.VSYNC_GPIO_NUM} ; Set the VSYNC pin + -DHREF_GPIO_NUM=${pinoutsESPCAM.HREF_GPIO_NUM} ; Set the HREF pin + -DPCLK_GPIO_NUM=${pinoutsESPCAM.PCLK_GPIO_NUM} ; Set the PCLK pin + build_unflags = ${common.build_unflags} board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} @@ -137,6 +160,7 @@ monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} build_flags = ${common.build_flags} + ${debug.build_flags} -DCORE_DEBUG_LEVEL=1 -DVERSION=${common.release_version} build_unflags = ${common.build_unflags} @@ -152,6 +176,7 @@ framework = ${common.framework} board = ${common.board} build_flags = ${common.build_flags} + ${debug.build_flags} -DCORE_DEBUG_LEVEL=1 -DDEBUG_ESP_OTA -DVERSION=${common.release_version} @@ -168,4 +193,42 @@ upload_port = 192.168.1.38 upload_protocol = espota upload_flags = --port=3232 - --auth=12345678 \ No newline at end of file + --auth=12345678 + +[env:wrover] +platform = ${common.platform} +board = esp-wrover-kit +framework = ${common.framework} +monitor_speed = ${common.monitor_speed} +;monitor_rts = ${common.monitor_rts} +;monitor_dtr = ${common.monitor_dtr} +build_flags = + ${common.build_flags} + -DCORE_DEBUG_LEVEL=4 + -DVERSION=${common.release_version} + + ; CAMERA PINOUT DEFINITIONS + -DPWDN_GPIO_NUM=${pinoutsESPWROVER.PWDN_GPIO_NUM} ; Set the PWDN pin + -DRESET_GPIO_NUM=${pinoutsESPWROVER.RESET_GPIO_NUM} ; Set the RESET pin + -DXCLK_GPIO_NUM=${pinoutsESPWROVER.XCLK_GPIO_NUM} ; Set the XCLK pin + -DSIOD_GPIO_NUM=${pinoutsESPWROVER.SIOD_GPIO_NUM} ; Set the SIOD pin + -DSIOC_GPIO_NUM=${pinoutsESPWROVER.SIOC_GPIO_NUM} ; Set the SIOC pin + -DY9_GPIO_NUM=${pinoutsESPWROVER.Y9_GPIO_NUM} ; Set the Y9 pin + -DY8_GPIO_NUM=${pinoutsESPWROVER.Y8_GPIO_NUM} ; Set the Y8 pin + -DY7_GPIO_NUM=${pinoutsESPWROVER.Y7_GPIO_NUM} ; Set the Y7 pin + -DY6_GPIO_NUM=${pinoutsESPWROVER.Y6_GPIO_NUM} ; Set the Y6 pin + -DY5_GPIO_NUM=${pinoutsESPWROVER.Y5_GPIO_NUM} ; Set the Y5 pin + -DY4_GPIO_NUM=${pinoutsESPWROVER.Y4_GPIO_NUM} ; Set the Y4 pin + -DY3_GPIO_NUM=${pinoutsESPWROVER.Y3_GPIO_NUM} ; Set the Y3 pin + -DY2_GPIO_NUM=${pinoutsESPWROVER.Y2_GPIO_NUM} ; Set the Y2 pin + -DVSYNC_GPIO_NUM=${pinoutsESPWROVER.VSYNC_GPIO_NUM} ; Set the VSYNC pin + -DHREF_GPIO_NUM=${pinoutsESPWROVER.HREF_GPIO_NUM} ; Set the HREF pin + -DPCLK_GPIO_NUM=${pinoutsESPWROVER.PCLK_GPIO_NUM} ; Set the PCLK pin + +build_unflags = ${common.build_unflags} +board_build.partitions = ${common.board_build.partitions} +lib_ldf_mode = ${common.lib_ldf_mode} +upload_speed = ${common.upload_speed} +lib_deps = + ${common.lib_deps} +upload_port = COM6 \ No newline at end of file From c426688eb20f58ff18e354953489fc6b10127570 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 14 Aug 2022 13:04:44 +0100 Subject: [PATCH 037/153] update - refactoring wifi handler --- .../src/network/WifiHandler/wifiHandler.cpp | 82 +-- ESP/license.md | 674 ------------------ ...latformio-device-monitor-220814-123248.log | Bin 0 -> 3079 bytes ...latformio-device-monitor-220814-130220.log | Bin 0 -> 1630 bytes ESP/platformio.ini | 91 ++- ESP/src/main.cpp | 4 +- 6 files changed, 109 insertions(+), 742 deletions(-) delete mode 100644 ESP/license.md create mode 100644 ESP/platformio-device-monitor-220814-123248.log create mode 100644 ESP/platformio-device-monitor-220814-130220.log diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 19116c8..9186aa6 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -18,23 +18,18 @@ void WiFiHandler::setupWifi() stateManager->setState(WiFiState_e::WiFiState_Connecting); std::vector *networks = configManager->getWifiConfigs(); - int connection_timeout = 3000; + int connection_timeout = 30000; // 30 seconds + + int count = 0; + unsigned long currentMillis = millis(); + unsigned long _previousMillis = currentMillis; for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) { log_i("Trying to connect to the %s network", networkIterator->ssid); - int timeSpentConnecting = 0; WiFi.begin(networkIterator->ssid, networkIterator->password); - int wifi_status = WiFi.status(); - - while (timeSpentConnecting < connection_timeout || wifi_status != WL_CONNECTED) - { - wifi_status = WiFi.status(); - log_i("."); - timeSpentConnecting += 300; - delay(300); - } + count++; if (!WiFi.isConnected()) log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid); @@ -44,11 +39,27 @@ void WiFiHandler::setupWifi() stateManager->setState(WiFiState_e::WiFiState_Connected); return; } - } - // 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); + while (WiFi.status() != WL_CONNECTED) + { + stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting); + currentMillis = millis(); + Serial.print("."); + delay(300); + if (((currentMillis - _previousMillis) >= connection_timeout) && count >= networks->size()) + { + 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->setUpADHOC(); + log_w("Setting up adhoc"); + log_w("Please set your WiFi credentials and reboot the device"); + stateManager->setState(WiFiState_e::WiFiState_ADHOC); + return; + } + } + } } void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) @@ -71,34 +82,25 @@ void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) void WiFiHandler::setUpADHOC() { - unsigned int ap_ssid_length = sizeof(conf->ap.ssid); - unsigned int ap_password_length = sizeof(conf->ap.password); - - char ap_ssid[ap_ssid_length + 1]; - char ap_password[ap_ssid_length + 1]; - memcpy(ap_ssid, conf->ap.ssid, ap_ssid_length); - memcpy(ap_password, conf->ap.password, ap_password_length); - - ap_ssid[ap_ssid_length] = '\0'; // Null-terminate the string - ap_password[ap_password_length] = '\0'; // Null-terminate the string - if (ap_ssid[0] == '\0' || NULL) + size_t ssidLen = strlen((char *)conf->ap.ssid); + size_t passwordLen = strlen((char *)conf->ap.password); + char ap_ssid[ssidLen + 1]; + char ap_password[passwordLen + 1]; + auto ret = esp_wifi_get_config(WIFI_IF_STA, &*conf); + if (ret == ESP_OK) + { + memcpy(ap_ssid, conf->ap.ssid, ssidLen); + memcpy(ap_password, conf->ap.password, passwordLen); + + ap_ssid[ssidLen] = '\0'; // Null-terminate the string + ap_password[passwordLen] = '\0'; // Null-terminate the string + return; + } + + if (ssidLen == 0) { - log_i("[INFO]: No SSID or password has been set.\n"); - log_i("[INFO]: USing the default value.\r\n"); strcpy(ap_ssid, WIFI_SSID); - } - - if (ap_password[0] == '\0' || NULL) - { - log_i("[INFO]: No Password has been set.\n"); - log_i("[INFO]: Using the default value.\r\n"); strcpy(ap_password, WIFI_PASSWORD); - } - - if (conf->ap.channel == 0 || NULL) - { - log_i("[INFO]: No channel has been set.\n"); - log_i("[INFO]: Using the default value.\r\n"); conf->ap.channel = ADHOC_CHANNEL; } diff --git a/ESP/license.md b/ESP/license.md deleted file mode 100644 index 12aca0a..0000000 --- a/ESP/license.md +++ /dev/null @@ -1,674 +0,0 @@ -GNU GENERAL PUBLIC LICENSE -Version 3, 29 June 2007 - -Copyright (C) 2007 Free Software Foundation, Inc. -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. - - Preamble - -The GNU General Public License is a free, copyleft license for -software and other kinds of works. - -The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - -For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - -Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - -Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - -Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - -0. Definitions. - -"This License" refers to version 3 of the GNU General Public License. - -"Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -"The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - -To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - -A "covered work" means either the unmodified Program or a work based -on the Program. - -To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - -To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - -An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - -1. Source Code. - -The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - -A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - -The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - -The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - -The Corresponding Source for a work in source code form is that -same work. - -2. Basic Permissions. - -All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - -3. Protecting Users' Legal Rights From Anti-Circumvention Law. - -No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - -When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - -4. Conveying Verbatim Copies. - -You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - -5. Conveying Modified Source Versions. - -You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - -A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - -6. Conveying Non-Source Forms. - -You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - -"Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - -If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - -The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - -7. Additional Terms. - -"Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - -All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - -8. Termination. - -You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - -However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - -Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - -9. Acceptance Not Required for Having Copies. - -You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - -10. Automatic Licensing of Downstream Recipients. - -Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - -An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - -11. Patents. - -A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - -In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - -If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - -A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - -12. No Surrender of Others' Freedom. - -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - -13. Use with the GNU Affero General Public License. - -Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - -14. Revised Versions of this License. - -The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - -If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - -Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - -15. Disclaimer of Warranty. - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. Limitation of Liability. - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - -17. Interpretation of Sections 15 and 16. - -If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - -If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - -You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - -The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. \ No newline at end of file diff --git a/ESP/platformio-device-monitor-220814-123248.log b/ESP/platformio-device-monitor-220814-123248.log new file mode 100644 index 0000000000000000000000000000000000000000..9b4245699bdd78af3a517ed9126e190aadc358bd GIT binary patch literal 3079 zcmb_eO>f&q5G`^H;6u?KdYoK>7Ex4^`m}%^6ibSQ*cL6yH3C5pC~{>nrbvY!c4VNJ z{+Hf*YA;2AqCieXZbi{Ue?|X7-|UiAe}vngKcU$`o#N@;_i9?T66)R0j}Ny8*`d?S&G$c8 zcp885#e)aME6Y#QW$}QH@pNJPPn}g-c3Ot6Pbe12!7A-V;&mzlXMMc5`SPn4nMX%0 zsx~$Hnhg4ejH*VMDN);e)}p4Sesp-VxA$;NM9o@dGVV;qB3@OLg;gBcOW0^uCnWp* zz)K{uHEbV~2<(|J+-&)Nvo4pfqVSb)lBp90bMK<;tX8c`b3%S-yS(%WcQ3f0>@`xa z6&Q`lxH}n}k(i4Jp@>)l)U?WkE=2Ndorw5I1Q*GIv4X33iqYxJ4`<|yfabR6x5yP& zo+IdFFq-xTXD6KkeE%bWJN8mU_I>dEkKuVBlIt+KoO;1LylX<&G!P7Ob`V^H26BRX z;6S*PgmPpj&$^}?GFK{?LpyMN5hC|cvQevC*%HPeD2M??eO(R2Fep0Ju6!dg-vMXr z-+>!NYX-vV42!$$9%ZS|0c!xnUOe}D-g6O%$a7?RniXVvDy~G39N4};vz<%!vK_gp z7lhR1i56+}l+OFT{&d)FcV1?Ym72==|ARCDX^q-bT*J{eA_U2Z7?%#}buc&+7hWK> zWA!_Tkfn&I!-$q%9D{&74VBvNG*oJLc!S~&!qj&u2$OBggRL}^8?maAT zekgF&dIMV8ktND07E+8A`_+0=+Zhcfz;+j*!wJYE$v1J^ z;T=L|=miPL*@V&DE#Nu?d=KnER`xVvCEE&cbr-Oq=^r5AN};xanT7jdfI4r9wpqv* zpjKi>vIMowGU2&xQr|?dZUlxl%-tE*_l>e%ZP{s$!&Tnaj?JB`Im(Kq%@$c1Gn+9^)ligmDt!)G08qS-~pL z9oqp;26aH;#G#l|#}iC$H;PbLigM4Q}ba+U#a zmHc7X8Xgt4B+Fl@`>UlZh z)nltWIx|s=3b|%@%69G+^u}ZjvMP*Siyfb?@GM=}hyf!w$z2=YQTf`eg5_&>+ttV6oA#tqK1AUDic!kb-O_V~oR9K$b+1=T1cE0^C&rUyHe7`(9rT7Oi*C`-bqit?=oCdTr z52fwZA`~?B!TQlO)dPS+K4-NmRtw|MR29NFa{5%Gkh36-Yn+J`xv^8)0OU^FM=v|R zLRs>77zH2D6}B7j4(l$uVOTT^7WjeV$)j}|8Sg@t1}bfYk+)iFR%<)L4o1`p#wkEv zGcD+%SRD$C>&UyJC$ab-wrSOF`#~Fga%thGTYTDJUx0{s_`0^cqyG|b? z=O*~dUEG|bI0&LWoAFL?y@al5L@<#vf#5u8;ELcXaey9(AYGZrv##k{`c|r$b%%RC zMvCcFOi5Ty+ms|XPzd>8NeEf*#HXT^aF%YtF^wBQ)ga-X($TzBY>Fy+D1~__#mV|k z7hykfd?toj1;f;Dsjy6 zUti8Z<%aBDDn5mg6p&UqNt*>+(tAKDBRG2f32?^BHMnLplt6Sk!;+!A9%N5{1(;XF z?y@R-jT|H9rq5F#I>5#Oa#41CzwNkt@|LB@OBfGeO>PuHg9X^FRcrRnTB-6rgEVt1 zDU<&PX%J+iS+dD?n&XHhNQp@6=>_#AVz7-}##8MyY8C2GN|Cw_BIvU?CIYUW!6e~M m;?2xog}()Sm+l64#a literal 0 HcmV?d00001 diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 459c81e..7157017 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -9,13 +9,13 @@ ; https://docs.platformio.org/page/projectconf.html [platformio] -default_envs = debug ; do not change this value +default_envs = esp32Cam ; do not change this value ; The below options are available for all environments ; The ssid and password are requried for the trackers to connect to your network!!! [wifi] -ssid="LoveHouse2G" ; your wifi network name goes here -password="vxwby2Gwtswp" ; Place your Wifi password here +ssid="EyeTrackVR" ; your wifi network name goes here +password="test" ; Place your Wifi password here OTAPassword="" ; if empty, no password will be required OTAServerPort=3232 enableADHOC=0 ; 0 = disable, 1 = enable @@ -62,11 +62,17 @@ PCLK_GPIO_NUM = 22 [common] platform = espressif32 -board = esp32cam framework = arduino monitor_speed = 115200 monitor_rts = 0 monitor_dtr = 0 +monitor_filters = + ;colorize -- uncomment this to get a colorful text in your terminal + log2file + time + default + esp32_exception_decoder + build_flags = -DOTA_SERVER_PORT=${wifi.OTAServerPort} ; Set the OTA server @@ -85,6 +91,8 @@ build_flags = -DDEBUG_ESP_PORT=Serial + -DCORE_DEBUG_LEVEL=4 + -DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue @@ -93,9 +101,6 @@ build_flags = ;-include "pinout.h" ; this has been added for future movement to a proper library structure ;-include "credentials.h" ; this has been added for future movement to a proper library structure - - - build_unflags = -Os ; board_build.partitions = min_spiffs.csv board_build.partitions = huge_app.csv @@ -108,23 +113,16 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git https://github.com/me-no-dev/AsyncTCP.git -[env:debug] +[env:esp32Cam] platform = ${common.platform} -board = ${common.board} +board = esp32cam framework = ${common.framework} monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} -monitor_filters = - ;colorize -- uncomment this to get a colorful text in your terminal - log2file - time - default - esp32_exception_decoder +monitor_filters = ${common.monitor_filters} build_flags = ${common.build_flags} - -DCORE_DEBUG_LEVEL=4 - -DVERSION=0 ; CAMERA PINOUT DEFINITIONS -DPWDN_GPIO_NUM=${pinoutsESPCAM.PWDN_GPIO_NUM} ; Set the PWDN pin @@ -151,16 +149,15 @@ upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} -[env:release] +[env:esp32Cam_release] platform = ${common.platform} -board = ${common.board} +board = esp32cam framework = ${common.framework} monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} build_flags = ${common.build_flags} - ${debug.build_flags} -DCORE_DEBUG_LEVEL=1 -DVERSION=${common.release_version} build_unflags = ${common.build_unflags} @@ -170,13 +167,12 @@ upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} ; Experimental OTA Environment - do not select unless you know what you are doing -[env:OTA] +[env:esp32Cam_OTA] platform = ${common.platform} +board = esp32cam framework = ${common.framework} -board = ${common.board} build_flags = ${common.build_flags} - ${debug.build_flags} -DCORE_DEBUG_LEVEL=1 -DDEBUG_ESP_OTA -DVERSION=${common.release_version} @@ -200,12 +196,12 @@ platform = ${common.platform} board = esp-wrover-kit framework = ${common.framework} monitor_speed = ${common.monitor_speed} +monitor_filters = ${common.monitor_filters} ;monitor_rts = ${common.monitor_rts} ;monitor_dtr = ${common.monitor_dtr} build_flags = ${common.build_flags} - -DCORE_DEBUG_LEVEL=4 - -DVERSION=${common.release_version} + -DVERSION=0 ; CAMERA PINOUT DEFINITIONS -DPWDN_GPIO_NUM=${pinoutsESPWROVER.PWDN_GPIO_NUM} ; Set the PWDN pin @@ -231,4 +227,47 @@ lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} -upload_port = COM6 \ No newline at end of file +upload_port = COM6 + +[env:wrover_release] +platform = ${common.platform} +board = esp-wrover-kit +framework = ${common.framework} +monitor_speed = ${common.monitor_speed} +monitor_rts = ${common.monitor_rts} +monitor_dtr = ${common.monitor_dtr} +build_flags = + ${common.build_flags} + -DCORE_DEBUG_LEVEL=1 + -DVERSION=${common.release_version} +build_unflags = ${common.build_unflags} +board_build.partitions = ${common.board_build.partitions} +lib_ldf_mode = ${common.lib_ldf_mode} +upload_speed = ${common.upload_speed} +lib_deps = ${common.lib_deps} +upload_port = COM6 + +; Experimental OTA Environment - do not select unless you know what you are doing +[env:wrover_OTA] +platform = ${common.platform} +board = esp-wrover-kit +framework = ${common.framework} +build_flags = + ${common.build_flags} + -DCORE_DEBUG_LEVEL=1 + -DDEBUG_ESP_OTA + -DVERSION=${common.release_version} +lib_deps = + ${common.lib_deps} +upload_speed = ${common.upload_speed} +monitor_speed = ${common.monitor_speed} +monitor_rts = ${common.monitor_rts} +monitor_dtr = ${common.monitor_dtr} +; extra_scripts = ${common.extra_scripts} +board_build.partitions = ${common.board_build.partitions} +lib_ldf_mode = ${common.lib_ldf_mode} +upload_port = 192.168.1.38 +upload_protocol = espota +upload_flags = + --port=3232 + --auth=12345678 diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 21af4d7..72de9bb 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -24,7 +24,7 @@ OTA ota(&*deviceConfig); std::unique_ptr serialManager = std::make_unique(&*deviceConfig); std::unique_ptr wifiHandler = std::make_unique(&*deviceConfig, &wifiStateManager); std::unique_ptr ledManager = std::make_unique(33); -std::shared_ptr cameraHandler = std::make_shared(&*deviceConfig); //! Create a shared pointer to the camera handler +std::shared_ptr cameraHandler = std::make_shared(&*deviceConfig); //! Create a shared pointer to the camera handler std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler, &*wifiHandler); //! Dereference the shared pointer to get the address of the camera handler std::unique_ptr mdnsHandler = std::make_unique(&mdnsStateManager, &*deviceConfig); std::unique_ptr streamServer = std::make_unique(STREAM_SERVER_PORT); @@ -77,5 +77,5 @@ void loop() { ota.HandleOTAUpdate(); ledManager->displayStatus(); - serialManager->handleSerial(); + // serialManager->handleSerial(); } \ No newline at end of file From b69e6f9fadf2703285efad2b0b02d3164fc946b2 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 14 Aug 2022 17:09:50 +0100 Subject: [PATCH 038/153] update gitignore to ignore log files --- ESP/.gitignore | 7 ++++--- ESP/platformio-device-monitor-220814-123248.log | Bin 3079 -> 0 bytes ESP/platformio-device-monitor-220814-130220.log | Bin 1630 -> 0 bytes 3 files changed, 4 insertions(+), 3 deletions(-) delete mode 100644 ESP/platformio-device-monitor-220814-123248.log delete mode 100644 ESP/platformio-device-monitor-220814-130220.log diff --git a/ESP/.gitignore b/ESP/.gitignore index 661538a..31f4c8f 100644 --- a/ESP/.gitignore +++ b/ESP/.gitignore @@ -1,3 +1,4 @@ -.pio -.vscode -build +.pio/ +.vscode/ +build/ +*.log diff --git a/ESP/platformio-device-monitor-220814-123248.log b/ESP/platformio-device-monitor-220814-123248.log deleted file mode 100644 index 9b4245699bdd78af3a517ed9126e190aadc358bd..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3079 zcmb_eO>f&q5G`^H;6u?KdYoK>7Ex4^`m}%^6ibSQ*cL6yH3C5pC~{>nrbvY!c4VNJ z{+Hf*YA;2AqCieXZbi{Ue?|X7-|UiAe}vngKcU$`o#N@;_i9?T66)R0j}Ny8*`d?S&G$c8 zcp885#e)aME6Y#QW$}QH@pNJPPn}g-c3Ot6Pbe12!7A-V;&mzlXMMc5`SPn4nMX%0 zsx~$Hnhg4ejH*VMDN);e)}p4Sesp-VxA$;NM9o@dGVV;qB3@OLg;gBcOW0^uCnWp* zz)K{uHEbV~2<(|J+-&)Nvo4pfqVSb)lBp90bMK<;tX8c`b3%S-yS(%WcQ3f0>@`xa z6&Q`lxH}n}k(i4Jp@>)l)U?WkE=2Ndorw5I1Q*GIv4X33iqYxJ4`<|yfabR6x5yP& zo+IdFFq-xTXD6KkeE%bWJN8mU_I>dEkKuVBlIt+KoO;1LylX<&G!P7Ob`V^H26BRX z;6S*PgmPpj&$^}?GFK{?LpyMN5hC|cvQevC*%HPeD2M??eO(R2Fep0Ju6!dg-vMXr z-+>!NYX-vV42!$$9%ZS|0c!xnUOe}D-g6O%$a7?RniXVvDy~G39N4};vz<%!vK_gp z7lhR1i56+}l+OFT{&d)FcV1?Ym72==|ARCDX^q-bT*J{eA_U2Z7?%#}buc&+7hWK> zWA!_Tkfn&I!-$q%9D{&74VBvNG*oJLc!S~&!qj&u2$OBggRL}^8?maAT zekgF&dIMV8ktND07E+8A`_+0=+Zhcfz;+j*!wJYE$v1J^ z;T=L|=miPL*@V&DE#Nu?d=KnER`xVvCEE&cbr-Oq=^r5AN};xanT7jdfI4r9wpqv* zpjKi>vIMowGU2&xQr|?dZUlxl%-tE*_l>e%ZP{s$!&Tnaj?JB`Im(Kq%@$c1Gn+9^)ligmDt!)G08qS-~pL z9oqp;26aH;#G#l|#}iC$H;PbLigM4Q}ba+U#a zmHc7X8Xgt4B+Fl@`>UlZh z)nltWIx|s=3b|%@%69G+^u}ZjvMP*Siyfb?@GM=}hyf!w$z2=YQTf`eg5_&>+ttV6oA#tqK1AUDic!kb-O_V~oR9K$b+1=T1cE0^C&rUyHe7`(9rT7Oi*C`-bqit?=oCdTr z52fwZA`~?B!TQlO)dPS+K4-NmRtw|MR29NFa{5%Gkh36-Yn+J`xv^8)0OU^FM=v|R zLRs>77zH2D6}B7j4(l$uVOTT^7WjeV$)j}|8Sg@t1}bfYk+)iFR%<)L4o1`p#wkEv zGcD+%SRD$C>&UyJC$ab-wrSOF`#~Fga%thGTYTDJUx0{s_`0^cqyG|b? z=O*~dUEG|bI0&LWoAFL?y@al5L@<#vf#5u8;ELcXaey9(AYGZrv##k{`c|r$b%%RC zMvCcFOi5Ty+ms|XPzd>8NeEf*#HXT^aF%YtF^wBQ)ga-X($TzBY>Fy+D1~__#mV|k z7hykfd?toj1;f;Dsjy6 zUti8Z<%aBDDn5mg6p&UqNt*>+(tAKDBRG2f32?^BHMnLplt6Sk!;+!A9%N5{1(;XF z?y@R-jT|H9rq5F#I>5#Oa#41CzwNkt@|LB@OBfGeO>PuHg9X^FRcrRnTB-6rgEVt1 zDU<&PX%J+iS+dD?n&XHhNQp@6=>_#AVz7-}##8MyY8C2GN|Cw_BIvU?CIYUW!6e~M m;?2xog}()Sm+l64#a From 8ce0ea086063d725dda0e03f18580c84ec099269 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 15 Aug 2022 05:54:06 +0100 Subject: [PATCH 039/153] update - Fix preferences lib - Fix ADHOC - Optimize API - Implement full preferences lib - Implement API with preferences lib --- ESP/lib/src/data/config/project_config.cpp | 102 +++++- ESP/lib/src/data/config/project_config.hpp | 26 +- .../src/io/SerialManager/serialmanager.cpp | 34 +- .../src/io/SerialManager/serialmanager.hpp | 1 + ESP/lib/src/network/OTA/OTA.cpp | 2 +- .../src/network/WifiHandler/WifiHandler.hpp | 16 +- .../src/network/WifiHandler/wifiHandler.cpp | 217 ++++++------ ESP/lib/src/network/mDNS/MDNSManager.cpp | 2 +- .../network/webserver/webserverHandler.cpp | 314 ++++++++++-------- .../network/webserver/webserverHandler.hpp | 19 +- ESP/platformio.ini | 13 +- ESP/src/main.cpp | 1 + 12 files changed, 449 insertions(+), 298 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 8a2d368..7e86b8f 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -2,7 +2,7 @@ Preferences preferences; -ProjectConfig::ProjectConfig() : Config(&preferences ,"config"), _already_loaded(false) {} +ProjectConfig::ProjectConfig() : Config(&preferences, "config"), _already_loaded(false) {} ProjectConfig::~ProjectConfig() {} @@ -18,19 +18,28 @@ void ProjectConfig::initConfig() "", 0, }; + this->config.camera = { 0, 0, 0, 0, }; + this->config.networks = { { "", "", "", + 0, }, }; + + this->config.ap_network = { + "", + "", + 0, + }; } void ProjectConfig::load() @@ -42,13 +51,41 @@ void ProjectConfig::load() return; } - bool device_success = this->read("device", this->config.device); - bool camera_success = this->read("camera", this->config.camera); - bool network_info_success = this->read("network_info", this->config.networks); + bool device_name_success = this->read("device_name", this->config.device.name); + bool device_otapassword_success = this->read("ota_pass", this->config.device.OTAPassword); + 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) { - log_e("Failed to load project config"); + log_e("Failed to load project config - Generating config and restarting"); + save(); + delay(1000); + ESP.restart(); return; } @@ -59,9 +96,28 @@ void ProjectConfig::load() void ProjectConfig::save() { log_d("Saving project config"); - this->write("device", this->config.device); - this->write("camera", this->config.camera); - this->write("network_info", this->config.networks); + + this->write("device_name", this->config.device.name); + 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() @@ -79,8 +135,8 @@ void ProjectConfig::setDeviceConfig(const char *name, const char *OTAPassword, i { log_d("Updating device config"); this->config.device = { - name, - OTAPassword, + (char *)name, + (char *)OTAPassword, *OTAPort, }; 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; 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]; } @@ -119,13 +175,29 @@ void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, con { this->config.networks = { { - networkName, - ssid, - password, + (char *)networkName, + (char *)ssid, + (char *)password, + *channel, }, }; if (shouldNotify) this->notify(ObserverEvent::networksConfigUpdated); } 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); + } } \ No newline at end of file diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 9b56d23..20bd0fd 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "data/utilities/Observer.hpp" @@ -19,8 +20,8 @@ public: struct DeviceConfig_t { - const char *name; - const char *OTAPassword; + std::string name; + std::string OTAPassword; int OTAPort; bool data_json; bool config_json; @@ -40,9 +41,17 @@ public: struct WiFiConfig_t { - const char *name; - const char *ssid; - const char *password; + std::string name; + std::string ssid; + std::string password; + uint8_t channel; + }; + + struct AP_WiFiConfig_t + { + std::string ssid; + std::string password; + uint8_t channel; }; struct TrackerConfig_t @@ -50,16 +59,19 @@ public: DeviceConfig_t device; CameraConfig_t camera; std::vector networks; + AP_WiFiConfig_t ap_network; }; DeviceConfig_t *getDeviceConfig() { return &this->config.device; } CameraConfig_t *getCameraConfig() { return &this->config.camera; } std::vector *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 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: const char *configFileName; TrackerConfig_t config; diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp index 54db530..0df354d 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -1,20 +1,21 @@ #include "serialmanager.hpp" SerialManager::SerialManager(ProjectConfig *projectConfig) : projectConfig(projectConfig), - serialManagerActive(false), - newData(false), - tempBuffer{0}, - serialBuffer{0}, - device_config_name{0}, - device_config_OTAPassword{0}, - device_config_OTAPort(0), - camera_config_vflip{0}, - camera_config_href{0}, - camera_config_framesize{0}, - camera_config_quality{0}, - wifi_config_name{0}, - wifi_config_ssid{0}, - wifi_config_password{0} {} + serialManagerActive(false), + newData(false), + tempBuffer{0}, + serialBuffer{0}, + device_config_name{0}, + device_config_OTAPassword{0}, + device_config_OTAPort(0), + camera_config_vflip{0}, + camera_config_href{0}, + camera_config_framesize{0}, + camera_config_quality{0}, + wifi_config_name{0}, + wifi_config_ssid{0}, + wifi_config_password{0}, + wifi_config_channel(0) {} SerialManager::~SerialManager() {} @@ -104,6 +105,9 @@ void SerialManager::parseData() strtokIndx = strtok(NULL, ","); strcpy(wifi_config_password, strtokIndx); + + strtokIndx = strtok(NULL, ","); + wifi_config_channel = atoi(strtokIndx); } void SerialManager::handleSerial() @@ -115,7 +119,7 @@ void SerialManager::handleSerial() 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->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 newData = false; // reset new data } diff --git a/ESP/lib/src/io/SerialManager/serialmanager.hpp b/ESP/lib/src/io/SerialManager/serialmanager.hpp index 3ab5659..c949c84 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.hpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.hpp @@ -30,6 +30,7 @@ public: char wifi_config_name[32]; char wifi_config_ssid[100]; char wifi_config_password[100]; + uint8_t wifi_config_channel; private: diff --git a/ESP/lib/src/network/OTA/OTA.cpp b/ESP/lib/src/network/OTA/OTA.cpp index 2fcde6f..7abd36d 100644 --- a/ESP/lib/src/network/OTA/OTA.cpp +++ b/ESP/lib/src/network/OTA/OTA.cpp @@ -9,7 +9,7 @@ void OTA::SetupOTA() log_e("Setting up OTA updates"); auto localConfig = _deviceConfig->getDeviceConfig(); - if (strcmp(localConfig->OTAPassword, "") == 0) + if (strcmp(localConfig->OTAPassword.c_str(), "") == 0) { log_e("THE PASSWORD IS REQUIRED, [[ABORTING]]"); return; diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 46aadc0..fd77729 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -6,25 +6,17 @@ #include "data/StateManager/StateManager.hpp" #include "data/config/project_config.hpp" -extern "C" -{ -#include -#include -#include -} - class WiFiHandler { public: WiFiHandler(ProjectConfig *configManager, StateManager *stateManager); virtual ~WiFiHandler(); void setupWifi(); + ProjectConfig *configManager; + StateManager *stateManager; +private: void setUpADHOC(); void adhoc(const char *ssid, const char *password, uint8_t channel); - void setWiFiConf(const char *value, uint8_t *location, wifi_config_t *conf); - std::unique_ptr conf; - ProjectConfig *configManager; -private: - StateManager *stateManager; + void iniSTA(); }; #endif // WIFIHANDLER_HPP diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 9186aa6..7ab4d9b 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -1,132 +1,153 @@ #include "WifiHandler.hpp" #include -WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager) : conf(new wifi_config_t), - configManager(configManager), - stateManager(stateManager) {} +WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager) : configManager(configManager), + stateManager(stateManager) {} WiFiHandler::~WiFiHandler() {} void WiFiHandler::setupWifi() { - if (ENABLE_ADHOC || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) - { - this->setUpADHOC(); - return; - } - log_i("Initializing connection to wifi"); - stateManager->setState(WiFiState_e::WiFiState_Connecting); + if (ENABLE_ADHOC || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + { + this->setUpADHOC(); + return; + } + log_i("Initializing connection to wifi"); + stateManager->setState(WiFiState_e::WiFiState_Connecting); - std::vector *networks = configManager->getWifiConfigs(); - int connection_timeout = 30000; // 30 seconds + std::vector *networks = configManager->getWifiConfigs(); + int connection_timeout = 30000; // 30 seconds - int count = 0; - unsigned long currentMillis = millis(); - unsigned long _previousMillis = currentMillis; + int count = 0; + unsigned long currentMillis = millis(); + unsigned long _previousMillis = currentMillis; - for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) - { - log_i("Trying to connect to the %s network", networkIterator->ssid); + for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) + { + log_i("Trying to connect to the %s network", networkIterator->ssid); - WiFi.begin(networkIterator->ssid, networkIterator->password); - count++; + WiFi.begin(networkIterator->ssid.c_str(), networkIterator->password.c_str()); + count++; - if (!WiFi.isConnected()) - log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid); - else - { - log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid); - stateManager->setState(WiFiState_e::WiFiState_Connected); - return; - } + if (!WiFi.isConnected()) + log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid); + else + { + log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->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) && count >= networks->size()) - { - 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->setUpADHOC(); - log_w("Setting up adhoc"); - log_w("Please set your WiFi credentials and reboot the device"); - stateManager->setState(WiFiState_e::WiFiState_ADHOC); - 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) && count >= networks->size()) + { + 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; + } + } + } } 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"); - WiFi.mode(WIFI_AP); + log_i("[INFO]: Configuring access point...\n"); + WiFi.mode(WIFI_AP); - Serial.printf("\r\nStarting AP. \r\nAP IP address: "); - IPAddress IP = WiFi.softAPIP(); - Serial.printf("[INFO]: AP IP address: %s.\r\n", IP.toString().c_str()); + Serial.printf("\r\nStarting AP. \r\nAP IP address: "); + IPAddress IP = WiFi.softAPIP(); + 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. - WiFi.softAP(ssid, password, channel, 0, 3); // AP mode with password + // 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.setTxPower(WIFI_POWER_11dBm); - stateManager->setState(WiFiState_e::WiFiState_ADHOC); + WiFi.setTxPower(WIFI_POWER_11dBm); + stateManager->setState(WiFiState_e::WiFiState_ADHOC); } +/* +* * +*/ void WiFiHandler::setUpADHOC() { - size_t ssidLen = strlen((char *)conf->ap.ssid); - size_t passwordLen = strlen((char *)conf->ap.password); - char ap_ssid[ssidLen + 1]; - char ap_password[passwordLen + 1]; - auto ret = esp_wifi_get_config(WIFI_IF_STA, &*conf); - if (ret == ESP_OK) - { - memcpy(ap_ssid, conf->ap.ssid, ssidLen); - memcpy(ap_password, conf->ap.password, passwordLen); + log_i("[INFO]: Setting Access Point...\n"); + size_t ssidLen = strlen(configManager->getAPWifiConfig()->ssid.c_str()); + size_t passwordLen = strlen(configManager->getAPWifiConfig()->password.c_str()); + char ssid[ssidLen + 1]; + char password[passwordLen + 1]; + uint8_t channel = configManager->getAPWifiConfig()->channel; + if (ssidLen > 0 || passwordLen > 0) + { + 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 - 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(ssid, password, 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. -/** - * @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) +void WiFiHandler::iniSTA() { - assert(conf != nullptr); -#if defined(ESP32) - if (WiFiGenericClass::getMode() != WIFI_MODE_NULL) - { - esp_wifi_get_config(WIFI_IF_STA, conf); + log_i("[INFO]: Setting up station...\n"); + int connection_timeout = 30000; // 30 seconds + unsigned long currentMillis = millis(); + unsigned long _previousMillis = currentMillis; - memset(location, 0, sizeof(location)); - for (int i = 0; i < sizeof(value) / sizeof(value[0]) && i < sizeof(location); i++) - location[i] = value[i]; + log_i("Trying to connect to the %s network", WIFI_SSID); - esp_wifi_set_config(WIFI_IF_STA, conf); - } -#endif + WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); + + 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; + } + } } \ No newline at end of file diff --git a/ESP/lib/src/network/mDNS/MDNSManager.cpp b/ESP/lib/src/network/mDNS/MDNSManager.cpp index 7c5ad13..3c261ac 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.cpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.cpp @@ -4,7 +4,7 @@ void MDNSHandler::startMDNS() { ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig(); - if (MDNS.begin(deviceConfig->name)) + if (MDNS.begin(deviceConfig->name.c_str())) { stateManager->setState(MDNSState_e::MDNSState_Starting); MDNS.addService("openIrisTracker", "tcp", 80); diff --git a/ESP/lib/src/network/webserver/webserverHandler.cpp b/ESP/lib/src/network/webserver/webserverHandler.cpp index 1f2651a..f313df0 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.cpp +++ b/ESP/lib/src/network/webserver/webserverHandler.cpp @@ -10,114 +10,118 @@ const char *APIServer::MIMETYPE_HTML{"text/html"}; // const char *APIServer::MIMETYPE_ICO{"image/x-icon"}; const char *APIServer::MIMETYPE_JSON{"application/json"}; +bool APIServer::ssid_write = false; +bool APIServer::pass_write = false; +bool APIServer::channel_write = false; + //********************************************************************************************* //! API Server //********************************************************************************************* APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network) : network(network), - server(new AsyncWebServer(CONTROL_PORT)), - cameraHandler(cameraHandler) {} + server(new AsyncWebServer(CONTROL_PORT)), + cameraHandler(cameraHandler) {} void APIServer::startAPIServer() { - begin(); - /* this->server->on( - "/control", - HTTP_GET, - std::bind(&APIServer::command_handler, this, std::placeholders::_1)); */ + begin(); + /* this->server->on( + "/control", + HTTP_GET, + 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. - server->on("/", HTTP_GET, [&](AsyncWebServerRequest *request) - { request->send(200); }); + //! 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) + { request->send(200); }); - // preflight cors check - server->on("/", HTTP_OPTIONS, [&](AsyncWebServerRequest *request) - { + // preflight cors check + server->on("/", HTTP_OPTIONS, [&](AsyncWebServerRequest *request) + { AsyncWebServerResponse* response = request->beginResponse(204); 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-Credentials", "true"); 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); - server->onNotFound([&](AsyncWebServerRequest *request) - { api_utilities.notFound(request); }); - // Hex value of BUTT_PLUG_CONTROLLER == 425554545f504c55475f434f4e54524f4c4c4552 - this->server->on("/control", HTTP_GET, [&](AsyncWebServerRequest *request) - { command_handler(request); }); + // std::bind(&APIServer::API_Utilities::notFound, &api_utilities, std::placeholders::_1); + server->onNotFound([&](AsyncWebServerRequest *request) + { api_utilities.notFound(request); }); + // Hex value of BUTT_PLUG_CONTROLLER == 425554545f504c55475f434f4e54524f4c4c4552 + this->server->on("/control", HTTP_GET, [&](AsyncWebServerRequest *request) + { command_handler(request); }); - log_d("Initializing REST API"); - this->server->begin(); + log_d("Initializing REST API"); + this->server->begin(); } void APIServer::findParam(AsyncWebServerRequest *request, const char *param, String &value) { - if (request->hasParam(param)) - { - value = request->getParam(param)->value(); - } + if (request->hasParam(param)) + { + value = request->getParam(param)->value(); + } } void APIServer::begin() { - command_map_wifi_conf.emplace("ssid", [this](const char *value) -> void - { setSSID(value); }); - command_map_wifi_conf.emplace("password", [this](const char *value) -> void - { setPass(value); }); - command_map_wifi_conf.emplace("channel", [this](const char *value) -> void - { setChannel(value); }); + command_map_wifi_conf.emplace("ssid", [this](const char *value) -> void + { setSSID(value); }); + command_map_wifi_conf.emplace("password", [this](const char *value) -> void + { setPass(value); }); + command_map_wifi_conf.emplace("channel", [this](const char *value) -> void + { setChannel(value); }); - command_map_funct.emplace("reboot_device", [this](void) -> void - { rebootDevice(); }); - command_map_funct.emplace("reset_config", [this](void) -> void - { factoryReset(); }); + command_map_funct.emplace("reboot_device", [this](void) -> void + { rebootDevice(); }); + command_map_funct.emplace("reset_config", [this](void) -> void + { factoryReset(); }); - command_map_json.emplace("data_json", [this](AsyncWebServerRequest *request) -> void - { setDataJson(request); }); - command_map_json.emplace("config_json", [this](AsyncWebServerRequest *request) -> void - { setConfigJson(request); }); - command_map_json.emplace("settings_json", [this](AsyncWebServerRequest *request) -> void - { setSettingsJson(request); }); + command_map_json.emplace("data_json", [this](AsyncWebServerRequest *request) -> void + { setDataJson(request); }); + command_map_json.emplace("config_json", [this](AsyncWebServerRequest *request) -> void + { setConfigJson(request); }); + command_map_json.emplace("settings_json", [this](AsyncWebServerRequest *request) -> void + { setSettingsJson(request); }); } void APIServer::command_handler(AsyncWebServerRequest *request) { - int params = request->params(); - for (int i = 0; i < params; 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_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()); + int params = request->params(); + for (int i = 0; i < params; 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_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()); - if (it_wifi_conf != command_map_wifi_conf.end()) - { - command_map_wifi_conf.at(param->name().c_str())(param->value().c_str()); - auto &key_it = it_wifi_conf->first; - log_i("Command %s executed", key_it.c_str()); - } - else if (it_funct != command_map_funct.end()) - { - command_map_funct.at(param->name().c_str())(); - auto &key_it_funct = it_funct->first; - log_i("Command %s executed", key_it_funct.c_str()); - } - else if (it_json != command_map_json.end()) - { - command_map_json.at(param->name().c_str())(request); - auto &key_it_json = it_json->first; - log_i("Command %s executed", key_it_json.c_str()); - } - else - { - log_i("Command not found"); - } - } - log_i("GET[%s]: %s\n", param->name().c_str(), param->value().c_str()); - } + if (it_wifi_conf != command_map_wifi_conf.end()) + { + command_map_wifi_conf.at(param->name().c_str())(param->value().c_str()); + auto &key_it = it_wifi_conf->first; + log_i("Command %s executed", key_it.c_str()); + } + else if (it_funct != command_map_funct.end()) + { + command_map_funct.at(param->name().c_str())(); + auto &key_it_funct = it_funct->first; + log_i("Command %s executed", key_it_funct.c_str()); + } + else if (it_json != command_map_json.end()) + { + command_map_json.at(param->name().c_str())(request); + auto &key_it_json = it_json->first; + log_i("Command %s executed", key_it_json.c_str()); + } + else + { + log_i("Command not found"); + } + } + 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) { -#if ENABLE_ADHOC - network->setWiFiConf(value, network->conf->ap.ssid, &*network->conf); -#else - network->setWiFiConf(value, network->conf->sta.ssid, &*network->conf); -#endif // ENABLE_ADHOC + if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + this->wifiConfig.local_WifiConfig[0].ssid = value; + else + this->wifiConfig.local_WifiConfig[1].ssid = value; + ssid_write = true; } void APIServer::setPass(const char *value) { -#if ENABLE_ADHOC - network->setWiFiConf(network->conf->ap.password, value, &*network->conf); -#else - network->setWiFiConf(value, network->conf->sta.password, &*network->conf); -#endif // ENABLE_ADHOC + if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + this->wifiConfig.local_WifiConfig[0].pass = value; + else + this->wifiConfig.local_WifiConfig[1].pass = value; + pass_write = true; } void APIServer::setChannel(const char *value) { -#if ENABLE_ADHOC - network->setWiFiConf(value, network->conf->ap.channel, &*network->conf); -#else - network->setWiFiConf(value, &network->conf->sta.channel, &*network->conf); -#endif // ENABLE_ADHOC + if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + this->wifiConfig.local_WifiConfig[0].channel = atoi(value); + else + this->wifiConfig.local_WifiConfig[1].channel = atoi(value); + 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) { - network->configManager->getDeviceConfig()->data_json = true; - api_utilities.my_delay(1L); - String temp = network->configManager->getDeviceConfig()->data_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; + network->configManager->getDeviceConfig()->data_json = true; + api_utilities.my_delay(1L); + String temp = network->configManager->getDeviceConfig()->data_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; } void APIServer::setConfigJson(AsyncWebServerRequest *request) { - network->configManager->getDeviceConfig()->config_json = true; - api_utilities.my_delay(1L); - String temp = network->configManager->getDeviceConfig()->config_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; + network->configManager->getDeviceConfig()->config_json = true; + api_utilities.my_delay(1L); + String temp = network->configManager->getDeviceConfig()->config_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; } void APIServer::setSettingsJson(AsyncWebServerRequest *request) { - network->configManager->getDeviceConfig()->settings_json = true; - api_utilities.my_delay(1L); - String temp = network->configManager->getDeviceConfig()->settings_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; + network->configManager->getDeviceConfig()->settings_json = true; + api_utilities.my_delay(1L); + String temp = network->configManager->getDeviceConfig()->settings_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; } void APIServer::rebootDevice() { - delay(20000); - ESP.restart(); + delay(20000); + ESP.restart(); } void APIServer::factoryReset() { - network->configManager->reset(); + network->configManager->reset(); } //********************************************************************************************* @@ -194,56 +217,55 @@ void APIServer::factoryReset() APIServer::API_Utilities::API_Utilities() {} -std::string -APIServer::API_Utilities::shaEncoder(std::string data) +std::string APIServer::API_Utilities::shaEncoder(std::string data) { - const char *data_c = data.c_str(); - int size = 20; - uint8_t hash[size]; - mbedtls_md_context_t ctx; - mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1; + const char *data_c = data.c_str(); + int size = 20; + uint8_t hash[size]; + mbedtls_md_context_t ctx; + mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1; - const size_t len = strlen(data_c); - mbedtls_md_init(&ctx); - mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); - mbedtls_md_starts(&ctx); - mbedtls_md_update(&ctx, (const unsigned char *)data_c, len); - mbedtls_md_finish(&ctx, hash); - mbedtls_md_free(&ctx); + const size_t len = strlen(data_c); + mbedtls_md_init(&ctx); + mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); + mbedtls_md_starts(&ctx); + mbedtls_md_update(&ctx, (const unsigned char *)data_c, len); + mbedtls_md_finish(&ctx, hash); + mbedtls_md_free(&ctx); - std::string hash_string = ""; - for (uint16_t i = 0; i < size; i++) - { - std::string hex = String(hash[i], HEX).c_str(); - if (hex.length() < 2) - { - hex = "0" + hex; - } - hash_string += hex; - } - return hash_string; + std::string hash_string = ""; + for (uint16_t i = 0; i < size; i++) + { + std::string hex = String(hash[i], HEX).c_str(); + if (hex.length() < 2) + { + hex = "0" + hex; + } + hash_string += hex; + } + return hash_string; } void APIServer::API_Utilities::notFound(AsyncWebServerRequest *request) { - try - { - log_i("%s", _networkMethodsMap[request->method()]); - } - catch (const std::exception &e) - { - log_i("UNKNOWN"); - } + try + { + log_i("%s", _networkMethodsMap[request->method()]); + } + catch (const std::exception &e) + { + log_i("UNKNOWN"); + } - log_i(" http://%s%s/\n", request->host().c_str(), request->url().c_str()); - request->send(404, "text/plain", "Not found."); + log_i(" http://%s%s/\n", request->host().c_str(), request->url().c_str()); + request->send(404, "text/plain", "Not found."); } void APIServer::API_Utilities::my_delay(volatile long delay_time) { - delay_time = delay_time * 1e6L; - for (volatile long count = delay_time; count > 0L; count--) - ; + delay_time = delay_time * 1e6L; + for (volatile long count = delay_time; count > 0L; count--) + ; } APIServer::API_Utilities api_utilities; \ No newline at end of file diff --git a/ESP/lib/src/network/webserver/webserverHandler.hpp b/ESP/lib/src/network/webserver/webserverHandler.hpp index 75673ff..d78590d 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.hpp +++ b/ESP/lib/src/network/webserver/webserverHandler.hpp @@ -21,7 +21,6 @@ #include "io/camera/cameraHandler.hpp" #include "network/WifiHandler/WifiHandler.hpp" - class APIServer { private: @@ -62,11 +61,29 @@ private: /* static const char *MIMETYPE_JPG; */ /* static const char *MIMETYPE_ICO; */ 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 local_WifiConfig; + }; + + WifiConfig wifiConfig; public: APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network); void begin(); void startAPIServer(); + void triggerWifiConfigWrite(); void findParam(AsyncWebServerRequest *request, const char *param, String &value); class API_Utilities diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 7157017..daf34a5 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -14,8 +14,11 @@ default_envs = esp32Cam ; do not change this value ; The below options are available for all environments ; The ssid and password are requried for the trackers to connect to your network!!! [wifi] -ssid="EyeTrackVR" ; your wifi network name goes here -password="test" ; Place your Wifi password here +ssid="" ; your wifi network name goes 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 OTAServerPort=3232 enableADHOC=0 ; 0 = disable, 1 = enable @@ -80,6 +83,8 @@ build_flags = -DENABLE_ADHOC=${wifi.enableADHOC} ; -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 @@ -89,6 +94,10 @@ build_flags = '-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 -DCORE_DEBUG_LEVEL=4 diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 72de9bb..45865ca 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -77,5 +77,6 @@ void loop() { ota.HandleOTAUpdate(); ledManager->displayStatus(); + apiServer->triggerWifiConfigWrite(); // serialManager->handleSerial(); } \ No newline at end of file From e90e94d5a535bd7abee666804dbcc6d031b813d3 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 15 Aug 2022 05:58:45 +0100 Subject: [PATCH 040/153] update - implement backup to ADHOC if all attempts at STA networks fail --> tries flash first --> tries hard-coded value if flash fails --> goes to adhoc if all else fails --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 7ab4d9b..f6aacd0 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -49,12 +49,10 @@ void WiFiHandler::setupWifi() { 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"); + log_e("Could not connect to any of the saved 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); + log_i("[INFO]: Attempting to connect to hardcoded network from ini file"); return; } } @@ -143,9 +141,9 @@ void WiFiHandler::iniSTA() // 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"); + this->setUpADHOC(); + log_w("Setting up adhoc mode"); + log_w("Please use adhoc mode and the app to set your WiFi credentials and reboot the device"); stateManager->setState(WiFiState_e::WiFiState_ADHOC); return; } From 162c511a1f7d543c919a5491adf3ac4f818c08f2 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 15 Aug 2022 06:30:53 +0100 Subject: [PATCH 041/153] update - add proper build_type flag for debug and release - added default value for MDNS name --- ESP/lib/src/data/config/project_config.cpp | 8 +++++++- ESP/platformio.ini | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 7e86b8f..53bddff 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -14,9 +14,15 @@ void ProjectConfig::initConfig() { begin(); this->config.device = { + "EyeTrackVR", + "", + 3232, + false, + false, + false, "", "", - 0, + "" }; this->config.camera = { diff --git a/ESP/platformio.ini b/ESP/platformio.ini index daf34a5..d26aada 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -122,6 +122,8 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git https://github.com/me-no-dev/AsyncTCP.git +build_type = debug + [env:esp32Cam] platform = ${common.platform} board = esp32cam @@ -174,6 +176,7 @@ board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} +build_type = release ; Experimental OTA Environment - do not select unless you know what you are doing [env:esp32Cam_OTA] @@ -199,6 +202,7 @@ upload_protocol = espota upload_flags = --port=3232 --auth=12345678 +build_type = release [env:wrover] platform = ${common.platform} @@ -255,6 +259,7 @@ lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} upload_port = COM6 +build_type = release ; Experimental OTA Environment - do not select unless you know what you are doing [env:wrover_OTA] @@ -280,3 +285,4 @@ upload_protocol = espota upload_flags = --port=3232 --auth=12345678 +build_type = release From 36bfcf3a3a136aee97c2ad88f21995581f6f1a19 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 15 Aug 2022 06:46:12 +0100 Subject: [PATCH 042/153] update - remove extra, unneeded params for begin statement - changed default channel to 1 from 10 --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 2 +- ESP/platformio.ini | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index f6aacd0..42e366a 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -71,7 +71,7 @@ void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) 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. - WiFi.softAP(ssid, password, channel, 0, 3); // AP mode with password + WiFi.softAP(ssid, password, channel); // AP mode with password WiFi.setTxPower(WIFI_POWER_11dBm); stateManager->setState(WiFiState_e::WiFiState_ADHOC); diff --git a/ESP/platformio.ini b/ESP/platformio.ini index d26aada..8e5a12c 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -16,13 +16,13 @@ default_envs = esp32Cam ; do not change this value [wifi] ssid="" ; your wifi network name goes here password="" ; your wifi network password goes here -channel=10 ; wifi channel +channel=1 ; 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 OTAServerPort=3232 enableADHOC=0 ; 0 = disable, 1 = enable -adhocChannel=10 ; channel to use for adhoc network +adhocChannel=1 ; channel to use for adhoc network ; DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING [pinoutsESPCAM] From 687be8afb786d7bb52ff190057bff3ac571f3427 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 20 Aug 2022 14:02:10 +0100 Subject: [PATCH 043/153] large update - Fully reworked the API code, wifi handler, and serial manager - Added proper APIServer --- ESP/backup/WifiHandler/WifiHandler.hpp | 22 ++ ESP/backup/WifiHandler/wifiHandler.cpp | 151 ++++++++ .../webserver/webserverHandler.cpp | 4 +- .../webserver/webserverHandler.hpp | 1 + ESP/lib/src/data/config/project_config.cpp | 20 +- ESP/lib/src/data/config/project_config.hpp | 6 +- ESP/lib/src/data/utilities/Observer.hpp | 6 +- ESP/lib/src/data/utilities/helpers.cpp | 80 +++++ ESP/lib/src/data/utilities/helpers.hpp | 10 + ESP/lib/src/data/utilities/makeunique.hpp | 10 +- .../src/data/utilities/network_utilities.cpp | 54 +++ .../src/data/utilities/network_utilities.hpp | 16 + .../SerialManager2/serialmanager.cpp | 340 ------------------ .../SerialManager2/serialmanager.hpp | 158 -------- .../src/io/SerialManager/serialmanager.cpp | 171 ++++----- .../src/io/SerialManager/serialmanager.hpp | 49 ++- .../src/network/WifiHandler/WifiHandler.hpp | 14 +- .../src/network/WifiHandler/wifiHandler.cpp | 85 +++-- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 297 +++++++++++++++ ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 84 +++++ .../network/api/utilities/apiUtilities.cpp | 116 ++++++ .../network/api/utilities/apiUtilities.hpp | 98 +++++ ESP/lib/src/network/api/webserverHandler.cpp | 115 ++++++ ESP/lib/src/network/api/webserverHandler.hpp | 26 ++ ESP/lib/src/network/mDNS/MDNSManager.cpp | 4 +- ESP/lib/src/network/mDNS/MDNSManager.hpp | 1 + ESP/lib/src/network/stream/streamServer.hpp | 4 + ESP/platformio.ini | 47 +-- ESP/src/main.cpp | 58 +-- 29 files changed, 1322 insertions(+), 725 deletions(-) create mode 100644 ESP/backup/WifiHandler/WifiHandler.hpp create mode 100644 ESP/backup/WifiHandler/wifiHandler.cpp rename ESP/{lib/src/network => backup}/webserver/webserverHandler.cpp (98%) rename ESP/{lib/src/network => backup}/webserver/webserverHandler.hpp (99%) create mode 100644 ESP/lib/src/data/utilities/helpers.cpp create mode 100644 ESP/lib/src/data/utilities/helpers.hpp create mode 100644 ESP/lib/src/data/utilities/network_utilities.cpp create mode 100644 ESP/lib/src/data/utilities/network_utilities.hpp delete mode 100644 ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp delete mode 100644 ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp create mode 100644 ESP/lib/src/network/api/baseAPI/baseAPI.cpp create mode 100644 ESP/lib/src/network/api/baseAPI/baseAPI.hpp create mode 100644 ESP/lib/src/network/api/utilities/apiUtilities.cpp create mode 100644 ESP/lib/src/network/api/utilities/apiUtilities.hpp create mode 100644 ESP/lib/src/network/api/webserverHandler.cpp create mode 100644 ESP/lib/src/network/api/webserverHandler.hpp diff --git a/ESP/backup/WifiHandler/WifiHandler.hpp b/ESP/backup/WifiHandler/WifiHandler.hpp new file mode 100644 index 0000000..fd77729 --- /dev/null +++ b/ESP/backup/WifiHandler/WifiHandler.hpp @@ -0,0 +1,22 @@ +#pragma once +#ifndef WIFIHANDLER_HPP +#define WIFIHANDLER_HPP +#include +#include +#include "data/StateManager/StateManager.hpp" +#include "data/config/project_config.hpp" + +class WiFiHandler +{ +public: + WiFiHandler(ProjectConfig *configManager, StateManager *stateManager); + virtual ~WiFiHandler(); + void setupWifi(); + ProjectConfig *configManager; + StateManager *stateManager; +private: + void setUpADHOC(); + void adhoc(const char *ssid, const char *password, uint8_t channel); + void iniSTA(); +}; +#endif // WIFIHANDLER_HPP diff --git a/ESP/backup/WifiHandler/wifiHandler.cpp b/ESP/backup/WifiHandler/wifiHandler.cpp new file mode 100644 index 0000000..42e366a --- /dev/null +++ b/ESP/backup/WifiHandler/wifiHandler.cpp @@ -0,0 +1,151 @@ +#include "WifiHandler.hpp" +#include + +WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager) : configManager(configManager), + stateManager(stateManager) {} + +WiFiHandler::~WiFiHandler() {} + +void WiFiHandler::setupWifi() +{ + if (ENABLE_ADHOC || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + { + this->setUpADHOC(); + return; + } + log_i("Initializing connection to wifi"); + stateManager->setState(WiFiState_e::WiFiState_Connecting); + + std::vector *networks = configManager->getWifiConfigs(); + int connection_timeout = 30000; // 30 seconds + + int count = 0; + unsigned long currentMillis = millis(); + unsigned long _previousMillis = currentMillis; + + for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) + { + log_i("Trying to connect to the %s network", networkIterator->ssid); + + WiFi.begin(networkIterator->ssid.c_str(), networkIterator->password.c_str()); + count++; + + if (!WiFi.isConnected()) + log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid); + else + { + log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->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) && count >= networks->size()) + { + 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 saved networks, check your Wifi credentials"); + stateManager->setState(WiFiState_e::WiFiState_Error); + this->iniSTA(); + log_i("[INFO]: Attempting to connect to hardcoded network from ini file"); + return; + } + } + } +} + +void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) +{ + log_i("[INFO]: Setting Access Point...\n"); + + log_i("[INFO]: Configuring access point...\n"); + WiFi.mode(WIFI_AP); + + Serial.printf("\r\nStarting AP. \r\nAP IP address: "); + IPAddress IP = WiFi.softAPIP(); + 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. + WiFi.softAP(ssid, password, channel); // AP mode with password + + WiFi.setTxPower(WIFI_POWER_11dBm); + stateManager->setState(WiFiState_e::WiFiState_ADHOC); +} + +/* +* * +*/ +void WiFiHandler::setUpADHOC() +{ + log_i("[INFO]: Setting Access Point...\n"); + size_t ssidLen = strlen(configManager->getAPWifiConfig()->ssid.c_str()); + size_t passwordLen = strlen(configManager->getAPWifiConfig()->password.c_str()); + char ssid[ssidLen + 1]; + char password[passwordLen + 1]; + uint8_t channel = configManager->getAPWifiConfig()->channel; + if (ssidLen > 0 || passwordLen > 0) + { + 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; + } + + this->adhoc(ssid, password, 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); +} + +void WiFiHandler::iniSTA() +{ + log_i("[INFO]: Setting up station...\n"); + int connection_timeout = 30000; // 30 seconds + unsigned long currentMillis = millis(); + unsigned long _previousMillis = currentMillis; + + log_i("Trying to connect to the %s network", WIFI_SSID); + + WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); + + 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->setUpADHOC(); + log_w("Setting up adhoc mode"); + log_w("Please use adhoc mode and the app to set your WiFi credentials and reboot the device"); + stateManager->setState(WiFiState_e::WiFiState_ADHOC); + return; + } + } +} \ No newline at end of file diff --git a/ESP/lib/src/network/webserver/webserverHandler.cpp b/ESP/backup/webserver/webserverHandler.cpp similarity index 98% rename from ESP/lib/src/network/webserver/webserverHandler.cpp rename to ESP/backup/webserver/webserverHandler.cpp index f313df0..b41c5f1 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.cpp +++ b/ESP/backup/webserver/webserverHandler.cpp @@ -166,9 +166,9 @@ void APIServer::triggerWifiConfigWrite() 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); + 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, wifiConfig.local_WifiConfig[0].adhoc, 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->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, wifiConfig.local_WifiConfig[1].adhoc, true); network->configManager->save(); } } diff --git a/ESP/lib/src/network/webserver/webserverHandler.hpp b/ESP/backup/webserver/webserverHandler.hpp similarity index 99% rename from ESP/lib/src/network/webserver/webserverHandler.hpp rename to ESP/backup/webserver/webserverHandler.hpp index d78590d..9473028 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.hpp +++ b/ESP/backup/webserver/webserverHandler.hpp @@ -70,6 +70,7 @@ private: std::string ssid; std::string pass; uint8_t channel; + bool adhoc; }; struct WifiConfig diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 53bddff..e0eca06 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -22,8 +22,7 @@ void ProjectConfig::initConfig() false, "", "", - "" - }; + ""}; this->config.camera = { 0, @@ -38,6 +37,7 @@ void ProjectConfig::initConfig() "", "", 0, + false, }, }; @@ -45,6 +45,7 @@ void ProjectConfig::initConfig() "", "", 0, + false, }; } @@ -82,8 +83,9 @@ void ProjectConfig::load() 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); + bool networks_adhoc_success = this->read(buff, this->config.networks[i].adhoc); - network_info_success = networks_name_success && networks_ssid_success && networks_password_success && networks_channel_success; + network_info_success = networks_name_success && networks_ssid_success && networks_password_success && networks_channel_success && networks_adhoc_success; } if (!device_success || !camera_success || !network_info_success) @@ -123,7 +125,13 @@ void ProjectConfig::save() this->write(buff, this->config.networks[i].password); snprintf(buff, sizeof(buff), "%d_channel", i); this->write(buff, this->config.networks[i].channel); + this->write(buff, this->config.networks[i].adhoc); + } + + log_i("Project config saved and system is rebooting"); + delay(20000); + ESP.restart(); } void ProjectConfig::reset() @@ -167,7 +175,7 @@ void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t } } -void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, const char *password, uint8_t *channel, bool shouldNotify) +void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify) { WiFiConfig_t *networkToUpdate = nullptr; @@ -185,6 +193,7 @@ void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, con (char *)ssid, (char *)password, *channel, + adhoc, }, }; if (shouldNotify) @@ -193,12 +202,13 @@ void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, con log_d("Updating wifi config"); } -void ProjectConfig::setAPWifiConfig(const char *ssid, const char *password, uint8_t *channel, bool shouldNotify) +void ProjectConfig::setAPWifiConfig(const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify) { this->config.ap_network = { (char *)ssid, (char *)password, *channel, + adhoc, }; log_d("Updating access point config"); diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 20bd0fd..0b87401 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -45,6 +45,7 @@ public: std::string ssid; std::string password; uint8_t channel; + bool adhoc; }; struct AP_WiFiConfig_t @@ -52,6 +53,7 @@ public: std::string ssid; std::string password; uint8_t channel; + bool adhoc; }; struct TrackerConfig_t @@ -69,8 +71,8 @@ public: 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 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); + void setWifiConfig(const char *networkName, const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify); + void setAPWifiConfig(const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify); private: const char *configFileName; diff --git a/ESP/lib/src/data/utilities/Observer.hpp b/ESP/lib/src/data/utilities/Observer.hpp index 07fddd1..a3a0c99 100644 --- a/ESP/lib/src/data/utilities/Observer.hpp +++ b/ESP/lib/src/data/utilities/Observer.hpp @@ -1,4 +1,6 @@ #pragma once +#ifndef OBSERVER_HPP +#define OBSERVER_HPP #include namespace ObserverEvent @@ -44,4 +46,6 @@ public: ++iterator; } } -}; \ No newline at end of file +}; + +#endif // !OBSERVER_HPP \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/helpers.cpp b/ESP/lib/src/data/utilities/helpers.cpp new file mode 100644 index 0000000..927f3e9 --- /dev/null +++ b/ESP/lib/src/data/utilities/helpers.cpp @@ -0,0 +1,80 @@ +#include "helpers.hpp" + +char *Helpers::itoa(int value, char *result, int base) +{ + // check that the base if valid + if (base < 2 || base > 36) + { + *result = '\0'; + return result; + } + + char *ptr = result, *ptr1 = result, tmp_char; + int tmp_value; + + do + { + tmp_value = value; + value /= base; + *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35 + (tmp_value - value * base)]; + } while (value); + + // Apply negative sign + if (tmp_value < 0) + *ptr++ = '-'; + *ptr-- = '\0'; + while (ptr1 < ptr) + { + tmp_char = *ptr; + *ptr-- = *ptr1; + *ptr1++ = tmp_char; + } + return result; +} + +void split(std::string str, std::string splitBy, std::vector &tokens) +{ + /* Store the original string in the array, so we can loop the rest + * of the algorithm. */ + tokens.push_back(str); + + // Store the split index in a 'size_t' (unsigned integer) type. + size_t splitAt; + // Store the size of what we're splicing out. + size_t splitLen = splitBy.size(); + // Create a string for temporarily storing the fragment we're processing. + std::string frag; + // Loop infinitely - break is internal. + while (true) + { + /* Store the last string in the vector, which is the only logical + * candidate for processing. */ + frag = tokens.back(); + /* The index where the split is. */ + splitAt = frag.find(splitBy); + // If we didn't find a new split point... + if (splitAt == std::string::npos) + { + // Break the loop and (implicitly) return. + break; + } + /* Put everything from the left side of the split where the string + * being processed used to be. */ + tokens.back() = frag.substr(0, splitAt); + /* Push everything from the right side of the split to the next empty + * index in the vector. */ + tokens.push_back(frag.substr(splitAt + splitLen, frag.size() - (splitAt + splitLen))); + } +} + +std::vector Helpers::split(const std::string &s, char delimiter) +{ + std::vector parts; + std::string part; + std::istringstream tokenStream(s); + while (std::getline(tokenStream, part, delimiter)) + { + parts.push_back(part); + } + return parts; +} \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/helpers.hpp b/ESP/lib/src/data/utilities/helpers.hpp new file mode 100644 index 0000000..058d73c --- /dev/null +++ b/ESP/lib/src/data/utilities/helpers.hpp @@ -0,0 +1,10 @@ +#include +#include +#include + +namespace Helpers +{ + char *itoa(int value, char *result, int base); + void split(std::string str, std::string splitBy, std::vector &tokens); + std::vector split(const std::string &s, char delimiter); +} \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/makeunique.hpp b/ESP/lib/src/data/utilities/makeunique.hpp index 9ffca8d..f5d250c 100644 --- a/ESP/lib/src/data/utilities/makeunique.hpp +++ b/ESP/lib/src/data/utilities/makeunique.hpp @@ -1,12 +1,10 @@ #pragma once +#ifndef MAKE_UNIQUE_HPP +#define MAKE_UNIQUE_HPP #include #include #include #include -namespace Utilities -{ - -} /** * @brief override the STD namespace to add make_unique function @@ -53,4 +51,6 @@ namespace std template typename _Unique_if::_Known_bound make_unique(Args &&...) = delete; -} \ No newline at end of file +} + +#endif // !MAKE_UNIQUE_HPP \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/network_utilities.cpp b/ESP/lib/src/data/utilities/network_utilities.cpp new file mode 100644 index 0000000..f8467cc --- /dev/null +++ b/ESP/lib/src/data/utilities/network_utilities.cpp @@ -0,0 +1,54 @@ +#include "network_utilities.hpp" + +void Network_Utilities::SetupWifiScan() +{ + // Set WiFi to station mode and disconnect from an AP if it was previously connected + WiFi.mode(WIFI_STA); + WiFi.disconnect(); // Disconnect from the access point if connected before + delay(100); + + Serial.println("Setup done"); +} + +bool Network_Utilities::LoopWifiScan() +{ + // WiFi.scanNetworks will return the number of networks found + log_i("[INFO]: Beginning WiFi Scanner"); + int networks = WiFi.scanNetworks(); + log_i("[INFO]: scan done"); + + log_i("%d networks found", networks); + for (int i = networks; i--;) + { + // Print SSID and RSSI for each network found + //! Add method here to interface with the API and forward the scanned networks to the API + log_i("%d: %s (%d) %s\n", i - 1, WiFi.SSID(i), WiFi.RSSI(i), (WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*"); + my_delay(0.02L); // delay 20ms + } + + // Wait a bit before scanning again + delay(5000); + return (networks > 0); +} + +// Take measurements of the Wi-Fi strength and return the average result. +int Network_Utilities::getStrength(int points) // TODO: add to JSON doc +{ + int32_t rssi = 0, averageRSSI = 0; + + for (int i = 0; i < points; i++) + { + rssi += WiFi.RSSI(); + delay(20); + } + + averageRSSI = rssi / points; + return averageRSSI; +} + +void Network_Utilities::my_delay(volatile long delay_time) +{ + delay_time = delay_time * 1e6L; + for (volatile long count = delay_time; count > 0L; count--) + ; +} \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/network_utilities.hpp b/ESP/lib/src/data/utilities/network_utilities.hpp new file mode 100644 index 0000000..bcb2fe4 --- /dev/null +++ b/ESP/lib/src/data/utilities/network_utilities.hpp @@ -0,0 +1,16 @@ +#pragma once +#ifndef UTILITIES_hpp +#define UTILITIES_hpp +#include +#include "network/wifihandler/WifiHandler.hpp" +#include +namespace Network_Utilities +{ + bool LoopWifiScan(); + void SetupWifiScan(); + void my_delay(volatile long delay_time); + int CheckWifiState(); + int getStrength(int points); + String generateDeviceID(); +} +#endif // !UTILITIES_hpp \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp deleted file mode 100644 index f47fb80..0000000 --- a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.cpp +++ /dev/null @@ -1,340 +0,0 @@ -#include "serialmanager.hpp" - -#if SERIAL_CMD_DBG_EN - -static void printHex(Stream &port, uint8_t *data, uint8_t length); -static void printHex(Stream &port, uint16_t *data, uint8_t length); - -void printHex(Stream &port, uint8_t *data, uint8_t length) // prints 8-bit data in hex with leading zeroes -{ - for (int i = 0; i < length; i++) - { - // port.print("0x"); - if (data[i] < 0x10) - { - port.print("0"); - } - port.print(data[i], HEX); - port.print(" "); - } -} - -void printHex(Stream &port, uint16_t *data, uint8_t length) // prints 16-bit data in hex with leading zeroes -{ - for (int i = 0; i < length; i++) - { - // port.print("0x"); - uint8_t MSB = byte(data[i] >> 8); - uint8_t LSB = byte(data[i]); - if (MSB < 0x10) - { - port.print("0"); - } - port.print(MSB, HEX); - if (LSB < 0x10) - { - port.print("0"); - } - port.print(LSB, HEX); - port.print(" "); - } -} -#endif - -SerialManager2::SerialManager2() : userErrorHandler(NULL), _serial(NULL), ManagerCount(0), _serialManager2Active(false), newData(false) -{ - clear(); -} - -void SerialManager2::begin(Stream &serialPort) -{ - /* Save Serial Port configurations */ - _serial = &serialPort; -} - -// This checks the Serial stream for characters, and assembles them into a buffer. -// When the terminator character (defined by EOL constant) is seen, it starts parsing the -// buffer for a prefix Manager, and calls handlers setup by addManager() method -void SerialManager2::loop(unsigned long timeout) -{ - log_d("Listening to serial"); - _serialManager2Active = true; - Serial.setTimeout(timeout); - static bool recvInProgress = false; - char startDelimiter = '<'; //! we need to decide on a delimiter for the start of a message - char endDelimiter = '>'; //! we need to decide on a delimiter for the end of a message - char c; - while ((available() > 0) && !newData) - { - c = read(); - if (recvInProgress) - { - if (c != endDelimiter) - { - bufferHandler(c); - } - else - { - recvInProgress = false; - newData = true; - } - } - else - { - if (c == startDelimiter) - { - recvInProgress = true; - } - } - } - delay(timeout); - _serialManager2Active = false; -} - -/* Clear buffer */ -void SerialManager2::clear(void) -{ - memset(buffer, 0, SERIAL_CMD_BUFF_LEN); - pBuff = buffer; -} - -/* - * Send error response - * NOTE: Will execute user defined callback (defined using addDefault method), - * if no user defined callback it will send the ERROR message (sendERROR method). - */ -void SerialManager2::error(void) -{ - if (NULL != userErrorHandler) - { - (*userErrorHandler)(); - } - - clear(); /* Clear buffer */ -} - -// Retrieve the next token ("word" or "argument") from the Manager buffer. -// returns a NULL if no more tokens exist. -char *SerialManager2::next(void) -{ - return strtok_r(NULL, delimiters, &last); -} - -void SerialManager2::bufferHandler(char c) -{ - int len; - char *lastChars = NULL; - - if ((pBuff - buffer) > (SERIAL_CMD_BUFF_LEN - 2)) /* Check buffer overflow */ - { - error(); /* Send ERROR, Buffer overflow */ - } - - *pBuff++ = c; /* Put character into buffer */ - *pBuff = '\0'; /* Always null terminate strings */ - - if ((pBuff - buffer) > 2) /* Check buffer length */ - { - /* Get EOL */ - len = strlen(buffer); - lastChars = buffer + len - 2; - - /* Compare last chars to EOL */ - if (0 == strcmp(lastChars, EOL)) - { - - // *lastChars = '\0'; /* Replace EOL with NULL terminator */ - -#if (SERIAL_CMD_DBG_EN == 1) - log_d("Received: %s", buffer); -#endif - - if (ManagerHandler()) - { - clear(); - } - else - { - error(); - } - } - } -} - -/* Return true if match was found */ -bool SerialManager2::ManagerHandler(void) -{ - int i; - bool ret = false; - char *token = NULL; - char *offset = NULL; - char userInput[SERIAL_CMD_BUFF_LEN]; - - memcpy(userInput, buffer, SERIAL_CMD_BUFF_LEN); - - /* Search for Manager at start of buffer */ - token = strtok_r(buffer, delimiters, &last); - -#if SERIAL_CMD_DBG_EN - print("User input: ("); - printHex(Serial, (uint8_t *)userInput, SERIAL_CMD_BUFF_LEN); - println(")"); -#endif - - if (NULL != token) - { - -#if SERIAL_CMD_DBG_EN - log_d("Token: %s", token); -#endif - - for (i = 0; (i < ManagerCount); i++) - { - -#if SERIAL_CMD_DBG_EN - print("Case: \""); - print(ManagerList[i].Manager); - print("\" "); -#endif - - /* Compare the token against the list of known Managers */ - if (0 == strncmp(token, ManagerList[i].Manager, SERIAL_CMD_BUFF_LEN)) - { - -#if SERIAL_CMD_DBG_EN - log_d("- Match Found!"); -#endif - offset = (char *)(userInput + strlen(token)); - - /* Check for query Manager */ - if (0 == strncmp(offset, "=?", 2)) - { -#if SERIAL_CMD_DBG_EN - log_d("Run test callback"); -#endif - if (NULL != *ManagerList[i].test) - { - /* Run test callback */ - (*ManagerList[i].test)(); - } - } - else if (('?' == *offset) && (NULL != *ManagerList[i].read)) - { -#if SERIAL_CMD_DBG_EN - log_d("Run read callback"); -#endif - /* Run read callback */ - (*ManagerList[i].read)(); - } - else if (('=' == *offset) && (NULL != *ManagerList[i].write)) - { -#if (SERIAL_CMD_DBG_EN == 1) - log_d("Run write callback"); -#endif - /* Run write callback */ - (*ManagerList[i].write)(); - } - else if (NULL != *ManagerList[i].execute) - { -#if SERIAL_CMD_DBG_EN - log_d("Run execute callback"); -#endif - /* Run execute callback */ - (*ManagerList[i].execute)(); - } - else - { - log_e("INVALID"); - ret = false; - break; - } - - ret = true; - break; - } - -#if SERIAL_CMD_DBG_EN - else - { - log_e("- Not a match!"); - } -#endif - } - } - - return ret; -} - -// Adds a "Manager" and a handler function to the list of available Managers. -// This is used for matching a found token in the buffer, and gives the pointer -// to the handler function to deal with it. -void SerialManager2::addManager(char *cmd, void (*test)(), void (*read)(), void (*write)(), void (*execute)()) -{ - -#if SERIAL_CMD_DBG_EN - print("["); - print(ManagerCount); - print("] New Manager: "); - println(cmd); -#endif - - ManagerList = (serialManager2Callback *)realloc(ManagerList, (ManagerCount + 1) * sizeof(serialManager2Callback)); - strncpy(ManagerList[ManagerCount].Manager, cmd, SERIAL_CMD_BUFF_LEN); - ManagerList[ManagerCount].test = test; - ManagerList[ManagerCount].read = read; - ManagerList[ManagerCount].write = write; - ManagerList[ManagerCount].execute = execute; - ManagerCount++; -} - -/* Optional user-defined function to call when an error occurs, default is NULL */ -void SerialManager2::addError(void (*callback)()) -{ - userErrorHandler = callback; -} - -int SerialManager2::available() -{ - int bytes = 0; - if (NULL != _serial) - { - bytes = _serial->available(); - } - return bytes; -} - -int SerialManager2::read() -{ - int bytes = 0; - if (NULL != _serial) - { - bytes = _serial->read(); - } - return bytes; -} - -int SerialManager2::peek() -{ - int bytes = 0; - if (NULL != _serial) - { - bytes = _serial->peek(); - } - return bytes; -} - -void SerialManager2::flush() -{ - if (NULL != _serial) - { - _serial->flush(); - } -} - -size_t SerialManager2::write(uint8_t x) -{ - (void)x; - return 0; -} - -SerialManager2 serialManager2; \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp b/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp deleted file mode 100644 index 1ca6b76..0000000 --- a/ESP/lib/src/io/SerialManager/SerialManager2/serialmanager.hpp +++ /dev/null @@ -1,158 +0,0 @@ -#ifndef SERIALMANAGER2_HPP -#define SERIALMANAGER2_HPP -#include -#include - -#define SERIAL_CMD_DBG_EN 0 -#define SERIAL_CMD_BUFF_LEN 100 /* Max length for each serial Manager */ - -/* Data structure to hold Manager/Handler function key-value pairs */ -typedef struct -{ - char Manager[SERIAL_CMD_BUFF_LEN]; - void (*test)(); - void (*read)(); - void (*write)(); - void (*execute)(); -} serialManager2Callback; - -/* - * Token delimiters (setup '=', query '?', separator ',') - */ -const char delimiters[] = "=,?\r\n"; - -/* - * End Of Line: - * = - * = - */ -const char EOL[] = "\r\n"; - -class SerialManager2 : public Stream -{ -public: - SerialManager2(); - virtual ~SerialManager2(); - - /** - * Start connection to serial port - * - * @param serialPort - Serial port to listen for Managers - * @param baud - Baud rate - */ - void begin(Stream &serialPort); - - /** - * Execute this function inside Arduino's loop function. - */ - void loop(unsigned long timeout); - - /** - * Add a new Manager - * - * @param cmd - Manager to listen - * @param test - Test Manager callback - * @param read - Read Manager callback - * @param write - Write Manager callback - * @param execute - Execute Manager callback - */ - void addManager(char *cmd, void (*test)(), void (*read)(), void (*write)(), void (*execute)()); - - /** - * Add a read-only Manager - * - * @param cmd - Manager to listen - * @param callback - Read Manager callback - */ - void addTestManager(char *cmd, void (*callback)()) - { - addManager(cmd, callback, NULL, NULL, NULL); - } - - /** - * Add a read-only Manager - * - * @param cmd - Manager to listen - * @param callback - Read Manager callback - */ - void addReadManager(char *cmd, void (*callback)()) - { - addManager(cmd, NULL, callback, NULL, NULL); - } - - /** - * Add a write-only Manager - * - * @param cmd - Manager to listen - * @param callback - Write Manager callback - */ - void addWriteManager(char *cmd, void (*callback)()) - { - addManager(cmd, NULL, NULL, callback, NULL); - } - - /** - * Add a execute-only Manager - * - * @param cmd - Manager to listen - * @param callback - Execute Manager callback - */ - void addExecuteManager(char *cmd, void (*callback)()) - { - addManager(cmd, NULL, NULL, NULL, callback); - } - - /** - * Default function to execute when no match is found - * - * @param callback - Function to execute when Manager is received - */ - void addError(void (*callback)()); - - /* Return next argument found in Manager buffer */ - char *next(void); - - /* variable to track state of newdata in the buffer */ - bool newData; - - /* - * Virtual methods to match Stream class - */ - size_t write(uint8_t); - int available(); - int read(); - int peek(); - void flush(); - - -private: - /* Setup serial port */ - void setup(unsigned long baud); - /* Sets the Manager buffer to all '\0' (nulls) */ - void clear(void); - /* Send error message and clear buffer */ - void error(); - /* Process buffer */ - void bufferHandler(char c); - /* Check for Manager instances and handle callbacks and queries */ - bool ManagerHandler(void); - /* User defined error handler */ - void (*userErrorHandler)(); - /* Serial Port handler */ - Stream *_serial; - /* Actual definition for Manager/handler array */ - serialManager2Callback *ManagerList; - /* Buffer of stored characters while waiting for terminator character */ - char buffer[SERIAL_CMD_BUFF_LEN]; - /* Pointer to buffer, used to store data in the buffer */ - char *pBuff; - /* State variable used by strtok_r during processing */ - char *last; - /* Number of available Managers registered by new() */ - uint8_t ManagerCount; - - bool _serialManager2Active; - -}; -extern SerialManager2 serialManager2; -#endif // SerialManager2_h \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp index 0df354d..0657960 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -1,126 +1,83 @@ #include "serialmanager.hpp" +std::unordered_map SerialManager::command_map = { + {"", NO_INPUT}, + {"device_config", DEVICE_CONFIG}, + {"camera_config", CAMERA_CONFIG}, + {"wifi_config", WIFI_CONFIG}}; + +void readStr(const char *inStr); + SerialManager::SerialManager(ProjectConfig *projectConfig) : projectConfig(projectConfig), - serialManagerActive(false), - newData(false), - tempBuffer{0}, - serialBuffer{0}, - device_config_name{0}, - device_config_OTAPassword{0}, - device_config_OTAPort(0), - camera_config_vflip{0}, - camera_config_href{0}, - camera_config_framesize{0}, - camera_config_quality{0}, - wifi_config_name{0}, - wifi_config_ssid{0}, - wifi_config_password{0}, - wifi_config_channel(0) {} + serReader(std::make_unique()) +{ +} SerialManager::~SerialManager() {} -void SerialManager::listenToSerial(unsigned long timeout) +void SerialManager::begin() { - log_d("Listening to serial"); - serialManagerActive = true; - Serial.setTimeout(timeout); - - static bool recvInProgress = false; - static uint8_t index = 0; // index - char startDelimiter = '<'; //! we need to decide on a delimiter for the start of a message - char endDelimiter = '>'; //! we need to decide on a delimiter for the end of a message - char receivedChar; // to test for received data on the line - - while ((Serial.available() > 0) && !newData) - { - serialManagerActive = true; - receivedChar = Serial.read(); - if (recvInProgress) - { - if (receivedChar != endDelimiter) - { - serialBuffer[index] = receivedChar; - index++; - if (index >= sizeof(serialBuffer)) - { - log_e("Serial buffer overflow"); - index = 0; - recvInProgress = false; - } - } - else - { - recvInProgress = false; - serialBuffer[index] = '\0'; - index = 0; - newData = true; - } - } - else - { - if (receivedChar == startDelimiter) - { - recvInProgress = true; - } - } - } - serialManagerActive = false; + serReader->setCallback(readStr); } -void SerialManager::parseData() +void readStr(const char *inStr) { - log_d("Parsing data"); - char *strtokIndx; // this is used by strtok() as an index + Serial.print("command : "); + Serial.println(inStr); + std::string raw = inStr; + std::vector command; + Helpers::split(raw, ":", command); //! gives us the command and the value - "command:value" + std::vector command_value; + Helpers::split(command[1], ",", command_value); //! gives us the command and the value - "command:value" - //! Parse the data - //* Device Config *// - strtokIndx = strtok(tempBuffer, ","); // get the first part - strcpy(device_config_name, strtokIndx); // copy it to buffer + //! The following line uses strdup to return a char* to lwrCase + char *lwr_case = strdup(command[0].c_str()); + lwrCase(lwr_case); //! converts the command to lowercase - strtokIndx = strtok(NULL, ","); // get the second part - strcpy(device_config_OTAPassword, strtokIndx); - - strtokIndx = strtok(NULL, ","); - device_config_OTAPort = atoi(strtokIndx); - - //* Camera Config *// - strtokIndx = strtok(NULL, ","); - camera_config_vflip = atoi(strtokIndx); - - strtokIndx = strtok(NULL, ","); - camera_config_framesize = atoi(strtokIndx); - - strtokIndx = strtok(NULL, ","); - camera_config_href = atoi(strtokIndx); - - strtokIndx = strtok(NULL, ","); - camera_config_quality = atoi(strtokIndx); - - //* Wifi Config *// - strtokIndx = strtok(tempBuffer, ","); - strcpy(wifi_config_name, strtokIndx); - - strtokIndx = strtok(NULL, ","); - strcpy(wifi_config_ssid, strtokIndx); - - strtokIndx = strtok(NULL, ","); - strcpy(wifi_config_password, strtokIndx); - - strtokIndx = strtok(NULL, ","); - wifi_config_channel = atoi(strtokIndx); + switch (SerialManager::command_map[lwr_case]) + { + case SerialManager::NO_INPUT: + break; + case SerialManager::DEVICE_CONFIG: + break; + case SerialManager::CAMERA_CONFIG: + break; + case SerialManager::WIFI_CONFIG: + break; + } } void SerialManager::handleSerial() { - listenToSerial(30000L); // test for serial input every 30 seconds - if (newData) // input received + if (Serial.available() > 0) { - strcpy(tempBuffer, serialBuffer); // this temporary copy is necessary to protect the original data because strtok() used in parseData() replaces the commas with \0 - 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->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, &wifi_config_channel, true); // set the values in the project config - projectConfig->save(); // save the config to the EEPROM - newData = false; // reset new data + delay(10); + std::string raw = Serial.readStringUntil('#').c_str(); + // String s = "{\"a\":\"b\"}"; + + while (Serial.available() > 0) + { + Serial.read(); + } + log_d("Received Serial Data: %s", raw.c_str()); + + DeserializationError error = deserializeJson(jsonDoc, raw); + if (error) + { + log_e("deserializeJson() failed: %s", error.c_str()); + return; + } + + const char *device_config_name = jsonDoc["device_config_name"]; + const char *device_config_OTAPassword = jsonDoc["device_config_OTAPassword"]; + const char *device_config_OTAPort = jsonDoc["device_config_OTAPort"]; + const char *camera_config_vflip = jsonDoc["camera_config_vflip"]; + const char *camera_config_href = jsonDoc["camera_config_href"]; + const char *camera_config_framesize = jsonDoc["camera_config_framesize"]; + const char *camera_config_quality = jsonDoc["camera_config_quality"]; + const char *wifi_config_name = jsonDoc["wifi_config_name"]; + const char *wifi_config_ssid = jsonDoc["wifi_config_ssid"]; + const char *wifi_config_password = jsonDoc["wifi_config_password"]; + const char *wifi_config_channel = jsonDoc["wifi_config_channel"]; } } \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/serialmanager.hpp b/ESP/lib/src/io/SerialManager/serialmanager.hpp index c949c84..4b2c430 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.hpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.hpp @@ -2,8 +2,16 @@ #ifndef SERIAL_MANAGER_HPP #define SERIAL_MANAGER_HPP #include +#include +#include +#include +#include +#include +#include #include "data/config/project_config.hpp" +#include "data/utilities/makeunique.hpp" +#include "data/utilities/helpers.hpp" class SerialManager { @@ -11,36 +19,25 @@ public: SerialManager(ProjectConfig *projectConfig); virtual ~SerialManager(); + void begin(); void handleSerial(); - bool serialManagerActive; + friend void readStr(const char *inStr); - /* Device Config Variables */ - char device_config_name[32]; - char device_config_OTAPassword[100]; - int device_config_OTAPort; - - /* Camera Config Variables */ - uint8_t camera_config_vflip; - uint8_t camera_config_framesize; - uint8_t camera_config_href; - uint8_t camera_config_quality; - - /* Wifi Config Variables */ - char wifi_config_name[32]; - char wifi_config_ssid[100]; - char wifi_config_password[100]; - uint8_t wifi_config_channel; - -private: - - void listenToSerial(unsigned long timeout); - void parseData(); - - char serialBuffer[1000]; //! Need to find the appropriate size for this - count the maximum possible size of a message - char tempBuffer[sizeof(serialBuffer) / sizeof(serialBuffer[0])]; - bool newData; +protected: ProjectConfig *projectConfig; + std::unique_ptr serReader; + + enum Serial_Commands + { + NO_INPUT, + DEVICE_CONFIG, + CAMERA_CONFIG, + WIFI_CONFIG + }; + + static std::unordered_map command_map; + StaticJsonDocument<1024> jsonDoc; }; #endif // SERIAL_MANAGER_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index fd77729..a90ccfa 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -2,6 +2,7 @@ #ifndef WIFIHANDLER_HPP #define WIFIHANDLER_HPP #include +#include #include #include "data/StateManager/StateManager.hpp" #include "data/config/project_config.hpp" @@ -9,14 +10,25 @@ class WiFiHandler { public: - WiFiHandler(ProjectConfig *configManager, StateManager *stateManager); + WiFiHandler(ProjectConfig *configManager, StateManager *stateManager, + std::string ssid, + std::string password, + uint8_t channel); virtual ~WiFiHandler(); void setupWifi(); + ProjectConfig *configManager; StateManager *stateManager; + + bool _enable_adhoc; + private: void setUpADHOC(); void adhoc(const char *ssid, const char *password, uint8_t channel); void iniSTA(); + + std::string ssid; + std::string password; + uint8_t channel; }; #endif // WIFIHANDLER_HPP diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 42e366a..b93879e 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -1,22 +1,41 @@ #include "WifiHandler.hpp" #include -WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager) : configManager(configManager), - stateManager(stateManager) {} +WiFiHandler::WiFiHandler(ProjectConfig *configManager, + StateManager *stateManager, + std::string ssid, + std::string password, + uint8_t channel) : configManager(configManager), + stateManager(stateManager), + ssid(ssid), + password(password), + channel(channel), + _enable_adhoc(false) {} WiFiHandler::~WiFiHandler() {} void WiFiHandler::setupWifi() { - if (ENABLE_ADHOC || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + if (this->_enable_adhoc || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { this->setUpADHOC(); return; } + log_i("Initializing connection to wifi"); stateManager->setState(WiFiState_e::WiFiState_Connecting); std::vector *networks = configManager->getWifiConfigs(); + + // check size of networks + if (networks->size() == 0) + { + log_e("No networks found in config"); + this->iniSTA(); + stateManager->setState(WiFiState_e::WiFiState_Error); + return; + } + int connection_timeout = 30000; // 30 seconds int count = 0; @@ -26,19 +45,9 @@ void WiFiHandler::setupWifi() for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) { log_i("Trying to connect to the %s network", networkIterator->ssid); - WiFi.begin(networkIterator->ssid.c_str(), networkIterator->password.c_str()); count++; - if (!WiFi.isConnected()) - log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid); - else - { - log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid); - stateManager->setState(WiFiState_e::WiFiState_Connected); - return; - } - while (WiFi.status() != WL_CONNECTED) { stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting); @@ -50,12 +59,20 @@ void WiFiHandler::setupWifi() 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 saved networks, check your Wifi credentials"); - stateManager->setState(WiFiState_e::WiFiState_Error); + stateManager->setState(WiFiState_e::WiFiState_Disconnected); + log_i("[INFO]: Attempting to connect to hardcoded network"); this->iniSTA(); - log_i("[INFO]: Attempting to connect to hardcoded network from ini file"); return; } } + if (!WiFi.isConnected()) + log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid); + else + { + log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid); + stateManager->setState(WiFiState_e::WiFiState_Connected); + return; + } } } @@ -72,14 +89,14 @@ void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) // You can remove the password parameter if you want the AP to be open. WiFi.softAP(ssid, password, channel); // AP mode with password - WiFi.setTxPower(WIFI_POWER_11dBm); + stateManager->setState(WiFiState_e::WiFiState_ADHOC); } /* -* * -*/ + * * + */ void WiFiHandler::setUpADHOC() { log_i("[INFO]: Setting Access Point...\n"); @@ -96,9 +113,9 @@ void WiFiHandler::setUpADHOC() } else { - strcpy(ssid, WIFI_AP_SSID); - strcpy(password, WIFI_AP_PASSWORD); - channel = ADHOC_CHANNEL; + strcpy(ssid, "OpenIris"); + strcpy(password, "12345678"); + channel = 1; } this->adhoc(ssid, password, channel); @@ -116,18 +133,17 @@ void WiFiHandler::iniSTA() unsigned long currentMillis = millis(); unsigned long _previousMillis = currentMillis; - log_i("Trying to connect to the %s network", WIFI_SSID); + log_i("Trying to connect to the %s network", this->ssid.c_str()); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); - - if (!WiFi.isConnected()) - log_i("\n\rCould not connect to %s, please try another network\n\r", WIFI_SSID); - else + // check size of networks + if (this->ssid.size() == 0) { - log_i("\n\rSuccessfully connected to %s\n\r", WIFI_SSID); - stateManager->setState(WiFiState_e::WiFiState_Connected); + log_e("No networks passed into the constructor"); + this->setUpADHOC(); + stateManager->setState(WiFiState_e::WiFiState_Error); return; } + WiFi.begin(this->ssid.c_str(), this->password.c_str(), this->channel); while (WiFi.status() != WL_CONNECTED) { @@ -148,4 +164,13 @@ void WiFiHandler::iniSTA() return; } } -} \ No newline at end of file + + if (!WiFi.isConnected()) + log_i("\n\rCould not connect to %s, please try another network\n\r", this->ssid.c_str()); + else + { + log_i("\n\rSuccessfully connected to %s\n\r", this->ssid.c_str()); + stateManager->setState(WiFiState_e::WiFiState_Connected); + return; + } +} diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp new file mode 100644 index 0000000..b60bc24 --- /dev/null +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -0,0 +1,297 @@ +#include "baseAPI.hpp" + +BaseAPI::BaseAPI(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url) : API_Utilities(CONTROL_PORT, + network, + camera, + stateManager, + api_url) {} + +BaseAPI::~BaseAPI() {} + +void BaseAPI::begin() +{ + this->setupServer(); + //! i have changed this to use lambdas instead of std::bind to avoid the overhead. Lambdas are always more preferable. + server->on("/", 0b00000001, [&](AsyncWebServerRequest *request) + { request->send(200); }); + + // preflight cors check + server->on("/", 0b01000000, [&](AsyncWebServerRequest *request) + { + AsyncWebServerResponse* response = request->beginResponse(204); + response->addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS"); + response->addHeader("Access-Control-Allow-Headers", "Accept, Content-Type, Authorization"); + response->addHeader("Access-Control-Allow-Credentials", "true"); + request->send(response); }); + + DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); + + // std::bind(&BaseAPI::API_Utilities::notFound, &api_utilities, std::placeholders::_1); + server->onNotFound([&](AsyncWebServerRequest *request) + { notFound(request); }); +} + +void BaseAPI::setupServer() +{ + localWifiConfig = { + .ssid = "", + .pass = "", + .channel = 0, + .adhoc = false, + }; + + localAPWifiConfig = { + .ssid = "", + .pass = "", + .channel = 0, + .adhoc = false, + }; +} + +//********************************************************************************************* +//! Command Functions +//********************************************************************************************* +void BaseAPI::setWiFi(AsyncWebServerRequest *request) +{ + switch (_networkMethodsMap_enum[request->method()]) + { + case POST: + { + int params = request->params(); + for (int i = 0; i < params; i++) + { + AsyncWebParameter *param = request->getParam(i); + if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + { + localAPWifiConfig.ssid = param->value().c_str(); + localAPWifiConfig.pass = param->value().c_str(); + localAPWifiConfig.channel = atoi(param->value().c_str()); + localAPWifiConfig.adhoc = atoi(param->value().c_str()); + } + else + { + localWifiConfig.ssid = param->value().c_str(); + localWifiConfig.pass = param->value().c_str(); + localWifiConfig.channel = atoi(param->value().c_str()); + localWifiConfig.adhoc = atoi(param->value().c_str()); + } + } + ssid_write = true; + pass_write = true; + channel_write = true; + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); + break; + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + request->redirect("/"); + break; + } + } +} + +/** + * * 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 BaseAPI::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->setAPWifiConfig(localAPWifiConfig.ssid.c_str(), localAPWifiConfig.pass.c_str(), &localAPWifiConfig.channel, localAPWifiConfig.adhoc, true); + else + network->configManager->setWifiConfig(localWifiConfig.ssid.c_str(), localWifiConfig.ssid.c_str(), localWifiConfig.pass.c_str(), &localWifiConfig.channel, localAPWifiConfig.adhoc, true); + network->configManager->save(); + } +} + +void BaseAPI::handleJson(AsyncWebServerRequest *request) +{ + std::string type = request->pathArg(0).c_str(); + switch (_networkMethodsMap_enum[request->method()]) + { + case POST: + { + switch (json_TypesMap.at(type)) + { + case DATA: + { + break; + } + case SETTINGS: + { + break; + } + case CONFIG: + { + break; + } + default: + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + break; + } + case GET: + { + switch (json_TypesMap.at(type)) + { + case DATA: + { + network->configManager->getDeviceConfig()->data_json = true; + Network_Utilities::my_delay(1L); + String temp = network->configManager->getDeviceConfig()->data_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; + break; + } + case SETTINGS: + { + network->configManager->getDeviceConfig()->config_json = true; + Network_Utilities::my_delay(1L); + String temp = network->configManager->getDeviceConfig()->config_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; + break; + } + case CONFIG: + { + network->configManager->getDeviceConfig()->settings_json = true; + Network_Utilities::my_delay(1L); + String temp = network->configManager->getDeviceConfig()->settings_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; + break; + } + default: + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + + break; + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + } +} + +void BaseAPI::rebootDevice(AsyncWebServerRequest *request) +{ + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + delay(20000); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Rebooting Device\"}"); + ESP.restart(); + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + } +} + +void BaseAPI::factoryReset(AsyncWebServerRequest *request) +{ + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + log_d("Factory Reset"); + network->configManager->reset(); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Factory Reset\"}"); + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + } +} + +/** + * @brief Remove a command handler from the API + * + * @param request + * @return \c void + */ +void BaseAPI::deleteRoute(AsyncWebServerRequest *request) +{ + log_i("Request: %s", request->url().c_str()); + int params = request->params(); + auto it_map = route_map.find(request->pathArg(0).c_str()); + log_i("Request: %s", request->pathArg(0).c_str()); + if (it_map != route_map.end()) + { + auto it = it_map->second.find(request->pathArg(1).c_str()); + if (it != it_map->second.end()) + { + switch (_networkMethodsMap_enum[request->method()]) + { + case DELETE: + { + route_map.erase(it_map->first); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"OK - Command handler removed\"}"); + break; + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + } + } + else + { + request->send(404); + } + } + else + { + request->send(404); + } +} + +//********************************************************************************************* +//! Camera Command Functions +//********************************************************************************************* + +void BaseAPI::setCamera(AsyncWebServerRequest *request) +{ + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + int params = request->params(); + for (int i = 0; i < params; i++) + { + AsyncWebParameter *param = request->getParam(i); + camera->setCameraResolution((framesize_t)atoi(param->value().c_str())); + camera->setVFlip(atoi(param->value().c_str())); + camera->setHFlip(atoi(param->value().c_str())); + } + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera Settings have been set.\"}"); + break; + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + request->redirect("/"); + break; + } + } +} \ No newline at end of file diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp new file mode 100644 index 0000000..d8aab17 --- /dev/null +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -0,0 +1,84 @@ +#ifndef BASEAPI_HPP +#define BASEAPI_HPP +#include "network/wifihandler/wifiHandler.hpp" +#include "network/api/utilities/apiUtilities.hpp" + +class BaseAPI : public API_Utilities +{ +protected: + struct LocalWifiConfig + { + std::string ssid; + std::string pass; + uint8_t channel; + bool adhoc; + }; + + LocalWifiConfig localWifiConfig; + + struct LocalAPWifiConfig + { + std::string ssid; + std::string pass; + uint8_t channel; + }; + + LocalWifiConfig localAPWifiConfig; + + enum JSON_TYPES + { + CONFIG, + SETTINGS, + DATA, + STATUS, + COMMANDS, + WIFI, + WIFIAP, + }; + + std::unordered_map json_TypesMap = { + {"config", CONFIG}, + {"settings", SETTINGS}, + {"data", DATA}, + {"status", STATUS}, + {"commands", COMMANDS}, + {"wifi", WIFI}, + {"wifiap", WIFIAP}, + }; + +protected: + /* Commands */ + void setWiFi(AsyncWebServerRequest *request); + void handleJson(AsyncWebServerRequest *request); + void factoryReset(AsyncWebServerRequest *request); + void rebootDevice(AsyncWebServerRequest *request); + void deleteRoute(AsyncWebServerRequest *request); + + /* Camera Handler */ + void setCamera(AsyncWebServerRequest *request); + + using call_back_function_t = void (BaseAPI::*)(AsyncWebServerRequest *); + typedef call_back_function_t (*call_back_function_ptr)(AsyncWebServerRequest *); + + /* Route Command types */ + using route_method = void (BaseAPI::*)(AsyncWebServerRequest *); + // typedef void (*callback)(AsyncWebServerRequest *); + typedef std::unordered_map route_t; + typedef std::unordered_map route_map_t; + + route_t routes; + route_map_t route_map; + +public: + BaseAPI(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url); + virtual ~BaseAPI(); + virtual void begin(); + virtual void setupServer(); + void triggerWifiConfigWrite(); +}; + +#endif // BASEAPI_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp new file mode 100644 index 0000000..8237183 --- /dev/null +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -0,0 +1,116 @@ +#include "apiUtilities.hpp" + +//! These have to be called before the constructor of the class because they are static +//! C++ 11 does not have inline variables, sadly. So we have to do this. +const char *API_Utilities::MIMETYPE_HTML{"text/html"}; +// const char *BaseAPI::MIMETYPE_CSS{"text/css"}; +// const char *BaseAPI::MIMETYPE_JS{"application/javascript"}; +// const char *BaseAPI::MIMETYPE_PNG{"image/png"}; +// const char *BaseAPI::MIMETYPE_JPG{"image/jpeg"}; +// const char *BaseAPI::MIMETYPE_ICO{"image/x-icon"}; +const char *API_Utilities::MIMETYPE_JSON{"application/json"}; + +bool API_Utilities::ssid_write = false; +bool API_Utilities::pass_write = false; +bool API_Utilities::channel_write = false; + +//********************************************************************************************* +//! API Utilities +//********************************************************************************************* + +API_Utilities::API_Utilities(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url) : server(new AsyncWebServer(CONTROL_PORT)), + stateManager(stateManager), + network(network), + camera(camera), + api_url(api_url) {} +API_Utilities::~API_Utilities() {} +std::string API_Utilities::shaEncoder(std::string data) +{ + const char *data_c = data.c_str(); + int size = 64; + uint8_t hash[size]; + mbedtls_md_context_t ctx; + mbedtls_md_type_t md_type = MBEDTLS_MD_SHA512; + + const size_t len = strlen(data_c); + mbedtls_md_init(&ctx); + mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); + mbedtls_md_starts(&ctx); + mbedtls_md_update(&ctx, (const unsigned char *)data_c, len); + mbedtls_md_finish(&ctx, hash); + mbedtls_md_free(&ctx); + + std::string hash_string = ""; + for (uint16_t i = 0; i < size; i++) + { + std::string hex = String(hash[i], HEX).c_str(); + if (hex.length() < 2) + { + hex = "0" + hex; + } + hash_string += hex; + } + return hash_string; +} + +void API_Utilities::notFound(AsyncWebServerRequest *request) const +{ + if (_networkMethodsMap.find(request->method()) != _networkMethodsMap.end()) + { + log_i("%s: http://%s%s/\n", _networkMethodsMap.at(request->method()).c_str(), request->host().c_str(), request->url().c_str()); + char buffer[100]; + snprintf(buffer, sizeof(buffer), "Request %s Not found: %s", _networkMethodsMap.at(request->method()).c_str(), request->url().c_str()); + request->send(404, "text/plain", buffer); + } + else + { + request->send(404, "text/plain", "Request Not found using unknown method"); + } +} + +// Read File from SPIFFS +/* String API_Utilities::readFile(fs::FS &fs, std::string path) +{ + log_i("Reading file: %s\r\n", path.c_str()); + + File file = fs.open(path.c_str()); + if (!file || file.isDirectory()) + { + log_e("[INFO]: Failed to open file for reading"); + return String(); + } + + String fileContent; + while (file.available()) + { + fileContent = file.readStringUntil('\n'); + break; + } + return fileContent; +} + +// Write file to SPIFFS +void API_Utilities::writeFile(fs::FS &fs, std::string path, std::string message) +{ + log_i("[Writing File]: Writing file: %s\r\n", path); + Network_Utilities::my_delay(0.1L); + + File file = fs.open(path.c_str(), FILE_WRITE); + if (!file) + { + log_i("[Writing File]: failed to open file for writing"); + return; + } + if (file.print(message.c_str())) + { + log_i("[Writing File]: file written"); + } + else + { + log_i("[Writing File]: file write failed"); + } +} */ diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp new file mode 100644 index 0000000..4df0ea1 --- /dev/null +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -0,0 +1,98 @@ +#ifndef APIUTILITIES_HPP +#define APIUTILITIES_HPP + +#include +#include + + +#define WEBSERVER_H + +/* #define XHTTP_GET 0b00000001; +#define XHTTP_POST 0b00000010; +#define XHTTP_DELETE 0b00000100; +#define XHTTP_PUT 0b00001000; +#define XHTTP_PATCH 0b00010000; +#define XHTTP_HEAD 0b00100000; +#define XHTTP_OPTIONS 0b01000000; +#define XHTTP_ANY 0b01111111; */ + +#define HTTP_ANY 0b01111111 +#define HTTP_GET 0b00000001 + +#include +#include +#include "mbedtls/md.h" +#include "data/utilities/network_utilities.hpp" +#include "data/StateManager/StateManager.hpp" +#include "io/camera/cameraHandler.hpp" + +class API_Utilities +{ +public: + API_Utilities(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url); + virtual ~API_Utilities(); + +protected: + void notFound(AsyncWebServerRequest *request) const; + /* String readFile(fs::FS &fs, std::string path); + void writeFile(fs::FS &fs, std::string path, std::string message); */ + std::string shaEncoder(std::string data); + std::unordered_map _networkMethodsMap = { + {0, "NULL"}, + {0b00000001, "GET"}, + {0b00000010, "POST"}, + {0b00001000, "PUT"}, + {0b00000100, "DELETE"}, + {0b00010000, "PATCH"}, + {0b01000000, "OPTIONS"}, + }; + + enum RequestMethods + { + NULL_METHOD, + GET, + POST, + PUT, + DELETE, + PATCH, + OPTIONS, + }; + + std::unordered_map _networkMethodsMap_enum = { + {0, NULL_METHOD}, + {0b00000001, GET}, + {0b00000010, POST}, + {0b00001000, PUT}, + {0b00000100, DELETE}, + {0b00010000, PATCH}, + {0b01000000, OPTIONS}, + }; + +protected: + AsyncWebServer *server; + WiFiHandler *network; + CameraHandler *camera; + StateManager *stateManager; + typedef std::unordered_map networkMethodsMap_t; + +protected: + std::string api_url; + + static bool ssid_write; + static bool pass_write; + static bool channel_write; + + static const char *MIMETYPE_HTML; + /* static const char *MIMETYPE_CSS; */ + /* static const char *MIMETYPE_JS; */ + /* static const char *MIMETYPE_PNG; */ + /* static const char *MIMETYPE_JPG; */ + /* static const char *MIMETYPE_ICO; */ + static const char *MIMETYPE_JSON; +}; + +#endif // APIUTILITIES_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp new file mode 100644 index 0000000..cd7f076 --- /dev/null +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -0,0 +1,115 @@ +#include "webserverHandler.hpp" + +//********************************************************************************************* +//! API Server +//********************************************************************************************* + +APIServer::APIServer(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url) : BaseAPI(CONTROL_PORT, + network, + camera, + stateManager, + api_url) {} + +APIServer::~APIServer() {} + +void APIServer::begin() +{ + log_d("Initializing REST API"); + this->setupServer(); + BaseAPI::begin(); + + char buffer[1000]; + snprintf(buffer, sizeof(buffer), "^\\%s\\/([a-zA-Z0-9]+)\\/command\\/([a-zA-Z0-9]+)$", this->api_url.c_str()); + log_d("API URL: %s", buffer); + server->on(buffer, 0b01111111, [&](AsyncWebServerRequest *request) + { handleRequest(request); }); + + server->begin(); +} + +void APIServer::setupServer() +{ + // Set case NULL_METHOD routes + routes.emplace("wifi", &APIServer::setWiFi); + routes.emplace("reset_config", &APIServer::factoryReset); + routes.emplace("reboot_device", &APIServer::rebootDevice); + routes.emplace("set_json", &APIServer::handleJson); + routes.emplace("set_camera", &APIServer::setCamera); + routes.emplace("delete_route", &APIServer::deleteRoute); + + routeHandler("builtin", routes); // add new map to the route map +} + +void APIServer::findParam(AsyncWebServerRequest *request, const char *param, String &value) +{ + if (request->hasParam(param)) + { + value = request->getParam(param)->value(); + } +} + +/** + * @brief Add a command handler to the API + * + * @param index + * @param funct + * @return \c vector a list of the indexes of the command handlers + */ +std::vector APIServer::routeHandler(std::string index, route_t route) +{ + route_map.emplace(index, route); + std::vector indexes; + indexes.reserve(route.size()); + + for (const auto &key : route) + { + indexes.push_back(key.first); + } + + return indexes; +} + +void APIServer::handleRequest(AsyncWebServerRequest *request) +{ + // Get the route + log_i("Request: %s", request->url().c_str()); + int params = request->params(); + auto it_map = route_map.find(request->pathArg(0).c_str()); + log_i("Request: %s", request->pathArg(0).c_str()); + auto it_method = it_map->second.find(request->pathArg(1).c_str()); + log_i("Request: %s", request->pathArg(1).c_str()); + + for (int i = 0; i < params; i++) + { + AsyncWebParameter *param = request->getParam(i); + { + { + if (it_map != route_map.end()) + { + if (it_method != it_map->second.end()) + { + (*this.*(it_method->second))(request); + } + else + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Command\"}"); + request->redirect("/"); + return; + } + } + else + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Map Index\"}"); + request->redirect("/"); + return; + } + } + log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); + } + } + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Command executed\"}"); +} diff --git a/ESP/lib/src/network/api/webserverHandler.hpp b/ESP/lib/src/network/api/webserverHandler.hpp new file mode 100644 index 0000000..8e2324b --- /dev/null +++ b/ESP/lib/src/network/api/webserverHandler.hpp @@ -0,0 +1,26 @@ +#pragma once +#ifndef XWEBSERVERHANDLER_HPP +#define XWEBSERVERHANDLER_HPP + +#include "network/api/baseAPI/baseAPI.hpp" + +class APIServer : public BaseAPI +{ +public: + APIServer(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler* camera, + StateManager *stateManager, + std::string api_url); + + virtual ~APIServer(); + void begin(); + void setupServer(); + + void findParam(AsyncWebServerRequest *request, const char *param, String &value); + void updateCommandHandlers(); + std::vector routeHandler(std::string index, route_t route); + void handleRequest(AsyncWebServerRequest *request); + +}; +#endif // WEBSERVERHANDLER_HPP diff --git a/ESP/lib/src/network/mDNS/MDNSManager.cpp b/ESP/lib/src/network/mDNS/MDNSManager.cpp index 3c261ac..85f2133 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.cpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.cpp @@ -8,7 +8,9 @@ void MDNSHandler::startMDNS() { stateManager->setState(MDNSState_e::MDNSState_Starting); MDNS.addService("openIrisTracker", "tcp", 80); - MDNS.addServiceTxt("openIrisTracker", "tcp", "stream_port", String(80)); + char port[20]; + //!Add service needs leading _ on ESP32 implementation for some reason (according to the docs) + MDNS.addServiceTxt("_openIrisTracker", "_tcp", "_stream_port", (const char*)Helpers::itoa(80, port, 10)); //! convert int to const char* using a very efficient implemenation of itoa log_i("MDNS initialized!"); stateManager->setState(MDNSState_e::MDNSState_Started); } diff --git a/ESP/lib/src/network/mDNS/MDNSManager.hpp b/ESP/lib/src/network/mDNS/MDNSManager.hpp index 40c0d27..865afbc 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.hpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.hpp @@ -2,6 +2,7 @@ #include #include "data/StateManager/StateManager.hpp" #include "data/utilities/Observer.hpp" +#include "data/utilities/helpers.hpp" #include "data/config/project_config.hpp" class MDNSHandler : public IObserver diff --git a/ESP/lib/src/network/stream/streamServer.hpp b/ESP/lib/src/network/stream/streamServer.hpp index 7e89bd7..a936334 100644 --- a/ESP/lib/src/network/stream/streamServer.hpp +++ b/ESP/lib/src/network/stream/streamServer.hpp @@ -1,4 +1,6 @@ #pragma once +#ifndef STREAM_SERVER_HPP +#define STREAM_SERVER_HPP #define PART_BOUNDARY "123456789000000000000987654321" #include #include "esp_camera.h" @@ -19,3 +21,5 @@ public: StreamServer(int STREAM_PORT) : STREAM_SERVER_PORT(STREAM_PORT) {} int startStreamServer(); }; + +#endif // STREAM_SERVER_HPP diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 8e5a12c..36b9ec5 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -14,14 +14,14 @@ default_envs = esp32Cam ; do not change this value ; The below options are available for all environments ; The ssid and password are requried for the trackers to connect to your network!!! [wifi] -ssid="" ; your wifi network name goes here -password="" ; your wifi network password goes here +ssid="LoveHouse2G" ; your wifi network name goes here +password="vxwby2Gwtswp" ; your wifi network password goes here channel=1 ; 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 OTAServerPort=3232 -enableADHOC=0 ; 0 = disable, 1 = enable +enableADHOC=1 ; 0 = disable, 1 = enable adhocChannel=1 ; channel to use for adhoc network ; DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING @@ -104,6 +104,8 @@ build_flags = -DBOARD_HAS_PSRAM + -DASYNCWEBSERVER_REGEX ; add regex support to AsyncWebServer + -mfix-esp32-psram-cache-issue ;-I include @@ -118,9 +120,11 @@ upload_speed = 921600 release_version = 0.0.1 ; increase this value every release build lib_deps = esp32-camera + leftcoast/LC_baseTools@^1.5 https://github.com/ZanzyTHEbar/EasyPreferencesLibrary.git https://github.com/me-no-dev/ESPAsyncWebServer.git https://github.com/me-no-dev/AsyncTCP.git + https://github.com/bblanchon/ArduinoJson.git build_type = debug @@ -132,26 +136,25 @@ monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} monitor_filters = ${common.monitor_filters} -build_flags = - ${common.build_flags} +build_flags = ${common.build_flags} - ; CAMERA PINOUT DEFINITIONS - -DPWDN_GPIO_NUM=${pinoutsESPCAM.PWDN_GPIO_NUM} ; Set the PWDN pin - -DRESET_GPIO_NUM=${pinoutsESPCAM.RESET_GPIO_NUM} ; Set the RESET pin - -DXCLK_GPIO_NUM=${pinoutsESPCAM.XCLK_GPIO_NUM} ; Set the XCLK pin - -DSIOD_GPIO_NUM=${pinoutsESPCAM.SIOD_GPIO_NUM} ; Set the SIOD pin - -DSIOC_GPIO_NUM=${pinoutsESPCAM.SIOC_GPIO_NUM} ; Set the SIOC pin - -DY9_GPIO_NUM=${pinoutsESPCAM.Y9_GPIO_NUM} ; Set the Y9 pin - -DY8_GPIO_NUM=${pinoutsESPCAM.Y8_GPIO_NUM} ; Set the Y8 pin - -DY7_GPIO_NUM=${pinoutsESPCAM.Y7_GPIO_NUM} ; Set the Y7 pin - -DY6_GPIO_NUM=${pinoutsESPCAM.Y6_GPIO_NUM} ; Set the Y6 pin - -DY5_GPIO_NUM=${pinoutsESPCAM.Y5_GPIO_NUM} ; Set the Y5 pin - -DY4_GPIO_NUM=${pinoutsESPCAM.Y4_GPIO_NUM} ; Set the Y4 pin - -DY3_GPIO_NUM=${pinoutsESPCAM.Y3_GPIO_NUM} ; Set the Y3 pin - -DY2_GPIO_NUM=${pinoutsESPCAM.Y2_GPIO_NUM} ; Set the Y2 pin - -DVSYNC_GPIO_NUM=${pinoutsESPCAM.VSYNC_GPIO_NUM} ; Set the VSYNC pin - -DHREF_GPIO_NUM=${pinoutsESPCAM.HREF_GPIO_NUM} ; Set the HREF pin - -DPCLK_GPIO_NUM=${pinoutsESPCAM.PCLK_GPIO_NUM} ; Set the PCLK pin + ; CAMERA PINOUT DEFINITIONS + -DPWDN_GPIO_NUM=${pinoutsESPCAM.PWDN_GPIO_NUM} ; Set the PWDN pin + -DRESET_GPIO_NUM=${pinoutsESPCAM.RESET_GPIO_NUM} ; Set the RESET pin + -DXCLK_GPIO_NUM=${pinoutsESPCAM.XCLK_GPIO_NUM} ; Set the XCLK pin + -DSIOD_GPIO_NUM=${pinoutsESPCAM.SIOD_GPIO_NUM} ; Set the SIOD pin + -DSIOC_GPIO_NUM=${pinoutsESPCAM.SIOC_GPIO_NUM} ; Set the SIOC pin + -DY9_GPIO_NUM=${pinoutsESPCAM.Y9_GPIO_NUM} ; Set the Y9 pin + -DY8_GPIO_NUM=${pinoutsESPCAM.Y8_GPIO_NUM} ; Set the Y8 pin + -DY7_GPIO_NUM=${pinoutsESPCAM.Y7_GPIO_NUM} ; Set the Y7 pin + -DY6_GPIO_NUM=${pinoutsESPCAM.Y6_GPIO_NUM} ; Set the Y6 pin + -DY5_GPIO_NUM=${pinoutsESPCAM.Y5_GPIO_NUM} ; Set the Y5 pin + -DY4_GPIO_NUM=${pinoutsESPCAM.Y4_GPIO_NUM} ; Set the Y4 pin + -DY3_GPIO_NUM=${pinoutsESPCAM.Y3_GPIO_NUM} ; Set the Y3 pin + -DY2_GPIO_NUM=${pinoutsESPCAM.Y2_GPIO_NUM} ; Set the Y2 pin + -DVSYNC_GPIO_NUM=${pinoutsESPCAM.VSYNC_GPIO_NUM} ; Set the VSYNC pin + -DHREF_GPIO_NUM=${pinoutsESPCAM.HREF_GPIO_NUM} ; Set the HREF pin + -DPCLK_GPIO_NUM=${pinoutsESPCAM.PCLK_GPIO_NUM} ; Set the PCLK pin build_unflags = ${common.build_unflags} board_build.partitions = ${common.board_build.partitions} diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 45865ca..717e7de 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -5,41 +5,49 @@ #include #include #include -#include +#include #include -#include // Basic Serial Manager -//#include // Advanced Serial MAnager //! Finish this to update the serial manager +//#include // Basic Serial Manager +//#include -uint8_t STREAM_SERVER_PORT = 80; -uint8_t CONTROL_SERVER_PORT = 81; +int STREAM_SERVER_PORT = 80; +int CONTROL_SERVER_PORT = 81; // Create smart pointers to the various classes that will be used in the program to make sure that they are deleted when the program ends // This is done to make sure that the memory is freed when the program ends and we are not left with dangling pointers to memory that is no longer in use // Make unique is a templated function that takes a class and returns a unique pointer to that class - // it is used to create a unique pointer to a class and ensure exception safety -std::unique_ptr deviceConfig = std::make_unique(); -OTA ota(&*deviceConfig); -std::unique_ptr serialManager = std::make_unique(&*deviceConfig); -std::unique_ptr wifiHandler = std::make_unique(&*deviceConfig, &wifiStateManager); -std::unique_ptr ledManager = std::make_unique(33); -std::shared_ptr cameraHandler = std::make_shared(&*deviceConfig); //! Create a shared pointer to the camera handler -std::unique_ptr apiServer = std::make_unique(CONTROL_SERVER_PORT, &*cameraHandler, &*wifiHandler); //! Dereference the shared pointer to get the address of the camera handler -std::unique_ptr mdnsHandler = std::make_unique(&mdnsStateManager, &*deviceConfig); -std::unique_ptr streamServer = std::make_unique(STREAM_SERVER_PORT); +ProjectConfig deviceConfig; +OTA ota(&deviceConfig); +LEDManager ledManager(33); +CameraHandler cameraHandler(&deviceConfig); +//SerialManager serialManager(&deviceConfig); +WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, 1); +//APIServer apiServer(CONTROL_SERVER_PORT, &wifiHandler, &cameraHandler, &wifiStateManager, "/control"); +MDNSHandler mdnsHandler(&mdnsStateManager, &deviceConfig); +StreamServer streamServer(STREAM_SERVER_PORT); void setup() { Serial.begin(115200); Serial.setDebugOutput(true); - ledManager->begin(); - deviceConfig->initConfig(); - deviceConfig->load(); - cameraHandler->setupCamera(); + ledManager.begin(); + deviceConfig.initConfig(); + deviceConfig.load(); + cameraHandler.setupCamera(); - wifiHandler->setupWifi(); - mdnsHandler->startMDNS(); + /* auto localConfig = deviceConfig.getAPWifiConfig(); + if (localConfig->adhoc == true) + { + + } */ + + wifiHandler._enable_adhoc = ENABLE_ADHOC; + + wifiHandler.setupWifi(); + mdnsHandler.startMDNS(); switch (wifiStateManager.getCurrentState()) { @@ -56,8 +64,8 @@ void setup() } case WiFiState_e::WiFiState_Connected: { - apiServer->startAPIServer(); - streamServer->startStreamServer(); + //apiServer.begin(); + streamServer.startStreamServer(); log_d("[SETUP]: Starting Stream Server"); break; } @@ -76,7 +84,7 @@ void setup() void loop() { ota.HandleOTAUpdate(); - ledManager->displayStatus(); - apiServer->triggerWifiConfigWrite(); - // serialManager->handleSerial(); + ledManager.displayStatus(); + //apiServer.triggerWifiConfigWrite(); + // serialManager.handleSerial(); } \ No newline at end of file From 78cc161e45bcbedbd6f8c417a2fbbdcb9a9bfeeb Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 20 Aug 2022 14:14:58 +0100 Subject: [PATCH 044/153] minor update - Changed formatting from 2 spaces to 4 for indents --- ESP/lib/src/data/config/project_config.cpp | 303 ++++++------ ESP/lib/src/data/config/project_config.hpp | 116 ++--- ESP/lib/src/io/LEDManager/LEDManager.cpp | 34 +- ESP/lib/src/io/LEDManager/LEDManager.hpp | 18 +- .../src/io/SerialManager/serialmanager.cpp | 110 ++--- .../src/io/SerialManager/serialmanager.hpp | 32 +- ESP/lib/src/io/camera/cameraHandler.cpp | 190 ++++---- ESP/lib/src/io/camera/cameraHandler.hpp | 21 +- .../src/network/WifiHandler/WifiHandler.hpp | 30 +- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 458 +++++++++--------- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 120 ++--- .../network/api/utilities/apiUtilities.cpp | 144 +++--- .../network/api/utilities/apiUtilities.hpp | 109 +++-- ESP/lib/src/network/api/webserverHandler.hpp | 25 +- ESP/lib/src/network/mDNS/MDNSManager.cpp | 42 +- ESP/lib/src/network/mDNS/MDNSManager.hpp | 10 +- ESP/lib/src/network/stream/streamServer.cpp | 154 +++--- ESP/lib/src/network/stream/streamServer.hpp | 10 +- ESP/src/main.cpp | 17 +- 19 files changed, 967 insertions(+), 976 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index e0eca06..e2448ab 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -12,132 +12,131 @@ ProjectConfig::~ProjectConfig() {} */ void ProjectConfig::initConfig() { - begin(); - this->config.device = { - "EyeTrackVR", - "", - 3232, - false, - false, - false, - "", - "", - ""}; + begin(); + this->config.device = { + "EyeTrackVR", + "", + 3232, + false, + false, + false, + "", + "", + ""}; - this->config.camera = { - 0, - 0, - 0, - 0, - }; + this->config.camera = { + 0, + 0, + 0, + 0, + }; - this->config.networks = { - { - "", - "", - "", - 0, - false, - }, - }; + this->config.networks = { + { + "", + "", + "", + 0, + false, + }, + }; - this->config.ap_network = { - "", - "", - 0, - false, - }; + this->config.ap_network = { + "", + "", + 0, + false, + }; } void ProjectConfig::load() { - log_d("Loading project config"); - if (this->_already_loaded) - { - log_w("Project config already loaded"); - return; - } + log_d("Loading project config"); + if (this->_already_loaded) + { + log_w("Project config already loaded"); + return; + } - bool device_name_success = this->read("device_name", this->config.device.name); - bool device_otapassword_success = this->read("ota_pass", this->config.device.OTAPassword); - bool device_otaport_success = this->read("ota_port", this->config.device.OTAPort); + bool device_name_success = this->read("device_name", this->config.device.name); + bool device_otapassword_success = this->read("ota_pass", this->config.device.OTAPassword); + 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 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_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 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); - bool networks_adhoc_success = this->read(buff, this->config.networks[i].adhoc); + 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); + bool networks_adhoc_success = this->read(buff, this->config.networks[i].adhoc); - network_info_success = networks_name_success && networks_ssid_success && networks_password_success && networks_channel_success && networks_adhoc_success; - } + network_info_success = networks_name_success && networks_ssid_success && networks_password_success && networks_channel_success && networks_adhoc_success; + } - if (!device_success || !camera_success || !network_info_success) - { - log_e("Failed to load project config - Generating config and restarting"); - save(); - delay(1000); - ESP.restart(); - return; - } + if (!device_success || !camera_success || !network_info_success) + { + log_e("Failed to load project config - Generating config and restarting"); + save(); + delay(1000); + ESP.restart(); + return; + } - this->_already_loaded = true; - this->notify(ObserverEvent::configLoaded); + this->_already_loaded = true; + this->notify(ObserverEvent::configLoaded); } void ProjectConfig::save() { - log_d("Saving project config"); + log_d("Saving project config"); - this->write("device_name", this->config.device.name); - this->write("ota_pass", this->config.device.OTAPassword); - this->write("ota_port", this->config.device.OTAPort); + this->write("device_name", this->config.device.name); + 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); + 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); - this->write(buff, this->config.networks[i].adhoc); + 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); + this->write(buff, this->config.networks[i].adhoc); + } - } - - log_i("Project config saved and system is rebooting"); - delay(20000); - ESP.restart(); + log_i("Project config saved and system is rebooting"); + delay(20000); + ESP.restart(); } void ProjectConfig::reset() { - log_w("Resetting project config"); - this->clear(); + log_w("Resetting project config"); + this->clear(); } //********************************************************************************************************************** @@ -147,73 +146,73 @@ void ProjectConfig::reset() //********************************************************************************************************************** void ProjectConfig::setDeviceConfig(const char *name, const char *OTAPassword, int *OTAPort, bool shouldNotify) { - log_d("Updating device config"); - this->config.device = { - (char *)name, - (char *)OTAPassword, - *OTAPort, - }; - if (shouldNotify) - { - this->notify(ObserverEvent::deviceConfigUpdated); - } + log_d("Updating device config"); + this->config.device = { + (char *)name, + (char *)OTAPassword, + *OTAPort, + }; + if (shouldNotify) + { + this->notify(ObserverEvent::deviceConfigUpdated); + } } void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, bool shouldNotify) { - this->config.camera = { - *vflip, - *framesize, - *href, - *quality, - }; + this->config.camera = { + *vflip, + *framesize, + *href, + *quality, + }; - log_d("Updating camera config"); - if (shouldNotify) - { - this->notify(ObserverEvent::cameraConfigUpdated); - } + log_d("Updating camera config"); + if (shouldNotify) + { + this->notify(ObserverEvent::cameraConfigUpdated); + } } void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify) { - WiFiConfig_t *networkToUpdate = nullptr; + WiFiConfig_t *networkToUpdate = nullptr; - for (int i = 0; i < this->config.networks.size(); i++) - { - if (strcmp(this->config.networks[i].name.c_str(), networkName) == 0) - networkToUpdate = &this->config.networks[i]; - } + for (int i = 0; i < this->config.networks.size(); i++) + { + if (strcmp(this->config.networks[i].name.c_str(), networkName) == 0) + networkToUpdate = &this->config.networks[i]; + } - if (networkToUpdate != nullptr) - { - this->config.networks = { - { - (char *)networkName, - (char *)ssid, - (char *)password, - *channel, - adhoc, - }, - }; - if (shouldNotify) - this->notify(ObserverEvent::networksConfigUpdated); - } - log_d("Updating wifi config"); + if (networkToUpdate != nullptr) + { + this->config.networks = { + { + (char *)networkName, + (char *)ssid, + (char *)password, + *channel, + adhoc, + }, + }; + if (shouldNotify) + this->notify(ObserverEvent::networksConfigUpdated); + } + log_d("Updating wifi config"); } void ProjectConfig::setAPWifiConfig(const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify) { - this->config.ap_network = { - (char *)ssid, - (char *)password, - *channel, - adhoc, - }; + this->config.ap_network = { + (char *)ssid, + (char *)password, + *channel, + adhoc, + }; - log_d("Updating access point config"); - if (shouldNotify) - { - this->notify(ObserverEvent::networksConfigUpdated); - } + log_d("Updating access point config"); + if (shouldNotify) + { + this->notify(ObserverEvent::networksConfigUpdated); + } } \ No newline at end of file diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 0b87401..ce60c64 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -11,73 +11,73 @@ class ProjectConfig : public Config, public ISubject { public: - ProjectConfig(); - virtual ~ProjectConfig(); - void load(); - void save(); - void reset(); - void initConfig(); + ProjectConfig(); + virtual ~ProjectConfig(); + void load(); + void save(); + void reset(); + void initConfig(); - struct DeviceConfig_t - { - std::string name; - std::string OTAPassword; - int OTAPort; - bool data_json; - bool config_json; - bool settings_json; - String data_json_string; - String config_json_string; - String settings_json_string; - }; + struct DeviceConfig_t + { + std::string name; + std::string OTAPassword; + int OTAPort; + bool data_json; + bool config_json; + bool settings_json; + String data_json_string; + String config_json_string; + String settings_json_string; + }; - struct CameraConfig_t - { - uint8_t vflip; - uint8_t framesize; - uint8_t href; - uint8_t quality; - }; + struct CameraConfig_t + { + uint8_t vflip; + uint8_t framesize; + uint8_t href; + uint8_t quality; + }; - struct WiFiConfig_t - { - std::string name; - std::string ssid; - std::string password; - uint8_t channel; - bool adhoc; - }; + struct WiFiConfig_t + { + std::string name; + std::string ssid; + std::string password; + uint8_t channel; + bool adhoc; + }; - struct AP_WiFiConfig_t - { - std::string ssid; - std::string password; - uint8_t channel; - bool adhoc; - }; + struct AP_WiFiConfig_t + { + std::string ssid; + std::string password; + uint8_t channel; + bool adhoc; + }; - struct TrackerConfig_t - { - DeviceConfig_t device; - CameraConfig_t camera; - std::vector networks; - AP_WiFiConfig_t ap_network; - }; + struct TrackerConfig_t + { + DeviceConfig_t device; + CameraConfig_t camera; + std::vector networks; + AP_WiFiConfig_t ap_network; + }; - DeviceConfig_t *getDeviceConfig() { return &this->config.device; } - CameraConfig_t *getCameraConfig() { return &this->config.camera; } - std::vector *getWifiConfigs() { return &this->config.networks; } - AP_WiFiConfig_t *getAPWifiConfig() { return &this->config.ap_network; } + DeviceConfig_t *getDeviceConfig() { return &this->config.device; } + CameraConfig_t *getCameraConfig() { return &this->config.camera; } + std::vector *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 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, uint8_t *channel, bool adhoc, bool shouldNotify); - void setAPWifiConfig(const char *ssid, const char *password, uint8_t *channel, bool adhoc, 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 setWifiConfig(const char *networkName, const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify); + void setAPWifiConfig(const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify); private: - const char *configFileName; - TrackerConfig_t config; - bool _already_loaded; + const char *configFileName; + TrackerConfig_t config; + bool _already_loaded; }; #endif // PROJECT_CONFIG_HPP \ No newline at end of file diff --git a/ESP/lib/src/io/LEDManager/LEDManager.cpp b/ESP/lib/src/io/LEDManager/LEDManager.cpp index e7cc57c..c3982ed 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.cpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.cpp @@ -6,32 +6,32 @@ LEDManager::~LEDManager() {} void LEDManager::begin() { - pinMode(_ledPin, OUTPUT); - onOff(false); + pinMode(_ledPin, OUTPUT); + onOff(false); - /* for (auto &led : _leds) - { - if (led > 0) - { - pinMode(led, OUTPUT); - } - } */ + /* for (auto &led : _leds) + { + if (led > 0) + { + pinMode(led, OUTPUT); + } + } */ } void LEDManager::onOff(bool state) const { - digitalWrite(_ledPin, state); + digitalWrite(_ledPin, state); } void LEDManager::blink(unsigned long time) { - unsigned long currentMillis = millis(); - if (currentMillis - _previousMillis >= time) - { - _previousMillis = currentMillis; - _ledState = !_ledState; - onOff(_ledState); - } + unsigned long currentMillis = millis(); + if (currentMillis - _previousMillis >= time) + { + _previousMillis = currentMillis; + _ledState = !_ledState; + onOff(_ledState); + } } void LEDManager::displayStatus() diff --git a/ESP/lib/src/io/LEDManager/LEDManager.hpp b/ESP/lib/src/io/LEDManager/LEDManager.hpp index 70f09e8..6501723 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.hpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.hpp @@ -5,18 +5,18 @@ class LEDManager { public: - LEDManager(byte pin); - virtual ~LEDManager(); + LEDManager(byte pin); + virtual ~LEDManager(); - void begin(); - void onOff(bool state) const; - void blink(unsigned long time); - void displayStatus(); + void begin(); + void onOff(bool state) const; + void blink(unsigned long time); + void displayStatus(); private: - byte _ledPin; - unsigned long _previousMillis; - bool _ledState; + byte _ledPin; + unsigned long _previousMillis; + bool _ledState; }; #endif // LEDMANAGER_HPP \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/serialmanager.cpp b/ESP/lib/src/io/SerialManager/serialmanager.cpp index 0657960..bc8a670 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.cpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -1,15 +1,15 @@ #include "serialmanager.hpp" std::unordered_map SerialManager::command_map = { - {"", NO_INPUT}, - {"device_config", DEVICE_CONFIG}, - {"camera_config", CAMERA_CONFIG}, - {"wifi_config", WIFI_CONFIG}}; + {"", NO_INPUT}, + {"device_config", DEVICE_CONFIG}, + {"camera_config", CAMERA_CONFIG}, + {"wifi_config", WIFI_CONFIG}}; void readStr(const char *inStr); SerialManager::SerialManager(ProjectConfig *projectConfig) : projectConfig(projectConfig), - serReader(std::make_unique()) + serReader(std::make_unique()) { } @@ -17,67 +17,67 @@ SerialManager::~SerialManager() {} void SerialManager::begin() { - serReader->setCallback(readStr); + serReader->setCallback(readStr); } void readStr(const char *inStr) { - Serial.print("command : "); - Serial.println(inStr); - std::string raw = inStr; - std::vector command; - Helpers::split(raw, ":", command); //! gives us the command and the value - "command:value" - std::vector command_value; - Helpers::split(command[1], ",", command_value); //! gives us the command and the value - "command:value" + Serial.print("command : "); + Serial.println(inStr); + std::string raw = inStr; + std::vector command; + Helpers::split(raw, ":", command); //! gives us the command and the value - "command:value" + std::vector command_value; + Helpers::split(command[1], ",", command_value); //! gives us the command and the value - "command:value" - //! The following line uses strdup to return a char* to lwrCase - char *lwr_case = strdup(command[0].c_str()); - lwrCase(lwr_case); //! converts the command to lowercase + //! The following line uses strdup to return a char* to lwrCase + char *lwr_case = strdup(command[0].c_str()); + lwrCase(lwr_case); //! converts the command to lowercase - switch (SerialManager::command_map[lwr_case]) - { - case SerialManager::NO_INPUT: - break; - case SerialManager::DEVICE_CONFIG: - break; - case SerialManager::CAMERA_CONFIG: - break; - case SerialManager::WIFI_CONFIG: - break; - } + switch (SerialManager::command_map[lwr_case]) + { + case SerialManager::NO_INPUT: + break; + case SerialManager::DEVICE_CONFIG: + break; + case SerialManager::CAMERA_CONFIG: + break; + case SerialManager::WIFI_CONFIG: + break; + } } void SerialManager::handleSerial() { - if (Serial.available() > 0) - { - delay(10); - std::string raw = Serial.readStringUntil('#').c_str(); - // String s = "{\"a\":\"b\"}"; + if (Serial.available() > 0) + { + delay(10); + std::string raw = Serial.readStringUntil('#').c_str(); + // String s = "{\"a\":\"b\"}"; - while (Serial.available() > 0) - { - Serial.read(); - } - log_d("Received Serial Data: %s", raw.c_str()); + while (Serial.available() > 0) + { + Serial.read(); + } + log_d("Received Serial Data: %s", raw.c_str()); - DeserializationError error = deserializeJson(jsonDoc, raw); - if (error) - { - log_e("deserializeJson() failed: %s", error.c_str()); - return; - } + DeserializationError error = deserializeJson(jsonDoc, raw); + if (error) + { + log_e("deserializeJson() failed: %s", error.c_str()); + return; + } - const char *device_config_name = jsonDoc["device_config_name"]; - const char *device_config_OTAPassword = jsonDoc["device_config_OTAPassword"]; - const char *device_config_OTAPort = jsonDoc["device_config_OTAPort"]; - const char *camera_config_vflip = jsonDoc["camera_config_vflip"]; - const char *camera_config_href = jsonDoc["camera_config_href"]; - const char *camera_config_framesize = jsonDoc["camera_config_framesize"]; - const char *camera_config_quality = jsonDoc["camera_config_quality"]; - const char *wifi_config_name = jsonDoc["wifi_config_name"]; - const char *wifi_config_ssid = jsonDoc["wifi_config_ssid"]; - const char *wifi_config_password = jsonDoc["wifi_config_password"]; - const char *wifi_config_channel = jsonDoc["wifi_config_channel"]; - } + const char *device_config_name = jsonDoc["device_config_name"]; + const char *device_config_OTAPassword = jsonDoc["device_config_OTAPassword"]; + const char *device_config_OTAPort = jsonDoc["device_config_OTAPort"]; + const char *camera_config_vflip = jsonDoc["camera_config_vflip"]; + const char *camera_config_href = jsonDoc["camera_config_href"]; + const char *camera_config_framesize = jsonDoc["camera_config_framesize"]; + const char *camera_config_quality = jsonDoc["camera_config_quality"]; + const char *wifi_config_name = jsonDoc["wifi_config_name"]; + const char *wifi_config_ssid = jsonDoc["wifi_config_ssid"]; + const char *wifi_config_password = jsonDoc["wifi_config_password"]; + const char *wifi_config_channel = jsonDoc["wifi_config_channel"]; + } } \ No newline at end of file diff --git a/ESP/lib/src/io/SerialManager/serialmanager.hpp b/ESP/lib/src/io/SerialManager/serialmanager.hpp index 4b2c430..3d94a5d 100644 --- a/ESP/lib/src/io/SerialManager/serialmanager.hpp +++ b/ESP/lib/src/io/SerialManager/serialmanager.hpp @@ -16,28 +16,28 @@ class SerialManager { public: - SerialManager(ProjectConfig *projectConfig); - virtual ~SerialManager(); + SerialManager(ProjectConfig *projectConfig); + virtual ~SerialManager(); - void begin(); - void handleSerial(); + void begin(); + void handleSerial(); - friend void readStr(const char *inStr); + friend void readStr(const char *inStr); protected: - ProjectConfig *projectConfig; - std::unique_ptr serReader; + ProjectConfig *projectConfig; + std::unique_ptr serReader; - enum Serial_Commands - { - NO_INPUT, - DEVICE_CONFIG, - CAMERA_CONFIG, - WIFI_CONFIG - }; + enum Serial_Commands + { + NO_INPUT, + DEVICE_CONFIG, + CAMERA_CONFIG, + WIFI_CONFIG + }; - static std::unordered_map command_map; - StaticJsonDocument<1024> jsonDoc; + static std::unordered_map command_map; + StaticJsonDocument<1024> jsonDoc; }; #endif // SERIAL_MANAGER_HPP \ No newline at end of file diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index 1fea831..f833f88 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -2,120 +2,120 @@ int CameraHandler::setupCamera() { - log_d("Setting up camera \r\n"); + log_d("Setting up camera \r\n"); - config.ledc_channel = LEDC_CHANNEL_0; - config.ledc_timer = LEDC_TIMER_0; - config.pin_d0 = Y2_GPIO_NUM; - config.pin_d1 = Y3_GPIO_NUM; - config.pin_d2 = Y4_GPIO_NUM; - config.pin_d3 = Y5_GPIO_NUM; - config.pin_d4 = Y6_GPIO_NUM; - config.pin_d5 = Y7_GPIO_NUM; - config.pin_d6 = Y8_GPIO_NUM; - config.pin_d7 = Y9_GPIO_NUM; - config.pin_xclk = XCLK_GPIO_NUM; - config.pin_pclk = PCLK_GPIO_NUM; - config.pin_vsync = VSYNC_GPIO_NUM; - config.pin_href = HREF_GPIO_NUM; - config.pin_sscb_sda = SIOD_GPIO_NUM; - config.pin_sscb_scl = SIOC_GPIO_NUM; - config.pin_pwdn = PWDN_GPIO_NUM; - config.pin_reset = RESET_GPIO_NUM; - config.xclk_freq_hz = 20000000; // 10000000 stable, - // 16500000 optimal, - // 20000000 max fps - config.pixel_format = PIXFORMAT_JPEG; + config.ledc_channel = LEDC_CHANNEL_0; + config.ledc_timer = LEDC_TIMER_0; + config.pin_d0 = Y2_GPIO_NUM; + config.pin_d1 = Y3_GPIO_NUM; + config.pin_d2 = Y4_GPIO_NUM; + config.pin_d3 = Y5_GPIO_NUM; + config.pin_d4 = Y6_GPIO_NUM; + config.pin_d5 = Y7_GPIO_NUM; + config.pin_d6 = Y8_GPIO_NUM; + config.pin_d7 = Y9_GPIO_NUM; + config.pin_xclk = XCLK_GPIO_NUM; + config.pin_pclk = PCLK_GPIO_NUM; + config.pin_vsync = VSYNC_GPIO_NUM; + config.pin_href = HREF_GPIO_NUM; + config.pin_sscb_sda = SIOD_GPIO_NUM; + config.pin_sscb_scl = SIOC_GPIO_NUM; + config.pin_pwdn = PWDN_GPIO_NUM; + config.pin_reset = RESET_GPIO_NUM; + config.xclk_freq_hz = 20000000; // 10000000 stable, + // 16500000 optimal, + // 20000000 max fps + config.pixel_format = PIXFORMAT_JPEG; - if (psramFound()) - { - log_d("Found psram, setting the 240x240 image quality"); - config.frame_size = FRAMESIZE_240X240; - config.jpeg_quality = 7; // 0-63 lower number = higher quality, more latency and less fps 7 for most fps, 5 for best quality - config.fb_count = 3; - } - else - { - log_e("Did not find psram, setting svga quality"); - config.frame_size = FRAMESIZE_SVGA; - config.jpeg_quality = 1; - config.fb_count = 1; - } + if (psramFound()) + { + log_d("Found psram, setting the 240x240 image quality"); + config.frame_size = FRAMESIZE_240X240; + config.jpeg_quality = 7; // 0-63 lower number = higher quality, more latency and less fps 7 for most fps, 5 for best quality + config.fb_count = 3; + } + else + { + log_e("Did not find psram, setting svga quality"); + config.frame_size = FRAMESIZE_SVGA; + config.jpeg_quality = 1; + config.fb_count = 1; + } - esp_err_t err = esp_camera_init(&config); + esp_err_t err = esp_camera_init(&config); - camera_sensor = esp_camera_sensor_get(); - // fixes corrupted jpegs, https://github.com/espressif/esp32-camera/issues/203 - camera_sensor->set_reg(camera_sensor, 0xff, 0xff, 0x00); // banksel - camera_sensor->set_reg(camera_sensor, 0xd3, 0xff, 5); // clock - camera_sensor->set_brightness(camera_sensor, 2); // -2 to 2 I see no difference between numbers.. - camera_sensor->set_contrast(camera_sensor, 2); // -2 to 2 - camera_sensor->set_saturation(camera_sensor, -2); // -2 to 2 - camera_sensor->set_whitebal(camera_sensor, 1); // 0 = disable , 1 = enable - camera_sensor->set_awb_gain(camera_sensor, 1); // 0 = disable , 1 = enable - camera_sensor->set_wb_mode(camera_sensor, 0); // 0 to 4 - if awb_gain enabled (0 - Auto, 1 - Sunny, 2 - Cloudy, 3 - Office, 4 - Home) - camera_sensor->set_exposure_ctrl(camera_sensor, 1); // 0 = disable , 1 = enable - camera_sensor->set_aec2(camera_sensor, 0); // 0 = disable , 1 = enable - camera_sensor->set_gain_ctrl(camera_sensor, 0); // 0 = disable , 1 = enable - camera_sensor->set_agc_gain(camera_sensor, 2); // 0 to 30 brightness of sorts? higher = brighter with more lag - camera_sensor->set_gainceiling(camera_sensor, (gainceiling_t)6); // 0 to 6 - camera_sensor->set_bpc(camera_sensor, 1); // 0 = disable , 1 = enable - camera_sensor->set_wpc(camera_sensor, 1); // 0 = disable , 1 = enable - camera_sensor->set_raw_gma(camera_sensor, 1); // 0 = disable , 1 = enable (makes much lighter and noisy) - camera_sensor->set_lenc(camera_sensor, 0); // 0 = disable , 1 = enable // 0 = disable , 1 = enable - camera_sensor->set_dcw(camera_sensor, 0); // 0 = disable , 1 = enable - camera_sensor->set_colorbar(camera_sensor, 0); // 0 = disable , 1 = enable - camera_sensor->set_special_effect(camera_sensor, 2); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 4 - Green Tint, 5 - Blue Tint, 6 - Sepia) + camera_sensor = esp_camera_sensor_get(); + // fixes corrupted jpegs, https://github.com/espressif/esp32-camera/issues/203 + camera_sensor->set_reg(camera_sensor, 0xff, 0xff, 0x00); // banksel + camera_sensor->set_reg(camera_sensor, 0xd3, 0xff, 5); // clock + camera_sensor->set_brightness(camera_sensor, 2); // -2 to 2 I see no difference between numbers.. + camera_sensor->set_contrast(camera_sensor, 2); // -2 to 2 + camera_sensor->set_saturation(camera_sensor, -2); // -2 to 2 + camera_sensor->set_whitebal(camera_sensor, 1); // 0 = disable , 1 = enable + camera_sensor->set_awb_gain(camera_sensor, 1); // 0 = disable , 1 = enable + camera_sensor->set_wb_mode(camera_sensor, 0); // 0 to 4 - if awb_gain enabled (0 - Auto, 1 - Sunny, 2 - Cloudy, 3 - Office, 4 - Home) + camera_sensor->set_exposure_ctrl(camera_sensor, 1); // 0 = disable , 1 = enable + camera_sensor->set_aec2(camera_sensor, 0); // 0 = disable , 1 = enable + camera_sensor->set_gain_ctrl(camera_sensor, 0); // 0 = disable , 1 = enable + camera_sensor->set_agc_gain(camera_sensor, 2); // 0 to 30 brightness of sorts? higher = brighter with more lag + camera_sensor->set_gainceiling(camera_sensor, (gainceiling_t)6); // 0 to 6 + camera_sensor->set_bpc(camera_sensor, 1); // 0 = disable , 1 = enable + camera_sensor->set_wpc(camera_sensor, 1); // 0 = disable , 1 = enable + camera_sensor->set_raw_gma(camera_sensor, 1); // 0 = disable , 1 = enable (makes much lighter and noisy) + camera_sensor->set_lenc(camera_sensor, 0); // 0 = disable , 1 = enable // 0 = disable , 1 = enable + camera_sensor->set_dcw(camera_sensor, 0); // 0 = disable , 1 = enable + camera_sensor->set_colorbar(camera_sensor, 0); // 0 = disable , 1 = enable + camera_sensor->set_special_effect(camera_sensor, 2); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 4 - Green Tint, 5 - Blue Tint, 6 - Sepia) - if (err != ESP_OK) - { - log_e("Camera initialization failed with error: 0x%x \r\n", err); - //! TODO add led blinking here - return -1; - } - else - { - log_d("Sucessfully initialized the camera!"); - //! TODO add led blinking here - return 0; - } + if (err != ESP_OK) + { + log_e("Camera initialization failed with error: 0x%x \r\n", err); + //! TODO add led blinking here + return -1; + } + else + { + log_d("Sucessfully initialized the camera!"); + //! TODO add led blinking here + return 0; + } } void CameraHandler::update(ObserverEvent::Event event) { - if (event == ObserverEvent::cameraConfigUpdated) - { - ProjectConfig::CameraConfig_t *cameraConfig = configManager->getCameraConfig(); - this->setHFlip(cameraConfig->href); - this->setVFlip(cameraConfig->vflip); - this->setCameraResolution((framesize_t)cameraConfig->framesize); - camera_sensor->set_quality(camera_sensor, cameraConfig->quality); - } + if (event == ObserverEvent::cameraConfigUpdated) + { + ProjectConfig::CameraConfig_t *cameraConfig = configManager->getCameraConfig(); + this->setHFlip(cameraConfig->href); + this->setVFlip(cameraConfig->vflip); + this->setCameraResolution((framesize_t)cameraConfig->framesize); + camera_sensor->set_quality(camera_sensor, cameraConfig->quality); + } } int CameraHandler::setCameraResolution(framesize_t frameSize) { - if (camera_sensor->pixformat == PIXFORMAT_JPEG) - { - try - { - return camera_sensor->set_framesize(camera_sensor, frameSize); - } - catch (...) - { - // they sent us a malformed or unsupported frameSize - rather than crash - tell them about it - return -1; - } - } - return -1; + if (camera_sensor->pixformat == PIXFORMAT_JPEG) + { + try + { + return camera_sensor->set_framesize(camera_sensor, frameSize); + } + catch (...) + { + // they sent us a malformed or unsupported frameSize - rather than crash - tell them about it + return -1; + } + } + return -1; } int CameraHandler::setVFlip(int direction) { - return camera_sensor->set_vflip(camera_sensor, direction); + return camera_sensor->set_vflip(camera_sensor, direction); } int CameraHandler::setHFlip(int direction) { - return camera_sensor->set_hmirror(camera_sensor, direction); + return camera_sensor->set_hmirror(camera_sensor, direction); } \ No newline at end of file diff --git a/ESP/lib/src/io/camera/cameraHandler.hpp b/ESP/lib/src/io/camera/cameraHandler.hpp index 908cdec..3471077 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -7,17 +7,16 @@ class CameraHandler : IObserver { private: - sensor_t *camera_sensor; - camera_config_t config; - ProjectConfig *configManager; + sensor_t *camera_sensor; + camera_config_t config; + ProjectConfig *configManager; public: - - CameraHandler(ProjectConfig *configManager) : configManager(configManager) {} - int setupCamera(); - int setCameraResolution(framesize_t frameSize); - int setVFlip(int direction); - int setHFlip(int direction); - int setVieWindow(int offsetX, int offsetY, int outputX, int outputY); - void update(ObserverEvent::Event event); + CameraHandler(ProjectConfig *configManager) : configManager(configManager) {} + int setupCamera(); + int setCameraResolution(framesize_t frameSize); + int setVFlip(int direction); + int setHFlip(int direction); + int setVieWindow(int offsetX, int offsetY, int outputX, int outputY); + void update(ObserverEvent::Event event); }; diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index a90ccfa..8ce2866 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -10,25 +10,25 @@ class WiFiHandler { public: - WiFiHandler(ProjectConfig *configManager, StateManager *stateManager, - std::string ssid, - std::string password, - uint8_t channel); - virtual ~WiFiHandler(); - void setupWifi(); + WiFiHandler(ProjectConfig *configManager, StateManager *stateManager, + std::string ssid, + std::string password, + uint8_t channel); + virtual ~WiFiHandler(); + void setupWifi(); - ProjectConfig *configManager; - StateManager *stateManager; + ProjectConfig *configManager; + StateManager *stateManager; - bool _enable_adhoc; + bool _enable_adhoc; private: - void setUpADHOC(); - void adhoc(const char *ssid, const char *password, uint8_t channel); - void iniSTA(); + void setUpADHOC(); + void adhoc(const char *ssid, const char *password, uint8_t channel); + void iniSTA(); - std::string ssid; - std::string password; - uint8_t channel; + std::string ssid; + std::string password; + uint8_t channel; }; #endif // WIFIHANDLER_HPP diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index b60bc24..f303e60 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -1,55 +1,55 @@ #include "baseAPI.hpp" BaseAPI::BaseAPI(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - std::string api_url) : API_Utilities(CONTROL_PORT, - network, - camera, - stateManager, - api_url) {} + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url) : API_Utilities(CONTROL_PORT, + network, + camera, + stateManager, + api_url) {} BaseAPI::~BaseAPI() {} void BaseAPI::begin() { - this->setupServer(); - //! i have changed this to use lambdas instead of std::bind to avoid the overhead. Lambdas are always more preferable. - server->on("/", 0b00000001, [&](AsyncWebServerRequest *request) - { request->send(200); }); + this->setupServer(); + //! i have changed this to use lambdas instead of std::bind to avoid the overhead. Lambdas are always more preferable. + server->on("/", 0b00000001, [&](AsyncWebServerRequest *request) + { request->send(200); }); - // preflight cors check - server->on("/", 0b01000000, [&](AsyncWebServerRequest *request) - { + // preflight cors check + server->on("/", 0b01000000, [&](AsyncWebServerRequest *request) + { AsyncWebServerResponse* response = request->beginResponse(204); response->addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS"); response->addHeader("Access-Control-Allow-Headers", "Accept, Content-Type, Authorization"); response->addHeader("Access-Control-Allow-Credentials", "true"); request->send(response); }); - DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); + DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); - // std::bind(&BaseAPI::API_Utilities::notFound, &api_utilities, std::placeholders::_1); - server->onNotFound([&](AsyncWebServerRequest *request) - { notFound(request); }); + // std::bind(&BaseAPI::API_Utilities::notFound, &api_utilities, std::placeholders::_1); + server->onNotFound([&](AsyncWebServerRequest *request) + { notFound(request); }); } void BaseAPI::setupServer() { - localWifiConfig = { - .ssid = "", - .pass = "", - .channel = 0, - .adhoc = false, - }; + localWifiConfig = { + .ssid = "", + .pass = "", + .channel = 0, + .adhoc = false, + }; - localAPWifiConfig = { - .ssid = "", - .pass = "", - .channel = 0, - .adhoc = false, - }; + localAPWifiConfig = { + .ssid = "", + .pass = "", + .channel = 0, + .adhoc = false, + }; } //********************************************************************************************* @@ -57,42 +57,42 @@ void BaseAPI::setupServer() //********************************************************************************************* void BaseAPI::setWiFi(AsyncWebServerRequest *request) { - switch (_networkMethodsMap_enum[request->method()]) - { - case POST: - { - int params = request->params(); - for (int i = 0; i < params; i++) - { - AsyncWebParameter *param = request->getParam(i); - if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) - { - localAPWifiConfig.ssid = param->value().c_str(); - localAPWifiConfig.pass = param->value().c_str(); - localAPWifiConfig.channel = atoi(param->value().c_str()); - localAPWifiConfig.adhoc = atoi(param->value().c_str()); - } - else - { - localWifiConfig.ssid = param->value().c_str(); - localWifiConfig.pass = param->value().c_str(); - localWifiConfig.channel = atoi(param->value().c_str()); - localWifiConfig.adhoc = atoi(param->value().c_str()); - } - } - ssid_write = true; - pass_write = true; - channel_write = true; - request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); - break; - } - default: - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - request->redirect("/"); - break; - } - } + switch (_networkMethodsMap_enum[request->method()]) + { + case POST: + { + int params = request->params(); + for (int i = 0; i < params; i++) + { + AsyncWebParameter *param = request->getParam(i); + if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + { + localAPWifiConfig.ssid = param->value().c_str(); + localAPWifiConfig.pass = param->value().c_str(); + localAPWifiConfig.channel = atoi(param->value().c_str()); + localAPWifiConfig.adhoc = atoi(param->value().c_str()); + } + else + { + localWifiConfig.ssid = param->value().c_str(); + localWifiConfig.pass = param->value().c_str(); + localWifiConfig.channel = atoi(param->value().c_str()); + localWifiConfig.adhoc = atoi(param->value().c_str()); + } + } + ssid_write = true; + pass_write = true; + channel_write = true; + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); + break; + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + request->redirect("/"); + break; + } + } } /** @@ -101,126 +101,126 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) */ void BaseAPI::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->setAPWifiConfig(localAPWifiConfig.ssid.c_str(), localAPWifiConfig.pass.c_str(), &localAPWifiConfig.channel, localAPWifiConfig.adhoc, true); - else - network->configManager->setWifiConfig(localWifiConfig.ssid.c_str(), localWifiConfig.ssid.c_str(), localWifiConfig.pass.c_str(), &localWifiConfig.channel, localAPWifiConfig.adhoc, true); - network->configManager->save(); - } + 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->setAPWifiConfig(localAPWifiConfig.ssid.c_str(), localAPWifiConfig.pass.c_str(), &localAPWifiConfig.channel, localAPWifiConfig.adhoc, true); + else + network->configManager->setWifiConfig(localWifiConfig.ssid.c_str(), localWifiConfig.ssid.c_str(), localWifiConfig.pass.c_str(), &localWifiConfig.channel, localAPWifiConfig.adhoc, true); + network->configManager->save(); + } } void BaseAPI::handleJson(AsyncWebServerRequest *request) { - std::string type = request->pathArg(0).c_str(); - switch (_networkMethodsMap_enum[request->method()]) - { - case POST: - { - switch (json_TypesMap.at(type)) - { - case DATA: - { - break; - } - case SETTINGS: - { - break; - } - case CONFIG: - { - break; - } - default: - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } - break; - } - case GET: - { - switch (json_TypesMap.at(type)) - { - case DATA: - { - network->configManager->getDeviceConfig()->data_json = true; - Network_Utilities::my_delay(1L); - String temp = network->configManager->getDeviceConfig()->data_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; - break; - } - case SETTINGS: - { - network->configManager->getDeviceConfig()->config_json = true; - Network_Utilities::my_delay(1L); - String temp = network->configManager->getDeviceConfig()->config_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; - break; - } - case CONFIG: - { - network->configManager->getDeviceConfig()->settings_json = true; - Network_Utilities::my_delay(1L); - String temp = network->configManager->getDeviceConfig()->settings_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; - break; - } - default: - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } + std::string type = request->pathArg(0).c_str(); + switch (_networkMethodsMap_enum[request->method()]) + { + case POST: + { + switch (json_TypesMap.at(type)) + { + case DATA: + { + break; + } + case SETTINGS: + { + break; + } + case CONFIG: + { + break; + } + default: + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + break; + } + case GET: + { + switch (json_TypesMap.at(type)) + { + case DATA: + { + network->configManager->getDeviceConfig()->data_json = true; + Network_Utilities::my_delay(1L); + String temp = network->configManager->getDeviceConfig()->data_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; + break; + } + case SETTINGS: + { + network->configManager->getDeviceConfig()->config_json = true; + Network_Utilities::my_delay(1L); + String temp = network->configManager->getDeviceConfig()->config_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; + break; + } + case CONFIG: + { + network->configManager->getDeviceConfig()->settings_json = true; + Network_Utilities::my_delay(1L); + String temp = network->configManager->getDeviceConfig()->settings_json_string; + request->send(200, MIMETYPE_JSON, temp); + temp = ""; + break; + } + default: + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } - break; - } - default: - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } - } + break; + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + } } void BaseAPI::rebootDevice(AsyncWebServerRequest *request) { - switch (_networkMethodsMap_enum[request->method()]) - { - case GET: - { - delay(20000); - request->send(200, MIMETYPE_JSON, "{\"msg\":\"Rebooting Device\"}"); - ESP.restart(); - } - default: - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } - } + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + delay(20000); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Rebooting Device\"}"); + ESP.restart(); + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + } } void BaseAPI::factoryReset(AsyncWebServerRequest *request) { - switch (_networkMethodsMap_enum[request->method()]) - { - case GET: - { - log_d("Factory Reset"); - network->configManager->reset(); - request->send(200, MIMETYPE_JSON, "{\"msg\":\"Factory Reset\"}"); - } - default: - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } - } + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + log_d("Factory Reset"); + network->configManager->reset(); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Factory Reset\"}"); + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + } } /** @@ -231,39 +231,39 @@ void BaseAPI::factoryReset(AsyncWebServerRequest *request) */ void BaseAPI::deleteRoute(AsyncWebServerRequest *request) { - log_i("Request: %s", request->url().c_str()); - int params = request->params(); - auto it_map = route_map.find(request->pathArg(0).c_str()); - log_i("Request: %s", request->pathArg(0).c_str()); - if (it_map != route_map.end()) - { - auto it = it_map->second.find(request->pathArg(1).c_str()); - if (it != it_map->second.end()) - { - switch (_networkMethodsMap_enum[request->method()]) - { - case DELETE: - { - route_map.erase(it_map->first); - request->send(200, MIMETYPE_JSON, "{\"msg\":\"OK - Command handler removed\"}"); - break; - } - default: - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } - } - } - else - { - request->send(404); - } - } - else - { - request->send(404); - } + log_i("Request: %s", request->url().c_str()); + int params = request->params(); + auto it_map = route_map.find(request->pathArg(0).c_str()); + log_i("Request: %s", request->pathArg(0).c_str()); + if (it_map != route_map.end()) + { + auto it = it_map->second.find(request->pathArg(1).c_str()); + if (it != it_map->second.end()) + { + switch (_networkMethodsMap_enum[request->method()]) + { + case DELETE: + { + route_map.erase(it_map->first); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"OK - Command handler removed\"}"); + break; + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + } + } + else + { + request->send(404); + } + } + else + { + request->send(404); + } } //********************************************************************************************* @@ -272,26 +272,26 @@ void BaseAPI::deleteRoute(AsyncWebServerRequest *request) void BaseAPI::setCamera(AsyncWebServerRequest *request) { - switch (_networkMethodsMap_enum[request->method()]) - { - case GET: - { - int params = request->params(); - for (int i = 0; i < params; i++) - { - AsyncWebParameter *param = request->getParam(i); - camera->setCameraResolution((framesize_t)atoi(param->value().c_str())); - camera->setVFlip(atoi(param->value().c_str())); - camera->setHFlip(atoi(param->value().c_str())); - } - request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera Settings have been set.\"}"); - break; - } - default: - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - request->redirect("/"); - break; - } - } + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + int params = request->params(); + for (int i = 0; i < params; i++) + { + AsyncWebParameter *param = request->getParam(i); + camera->setCameraResolution((framesize_t)atoi(param->value().c_str())); + camera->setVFlip(atoi(param->value().c_str())); + camera->setHFlip(atoi(param->value().c_str())); + } + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera Settings have been set.\"}"); + break; + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + request->redirect("/"); + break; + } + } } \ No newline at end of file diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index d8aab17..c8efd36 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -6,79 +6,79 @@ class BaseAPI : public API_Utilities { protected: - struct LocalWifiConfig - { - std::string ssid; - std::string pass; - uint8_t channel; - bool adhoc; - }; + struct LocalWifiConfig + { + std::string ssid; + std::string pass; + uint8_t channel; + bool adhoc; + }; - LocalWifiConfig localWifiConfig; + LocalWifiConfig localWifiConfig; - struct LocalAPWifiConfig - { - std::string ssid; - std::string pass; - uint8_t channel; - }; + struct LocalAPWifiConfig + { + std::string ssid; + std::string pass; + uint8_t channel; + }; - LocalWifiConfig localAPWifiConfig; + LocalWifiConfig localAPWifiConfig; - enum JSON_TYPES - { - CONFIG, - SETTINGS, - DATA, - STATUS, - COMMANDS, - WIFI, - WIFIAP, - }; + enum JSON_TYPES + { + CONFIG, + SETTINGS, + DATA, + STATUS, + COMMANDS, + WIFI, + WIFIAP, + }; - std::unordered_map json_TypesMap = { - {"config", CONFIG}, - {"settings", SETTINGS}, - {"data", DATA}, - {"status", STATUS}, - {"commands", COMMANDS}, - {"wifi", WIFI}, - {"wifiap", WIFIAP}, - }; + std::unordered_map json_TypesMap = { + {"config", CONFIG}, + {"settings", SETTINGS}, + {"data", DATA}, + {"status", STATUS}, + {"commands", COMMANDS}, + {"wifi", WIFI}, + {"wifiap", WIFIAP}, + }; protected: - /* Commands */ - void setWiFi(AsyncWebServerRequest *request); - void handleJson(AsyncWebServerRequest *request); - void factoryReset(AsyncWebServerRequest *request); - void rebootDevice(AsyncWebServerRequest *request); - void deleteRoute(AsyncWebServerRequest *request); + /* Commands */ + void setWiFi(AsyncWebServerRequest *request); + void handleJson(AsyncWebServerRequest *request); + void factoryReset(AsyncWebServerRequest *request); + void rebootDevice(AsyncWebServerRequest *request); + void deleteRoute(AsyncWebServerRequest *request); - /* Camera Handler */ - void setCamera(AsyncWebServerRequest *request); + /* Camera Handler */ + void setCamera(AsyncWebServerRequest *request); - using call_back_function_t = void (BaseAPI::*)(AsyncWebServerRequest *); - typedef call_back_function_t (*call_back_function_ptr)(AsyncWebServerRequest *); + using call_back_function_t = void (BaseAPI::*)(AsyncWebServerRequest *); + typedef call_back_function_t (*call_back_function_ptr)(AsyncWebServerRequest *); - /* Route Command types */ - using route_method = void (BaseAPI::*)(AsyncWebServerRequest *); - // typedef void (*callback)(AsyncWebServerRequest *); - typedef std::unordered_map route_t; - typedef std::unordered_map route_map_t; + /* Route Command types */ + using route_method = void (BaseAPI::*)(AsyncWebServerRequest *); + // typedef void (*callback)(AsyncWebServerRequest *); + typedef std::unordered_map route_t; + typedef std::unordered_map route_map_t; - route_t routes; - route_map_t route_map; + route_t routes; + route_map_t route_map; public: - BaseAPI(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - std::string api_url); - virtual ~BaseAPI(); - virtual void begin(); - virtual void setupServer(); - void triggerWifiConfigWrite(); + BaseAPI(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url); + virtual ~BaseAPI(); + virtual void begin(); + virtual void setupServer(); + void triggerWifiConfigWrite(); }; #endif // BASEAPI_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index 8237183..764d6b3 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -19,98 +19,98 @@ bool API_Utilities::channel_write = false; //********************************************************************************************* API_Utilities::API_Utilities(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - std::string api_url) : server(new AsyncWebServer(CONTROL_PORT)), - stateManager(stateManager), - network(network), - camera(camera), - api_url(api_url) {} + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url) : server(new AsyncWebServer(CONTROL_PORT)), + stateManager(stateManager), + network(network), + camera(camera), + api_url(api_url) {} API_Utilities::~API_Utilities() {} std::string API_Utilities::shaEncoder(std::string data) { - const char *data_c = data.c_str(); - int size = 64; - uint8_t hash[size]; - mbedtls_md_context_t ctx; - mbedtls_md_type_t md_type = MBEDTLS_MD_SHA512; + const char *data_c = data.c_str(); + int size = 64; + uint8_t hash[size]; + mbedtls_md_context_t ctx; + mbedtls_md_type_t md_type = MBEDTLS_MD_SHA512; - const size_t len = strlen(data_c); - mbedtls_md_init(&ctx); - mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); - mbedtls_md_starts(&ctx); - mbedtls_md_update(&ctx, (const unsigned char *)data_c, len); - mbedtls_md_finish(&ctx, hash); - mbedtls_md_free(&ctx); + const size_t len = strlen(data_c); + mbedtls_md_init(&ctx); + mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); + mbedtls_md_starts(&ctx); + mbedtls_md_update(&ctx, (const unsigned char *)data_c, len); + mbedtls_md_finish(&ctx, hash); + mbedtls_md_free(&ctx); - std::string hash_string = ""; - for (uint16_t i = 0; i < size; i++) - { - std::string hex = String(hash[i], HEX).c_str(); - if (hex.length() < 2) - { - hex = "0" + hex; - } - hash_string += hex; - } - return hash_string; + std::string hash_string = ""; + for (uint16_t i = 0; i < size; i++) + { + std::string hex = String(hash[i], HEX).c_str(); + if (hex.length() < 2) + { + hex = "0" + hex; + } + hash_string += hex; + } + return hash_string; } void API_Utilities::notFound(AsyncWebServerRequest *request) const { - if (_networkMethodsMap.find(request->method()) != _networkMethodsMap.end()) - { - log_i("%s: http://%s%s/\n", _networkMethodsMap.at(request->method()).c_str(), request->host().c_str(), request->url().c_str()); - char buffer[100]; - snprintf(buffer, sizeof(buffer), "Request %s Not found: %s", _networkMethodsMap.at(request->method()).c_str(), request->url().c_str()); - request->send(404, "text/plain", buffer); - } - else - { - request->send(404, "text/plain", "Request Not found using unknown method"); - } + if (_networkMethodsMap.find(request->method()) != _networkMethodsMap.end()) + { + log_i("%s: http://%s%s/\n", _networkMethodsMap.at(request->method()).c_str(), request->host().c_str(), request->url().c_str()); + char buffer[100]; + snprintf(buffer, sizeof(buffer), "Request %s Not found: %s", _networkMethodsMap.at(request->method()).c_str(), request->url().c_str()); + request->send(404, "text/plain", buffer); + } + else + { + request->send(404, "text/plain", "Request Not found using unknown method"); + } } // Read File from SPIFFS /* String API_Utilities::readFile(fs::FS &fs, std::string path) { - log_i("Reading file: %s\r\n", path.c_str()); + log_i("Reading file: %s\r\n", path.c_str()); - File file = fs.open(path.c_str()); - if (!file || file.isDirectory()) - { - log_e("[INFO]: Failed to open file for reading"); - return String(); - } + File file = fs.open(path.c_str()); + if (!file || file.isDirectory()) + { + log_e("[INFO]: Failed to open file for reading"); + return String(); + } - String fileContent; - while (file.available()) - { - fileContent = file.readStringUntil('\n'); - break; - } - return fileContent; + String fileContent; + while (file.available()) + { + fileContent = file.readStringUntil('\n'); + break; + } + return fileContent; } // Write file to SPIFFS void API_Utilities::writeFile(fs::FS &fs, std::string path, std::string message) { - log_i("[Writing File]: Writing file: %s\r\n", path); - Network_Utilities::my_delay(0.1L); + log_i("[Writing File]: Writing file: %s\r\n", path); + Network_Utilities::my_delay(0.1L); - File file = fs.open(path.c_str(), FILE_WRITE); - if (!file) - { - log_i("[Writing File]: failed to open file for writing"); - return; - } - if (file.print(message.c_str())) - { - log_i("[Writing File]: file written"); - } - else - { - log_i("[Writing File]: file write failed"); - } + File file = fs.open(path.c_str(), FILE_WRITE); + if (!file) + { + log_i("[Writing File]: failed to open file for writing"); + return; + } + if (file.print(message.c_str())) + { + log_i("[Writing File]: file written"); + } + else + { + log_i("[Writing File]: file write failed"); + } } */ diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index 4df0ea1..1edc44e 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -4,7 +4,6 @@ #include #include - #define WEBSERVER_H /* #define XHTTP_GET 0b00000001; @@ -29,70 +28,70 @@ class API_Utilities { public: - API_Utilities(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - std::string api_url); - virtual ~API_Utilities(); + API_Utilities(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url); + virtual ~API_Utilities(); protected: - void notFound(AsyncWebServerRequest *request) const; - /* String readFile(fs::FS &fs, std::string path); - void writeFile(fs::FS &fs, std::string path, std::string message); */ - std::string shaEncoder(std::string data); - std::unordered_map _networkMethodsMap = { - {0, "NULL"}, - {0b00000001, "GET"}, - {0b00000010, "POST"}, - {0b00001000, "PUT"}, - {0b00000100, "DELETE"}, - {0b00010000, "PATCH"}, - {0b01000000, "OPTIONS"}, - }; + void notFound(AsyncWebServerRequest *request) const; + /* String readFile(fs::FS &fs, std::string path); + void writeFile(fs::FS &fs, std::string path, std::string message); */ + std::string shaEncoder(std::string data); + std::unordered_map _networkMethodsMap = { + {0, "NULL"}, + {0b00000001, "GET"}, + {0b00000010, "POST"}, + {0b00001000, "PUT"}, + {0b00000100, "DELETE"}, + {0b00010000, "PATCH"}, + {0b01000000, "OPTIONS"}, + }; - enum RequestMethods - { - NULL_METHOD, - GET, - POST, - PUT, - DELETE, - PATCH, - OPTIONS, - }; + enum RequestMethods + { + NULL_METHOD, + GET, + POST, + PUT, + DELETE, + PATCH, + OPTIONS, + }; - std::unordered_map _networkMethodsMap_enum = { - {0, NULL_METHOD}, - {0b00000001, GET}, - {0b00000010, POST}, - {0b00001000, PUT}, - {0b00000100, DELETE}, - {0b00010000, PATCH}, - {0b01000000, OPTIONS}, - }; + std::unordered_map _networkMethodsMap_enum = { + {0, NULL_METHOD}, + {0b00000001, GET}, + {0b00000010, POST}, + {0b00001000, PUT}, + {0b00000100, DELETE}, + {0b00010000, PATCH}, + {0b01000000, OPTIONS}, + }; protected: - AsyncWebServer *server; - WiFiHandler *network; - CameraHandler *camera; - StateManager *stateManager; - typedef std::unordered_map networkMethodsMap_t; + AsyncWebServer *server; + WiFiHandler *network; + CameraHandler *camera; + StateManager *stateManager; + typedef std::unordered_map networkMethodsMap_t; protected: - std::string api_url; + std::string api_url; - static bool ssid_write; - static bool pass_write; - static bool channel_write; + static bool ssid_write; + static bool pass_write; + static bool channel_write; - static const char *MIMETYPE_HTML; - /* static const char *MIMETYPE_CSS; */ - /* static const char *MIMETYPE_JS; */ - /* static const char *MIMETYPE_PNG; */ - /* static const char *MIMETYPE_JPG; */ - /* static const char *MIMETYPE_ICO; */ - static const char *MIMETYPE_JSON; + static const char *MIMETYPE_HTML; + /* static const char *MIMETYPE_CSS; */ + /* static const char *MIMETYPE_JS; */ + /* static const char *MIMETYPE_PNG; */ + /* static const char *MIMETYPE_JPG; */ + /* static const char *MIMETYPE_ICO; */ + static const char *MIMETYPE_JSON; }; #endif // APIUTILITIES_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/api/webserverHandler.hpp b/ESP/lib/src/network/api/webserverHandler.hpp index 8e2324b..1dd0923 100644 --- a/ESP/lib/src/network/api/webserverHandler.hpp +++ b/ESP/lib/src/network/api/webserverHandler.hpp @@ -7,20 +7,19 @@ class APIServer : public BaseAPI { public: - APIServer(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler* camera, - StateManager *stateManager, - std::string api_url); + APIServer(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url); - virtual ~APIServer(); - void begin(); - void setupServer(); + virtual ~APIServer(); + void begin(); + void setupServer(); - void findParam(AsyncWebServerRequest *request, const char *param, String &value); - void updateCommandHandlers(); - std::vector routeHandler(std::string index, route_t route); - void handleRequest(AsyncWebServerRequest *request); - + void findParam(AsyncWebServerRequest *request, const char *param, String &value); + void updateCommandHandlers(); + std::vector routeHandler(std::string index, route_t route); + void handleRequest(AsyncWebServerRequest *request); }; #endif // WEBSERVERHANDLER_HPP diff --git a/ESP/lib/src/network/mDNS/MDNSManager.cpp b/ESP/lib/src/network/mDNS/MDNSManager.cpp index 85f2133..319cdaa 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.cpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.cpp @@ -2,30 +2,30 @@ void MDNSHandler::startMDNS() { - ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig(); + ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig(); - if (MDNS.begin(deviceConfig->name.c_str())) - { - stateManager->setState(MDNSState_e::MDNSState_Starting); - MDNS.addService("openIrisTracker", "tcp", 80); - char port[20]; - //!Add service needs leading _ on ESP32 implementation for some reason (according to the docs) - MDNS.addServiceTxt("_openIrisTracker", "_tcp", "_stream_port", (const char*)Helpers::itoa(80, port, 10)); //! convert int to const char* using a very efficient implemenation of itoa - log_i("MDNS initialized!"); - stateManager->setState(MDNSState_e::MDNSState_Started); - } - else - { - stateManager->setState(MDNSState_e::MDNSState_Error); - log_e("Error initializing MDNS"); - } + if (MDNS.begin(deviceConfig->name.c_str())) + { + stateManager->setState(MDNSState_e::MDNSState_Starting); + MDNS.addService("openIrisTracker", "tcp", 80); + char port[20]; + //! Add service needs leading _ on ESP32 implementation for some reason (according to the docs) + MDNS.addServiceTxt("_openIrisTracker", "_tcp", "_stream_port", (const char *)Helpers::itoa(80, port, 10)); //! convert int to const char* using a very efficient implemenation of itoa + log_i("MDNS initialized!"); + stateManager->setState(MDNSState_e::MDNSState_Started); + } + else + { + stateManager->setState(MDNSState_e::MDNSState_Error); + log_e("Error initializing MDNS"); + } } void MDNSHandler::update(ObserverEvent::Event event) { - if (event == ObserverEvent::deviceConfigUpdated) - { - MDNS.end(); - startMDNS(); - } + if (event == ObserverEvent::deviceConfigUpdated) + { + MDNS.end(); + startMDNS(); + } } \ No newline at end of file diff --git a/ESP/lib/src/network/mDNS/MDNSManager.hpp b/ESP/lib/src/network/mDNS/MDNSManager.hpp index 865afbc..25237f0 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.hpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.hpp @@ -8,11 +8,11 @@ class MDNSHandler : public IObserver { private: - StateManager *stateManager; - ProjectConfig *configManager; + StateManager *stateManager; + ProjectConfig *configManager; public: - MDNSHandler(StateManager *stateManager, ProjectConfig *configManager) : stateManager(stateManager), configManager(configManager) {} - void startMDNS(); - void update(ObserverEvent::Event event); + MDNSHandler(StateManager *stateManager, ProjectConfig *configManager) : stateManager(stateManager), configManager(configManager) {} + void startMDNS(); + void update(ObserverEvent::Event event); }; \ No newline at end of file diff --git a/ESP/lib/src/network/stream/streamServer.cpp b/ESP/lib/src/network/stream/streamServer.cpp index b2f794a..5bfc272 100644 --- a/ESP/lib/src/network/stream/streamServer.cpp +++ b/ESP/lib/src/network/stream/streamServer.cpp @@ -6,103 +6,103 @@ constexpr static const char *STREAM_PART = "Content-Type: image/jpeg\r\nContent- esp_err_t StreamHelpers::stream(httpd_req_t *req) { - long last_request_time = 0; - camera_fb_t *fb = NULL; - struct timeval _timestamp; + long last_request_time = 0; + camera_fb_t *fb = NULL; + struct timeval _timestamp; - esp_err_t res = ESP_OK; + esp_err_t res = ESP_OK; - size_t _jpg_buf_len = 0; - uint8_t *_jpg_buf = NULL; + size_t _jpg_buf_len = 0; + uint8_t *_jpg_buf = NULL; - char *part_buf[128]; + char *part_buf[128]; - static int64_t last_frame = 0; - if (!last_frame) - last_frame = esp_timer_get_time(); + static int64_t last_frame = 0; + if (!last_frame) + last_frame = esp_timer_get_time(); - res = httpd_resp_set_type(req, STREAM_CONTENT_TYPE); - if (res != ESP_OK) - return res; + res = httpd_resp_set_type(req, STREAM_CONTENT_TYPE); + if (res != ESP_OK) + return res; - httpd_resp_set_hdr(req, "Access-Control-Allow-Origin; Content-Type: multipart/x-mixed-replace; boundary=123456789000000000000987654321\r\n", "*"); - httpd_resp_set_hdr(req, "X-Framerate", "60"); + httpd_resp_set_hdr(req, "Access-Control-Allow-Origin; Content-Type: multipart/x-mixed-replace; boundary=123456789000000000000987654321\r\n", "*"); + httpd_resp_set_hdr(req, "X-Framerate", "60"); - while (true) - { - fb = esp_camera_fb_get(); - if (!fb) - { - log_e("Camera capture failed"); - res = ESP_FAIL; - } - else - { - _timestamp.tv_sec = fb->timestamp.tv_sec; - _timestamp.tv_usec = fb->timestamp.tv_usec; - _jpg_buf_len = fb->len; - _jpg_buf = fb->buf; - } + while (true) + { + fb = esp_camera_fb_get(); + if (!fb) + { + log_e("Camera capture failed"); + res = ESP_FAIL; + } + else + { + _timestamp.tv_sec = fb->timestamp.tv_sec; + _timestamp.tv_usec = fb->timestamp.tv_usec; + _jpg_buf_len = fb->len; + _jpg_buf = fb->buf; + } - if (res == ESP_OK) - res = httpd_resp_send_chunk(req, STREAM_BOUNDARY, strlen(STREAM_BOUNDARY)); + if (res == ESP_OK) + res = httpd_resp_send_chunk(req, STREAM_BOUNDARY, strlen(STREAM_BOUNDARY)); - if (res == ESP_OK) - { - size_t hlen = snprintf((char *)part_buf, 128, STREAM_PART, _jpg_buf_len, _timestamp.tv_sec, _timestamp.tv_usec); - res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen); - } - if (res == ESP_OK) - res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len); + if (res == ESP_OK) + { + size_t hlen = snprintf((char *)part_buf, 128, STREAM_PART, _jpg_buf_len, _timestamp.tv_sec, _timestamp.tv_usec); + res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen); + } + if (res == ESP_OK) + res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len); - if (fb) - { - esp_camera_fb_return(fb); - fb = NULL; - _jpg_buf = NULL; - } + if (fb) + { + esp_camera_fb_return(fb); + fb = NULL; + _jpg_buf = NULL; + } - else if (_jpg_buf) - { - free(_jpg_buf); - _jpg_buf = NULL; - } + else if (_jpg_buf) + { + free(_jpg_buf); + _jpg_buf = NULL; + } - if (res != ESP_OK) - break; + if (res != ESP_OK) + break; - long request_end = millis(); - long latency = (request_end - last_request_time); - last_request_time = request_end; - log_d("Size: %uKB, Time: %ums (%ifps)\n", _jpg_buf_len / 1024, latency, 1000 / latency); - } + long request_end = millis(); + long latency = (request_end - last_request_time); + last_request_time = request_end; + log_d("Size: %uKB, Time: %ums (%ifps)\n", _jpg_buf_len / 1024, latency, 1000 / latency); + } - last_frame = 0; + last_frame = 0; - return res; + return res; } int StreamServer::startStreamServer() { - httpd_config_t config = HTTPD_DEFAULT_CONFIG(); - config.max_uri_handlers = 1; - config.server_port = this->STREAM_SERVER_PORT; - config.ctrl_port = this->STREAM_SERVER_PORT; + httpd_config_t config = HTTPD_DEFAULT_CONFIG(); + config.max_uri_handlers = 1; + config.server_port = this->STREAM_SERVER_PORT; + config.ctrl_port = this->STREAM_SERVER_PORT; - httpd_uri_t stream_page = { - .uri = "/", - .method = HTTP_GET, - .handler = &StreamHelpers::stream, - .user_ctx = nullptr}; + httpd_uri_t stream_page = { + .uri = "/", + .method = HTTP_GET, + .handler = &StreamHelpers::stream, + .user_ctx = nullptr}; - int status = httpd_start(&camera_stream, &config); + int status = httpd_start(&camera_stream, &config); - if (status != ESP_OK) - return -1; - else - { - httpd_register_uri_handler(camera_stream, &stream_page); - log_d("Stream server initialized"); - return 0; - } + if (status != ESP_OK) + return -1; + else + { + httpd_register_uri_handler(camera_stream, &stream_page); + log_d("Stream server initialized"); + return 0; + } } diff --git a/ESP/lib/src/network/stream/streamServer.hpp b/ESP/lib/src/network/stream/streamServer.hpp index a936334..2d19cae 100644 --- a/ESP/lib/src/network/stream/streamServer.hpp +++ b/ESP/lib/src/network/stream/streamServer.hpp @@ -8,18 +8,18 @@ namespace StreamHelpers { - esp_err_t stream(httpd_req_t *req); + esp_err_t stream(httpd_req_t *req); } class StreamServer { private: - httpd_handle_t camera_stream = nullptr; - int STREAM_SERVER_PORT; + httpd_handle_t camera_stream = nullptr; + int STREAM_SERVER_PORT; public: - StreamServer(int STREAM_PORT) : STREAM_SERVER_PORT(STREAM_PORT) {} - int startStreamServer(); + StreamServer(int STREAM_PORT) : STREAM_SERVER_PORT(STREAM_PORT) {} + int startStreamServer(); }; #endif // STREAM_SERVER_HPP diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 717e7de..12f4502 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -15,10 +15,11 @@ int STREAM_SERVER_PORT = 80; int CONTROL_SERVER_PORT = 81; -// Create smart pointers to the various classes that will be used in the program to make sure that they are deleted when the program ends -// This is done to make sure that the memory is freed when the program ends and we are not left with dangling pointers to memory that is no longer in use -// Make unique is a templated function that takes a class and returns a unique pointer to that class - -// it is used to create a unique pointer to a class and ensure exception safety +//! Create smart pointers to the various classes that will be used in the program to make sure that they are deleted when the program ends +//! This is done to make sure that the memory is freed when the program ends and we are not left with dangling pointers to memory that is no longer in use +//! Make unique is a templated function that takes a class and returns a unique pointer to that class - +//! it is used to create a unique pointer to a class and ensure exception safety + ProjectConfig deviceConfig; OTA ota(&deviceConfig); LEDManager ledManager(33); @@ -38,12 +39,6 @@ void setup() deviceConfig.load(); cameraHandler.setupCamera(); - /* auto localConfig = deviceConfig.getAPWifiConfig(); - if (localConfig->adhoc == true) - { - - } */ - wifiHandler._enable_adhoc = ENABLE_ADHOC; wifiHandler.setupWifi(); @@ -64,8 +59,8 @@ void setup() } case WiFiState_e::WiFiState_Connected: { - //apiServer.begin(); streamServer.startStreamServer(); + //apiServer.begin(); log_d("[SETUP]: Starting Stream Server"); break; } From a18129faf7c54de678cf54e4641d4ec5d1dc0266 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 20 Aug 2022 14:57:34 +0100 Subject: [PATCH 045/153] update - Fix some formatting issues --- ESP/lib/src/network/api/webserverHandler.cpp | 2 +- ESP/platformio.ini | 4 +- ESP/src/main.cpp | 90 ++++++++++---------- 3 files changed, 48 insertions(+), 48 deletions(-) diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index cd7f076..78b6283 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -25,7 +25,7 @@ void APIServer::begin() char buffer[1000]; snprintf(buffer, sizeof(buffer), "^\\%s\\/([a-zA-Z0-9]+)\\/command\\/([a-zA-Z0-9]+)$", this->api_url.c_str()); log_d("API URL: %s", buffer); - server->on(buffer, 0b01111111, [&](AsyncWebServerRequest *request) + server->on("/control", 0b01111111, [&](AsyncWebServerRequest *request) { handleRequest(request); }); server->begin(); diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 36b9ec5..666b942 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -14,8 +14,8 @@ default_envs = esp32Cam ; do not change this value ; The below options are available for all environments ; The ssid and password are requried for the trackers to connect to your network!!! [wifi] -ssid="LoveHouse2G" ; your wifi network name goes here -password="vxwby2Gwtswp" ; your wifi network password goes here +ssid="" ; your wifi network name goes here +password="" ; your wifi network password goes here channel=1 ; wifi channel ap_ssid="EyeTrackVR" ; your AP wifi network name goes here ap_password="test" ; Place your AP Wifi password here diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 12f4502..987971e 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -24,62 +24,62 @@ ProjectConfig deviceConfig; OTA ota(&deviceConfig); LEDManager ledManager(33); CameraHandler cameraHandler(&deviceConfig); -//SerialManager serialManager(&deviceConfig); +// SerialManager serialManager(&deviceConfig); WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, 1); -//APIServer apiServer(CONTROL_SERVER_PORT, &wifiHandler, &cameraHandler, &wifiStateManager, "/control"); +APIServer apiServer(CONTROL_SERVER_PORT, &wifiHandler, &cameraHandler, &wifiStateManager, "/control"); MDNSHandler mdnsHandler(&mdnsStateManager, &deviceConfig); StreamServer streamServer(STREAM_SERVER_PORT); void setup() { - Serial.begin(115200); - Serial.setDebugOutput(true); - ledManager.begin(); - deviceConfig.initConfig(); - deviceConfig.load(); - cameraHandler.setupCamera(); + Serial.begin(115200); + Serial.setDebugOutput(true); + ledManager.begin(); + deviceConfig.initConfig(); + deviceConfig.load(); + cameraHandler.setupCamera(); - wifiHandler._enable_adhoc = ENABLE_ADHOC; + wifiHandler._enable_adhoc = ENABLE_ADHOC; - wifiHandler.setupWifi(); - mdnsHandler.startMDNS(); + wifiHandler.setupWifi(); + mdnsHandler.startMDNS(); - switch (wifiStateManager.getCurrentState()) - { - case WiFiState_e::WiFiState_Disconnected: - { - break; - } - case WiFiState_e::WiFiState_Disconnecting: - { - break; - } - case WiFiState_e::WiFiState_ADHOC: - { - } - case WiFiState_e::WiFiState_Connected: - { - streamServer.startStreamServer(); - //apiServer.begin(); - log_d("[SETUP]: Starting Stream Server"); - break; - } - case WiFiState_e::WiFiState_Connecting: - { - break; - } - case WiFiState_e::WiFiState_Error: - { - break; - } - } - ota.SetupOTA(); + switch (wifiStateManager.getCurrentState()) + { + case WiFiState_e::WiFiState_Disconnected: + { + break; + } + case WiFiState_e::WiFiState_Disconnecting: + { + break; + } + case WiFiState_e::WiFiState_ADHOC: + { + } + case WiFiState_e::WiFiState_Connected: + { + streamServer.startStreamServer(); + apiServer.begin(); + log_d("[SETUP]: Starting Stream Server"); + break; + } + case WiFiState_e::WiFiState_Connecting: + { + break; + } + case WiFiState_e::WiFiState_Error: + { + break; + } + } + ota.SetupOTA(); } void loop() { - ota.HandleOTAUpdate(); - ledManager.displayStatus(); - //apiServer.triggerWifiConfigWrite(); - // serialManager.handleSerial(); + ota.HandleOTAUpdate(); + ledManager.displayStatus(); + apiServer.triggerWifiConfigWrite(); + // serialManager.handleSerial(); } \ No newline at end of file From 88e77cd571cff8b6978c259764a0df6840e18727 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 20 Aug 2022 15:54:11 +0100 Subject: [PATCH 046/153] update - APIServer is now fully functional - APIServer uses REGEX for url parsing --- ESP/lib/src/network/api/utilities/apiUtilities.hpp | 3 --- ESP/lib/src/network/api/webserverHandler.cpp | 12 ++++++------ ESP/platformio.ini | 5 +++-- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index 1edc44e..44d141f 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -41,7 +41,6 @@ protected: void writeFile(fs::FS &fs, std::string path, std::string message); */ std::string shaEncoder(std::string data); std::unordered_map _networkMethodsMap = { - {0, "NULL"}, {0b00000001, "GET"}, {0b00000010, "POST"}, {0b00001000, "PUT"}, @@ -52,7 +51,6 @@ protected: enum RequestMethods { - NULL_METHOD, GET, POST, PUT, @@ -62,7 +60,6 @@ protected: }; std::unordered_map _networkMethodsMap_enum = { - {0, NULL_METHOD}, {0b00000001, GET}, {0b00000010, POST}, {0b00001000, PUT}, diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 78b6283..5c9ced0 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -25,7 +25,7 @@ void APIServer::begin() char buffer[1000]; snprintf(buffer, sizeof(buffer), "^\\%s\\/([a-zA-Z0-9]+)\\/command\\/([a-zA-Z0-9]+)$", this->api_url.c_str()); log_d("API URL: %s", buffer); - server->on("/control", 0b01111111, [&](AsyncWebServerRequest *request) + server->on(buffer, 0b01111111, [&](AsyncWebServerRequest *request) { handleRequest(request); }); server->begin(); @@ -35,11 +35,11 @@ void APIServer::setupServer() { // Set case NULL_METHOD routes routes.emplace("wifi", &APIServer::setWiFi); - routes.emplace("reset_config", &APIServer::factoryReset); - routes.emplace("reboot_device", &APIServer::rebootDevice); - routes.emplace("set_json", &APIServer::handleJson); - routes.emplace("set_camera", &APIServer::setCamera); - routes.emplace("delete_route", &APIServer::deleteRoute); + routes.emplace("resetConfig", &APIServer::factoryReset); + routes.emplace("rebootDevice", &APIServer::rebootDevice); + routes.emplace("setJson", &APIServer::handleJson); + routes.emplace("setCamera", &APIServer::setCamera); + routes.emplace("deleteRoute", &APIServer::deleteRoute); routeHandler("builtin", routes); // add new map to the route map } diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 666b942..819cc8c 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -161,7 +161,7 @@ board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} - +build_type = ${common.build_type} [env:esp32Cam_release] platform = ${common.platform} @@ -243,7 +243,8 @@ lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} -upload_port = COM6 +;upload_port = COM6 +build_type = ${common.build_type} [env:wrover_release] platform = ${common.platform} From 942ecfefec6ae04a9318d98972179bb4a113f5b0 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 22 Aug 2022 15:44:53 +0100 Subject: [PATCH 047/153] update - optimize vector of routes --- ESP/lib/src/network/api/webserverHandler.cpp | 68 +++++++++++--------- ESP/lib/src/network/api/webserverHandler.hpp | 7 +- ESP/platformio.ini | 4 -- 3 files changed, 42 insertions(+), 37 deletions(-) diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 5c9ced0..0db3ff8 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -41,7 +41,9 @@ void APIServer::setupServer() routes.emplace("setCamera", &APIServer::setCamera); routes.emplace("deleteRoute", &APIServer::deleteRoute); - routeHandler("builtin", routes); // add new map to the route map + //! reserve enough memory for all routes - must be called after adding routes and before adding routes to route_map + indexes.reserve(routes.size()); // this is done to avoid reallocation of memory and copying of data + addRouteMap("builtin", routes, indexes); // add new route map to the route_map } void APIServer::findParam(AsyncWebServerRequest *request, const char *param, String &value) @@ -57,59 +59,65 @@ void APIServer::findParam(AsyncWebServerRequest *request, const char *param, Str * * @param index * @param funct - * @return \c vector a list of the indexes of the command handlers + * @param indexes \c std::vector a list of the routes of the command handlers + * + * @return void + * */ -std::vector APIServer::routeHandler(std::string index, route_t route) +void APIServer::addRouteMap(std::string index, route_t route, std::vector &indexes) { route_map.emplace(index, route); - std::vector indexes; - indexes.reserve(route.size()); for (const auto &key : route) { - indexes.push_back(key.first); + indexes.emplace_back(key.first); // add the route to the list of routes - use emplace_back to avoid copying } - - return indexes; } void APIServer::handleRequest(AsyncWebServerRequest *request) { - // Get the route - log_i("Request: %s", request->url().c_str()); - int params = request->params(); - auto it_map = route_map.find(request->pathArg(0).c_str()); - log_i("Request: %s", request->pathArg(0).c_str()); - auto it_method = it_map->second.find(request->pathArg(1).c_str()); - log_i("Request: %s", request->pathArg(1).c_str()); - - for (int i = 0; i < params; i++) + try { - AsyncWebParameter *param = request->getParam(i); + // Get the route + log_i("Request URL: %s", request->url().c_str()); + int params = request->params(); + auto it_map = route_map.find(request->pathArg(0).c_str()); + log_i("Request First Arg: %s", request->pathArg(0).c_str()); + auto it_method = it_map->second.find(request->pathArg(1).c_str()); + log_i("Request Second Arg: %s", request->pathArg(1).c_str()); + + for (int i = 0; i < params; i++) { + AsyncWebParameter *param = request->getParam(i); { - if (it_map != route_map.end()) { - if (it_method != it_map->second.end()) + if (it_map != route_map.end()) { - (*this.*(it_method->second))(request); + if (it_method != it_map->second.end()) + { + (*this.*(it_method->second))(request); + } + else + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Command\"}"); + request->redirect("/"); + return; + } } else { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Command\"}"); + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Map Index\"}"); request->redirect("/"); return; } } - else - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Map Index\"}"); - request->redirect("/"); - return; - } + log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } - log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Command executed\"}"); + } + catch (const std::exception &e) + { + log_e("Error: %s", e.what()); } - request->send(200, MIMETYPE_JSON, "{\"msg\":\"Command executed\"}"); } diff --git a/ESP/lib/src/network/api/webserverHandler.hpp b/ESP/lib/src/network/api/webserverHandler.hpp index 1dd0923..806f6b3 100644 --- a/ESP/lib/src/network/api/webserverHandler.hpp +++ b/ESP/lib/src/network/api/webserverHandler.hpp @@ -16,10 +16,11 @@ public: virtual ~APIServer(); void begin(); void setupServer(); - void findParam(AsyncWebServerRequest *request, const char *param, String &value); - void updateCommandHandlers(); - std::vector routeHandler(std::string index, route_t route); + void addRouteMap(std::string index, route_t route, std::vector &indexes); void handleRequest(AsyncWebServerRequest *request); + +public: + std::vector indexes; }; #endif // WEBSERVERHANDLER_HPP diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 819cc8c..69457ce 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -108,10 +108,6 @@ build_flags = -mfix-esp32-psram-cache-issue - ;-I include - ;-include "pinout.h" ; this has been added for future movement to a proper library structure - ;-include "credentials.h" ; this has been added for future movement to a proper library structure - build_unflags = -Os ; board_build.partitions = min_spiffs.csv board_build.partitions = huge_app.csv From 96cb7885e0cb96a71052f9082b35abecfff80cf5 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 22 Aug 2022 18:36:23 +0100 Subject: [PATCH 048/153] update - Improve performance of vectors --- ESP/backup/WifiHandler/WifiHandler.hpp | 22 -- ESP/backup/WifiHandler/wifiHandler.cpp | 151 ---------- ESP/backup/webserver/webserverHandler.cpp | 271 ------------------ ESP/backup/webserver/webserverHandler.hpp | 108 ------- .../src/data/utilities/enuminheritance.hpp | 9 +- ESP/lib/src/data/utilities/helpers.cpp | 4 +- ESP/lib/src/data/utilities/makeunique.hpp | 5 - .../src/data/utilities/network_utilities.cpp | 5 - .../src/network/WifiHandler/WifiHandler.hpp | 1 + .../src/network/WifiHandler/wifiHandler.cpp | 30 +- 10 files changed, 10 insertions(+), 596 deletions(-) delete mode 100644 ESP/backup/WifiHandler/WifiHandler.hpp delete mode 100644 ESP/backup/WifiHandler/wifiHandler.cpp delete mode 100644 ESP/backup/webserver/webserverHandler.cpp delete mode 100644 ESP/backup/webserver/webserverHandler.hpp diff --git a/ESP/backup/WifiHandler/WifiHandler.hpp b/ESP/backup/WifiHandler/WifiHandler.hpp deleted file mode 100644 index fd77729..0000000 --- a/ESP/backup/WifiHandler/WifiHandler.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -#ifndef WIFIHANDLER_HPP -#define WIFIHANDLER_HPP -#include -#include -#include "data/StateManager/StateManager.hpp" -#include "data/config/project_config.hpp" - -class WiFiHandler -{ -public: - WiFiHandler(ProjectConfig *configManager, StateManager *stateManager); - virtual ~WiFiHandler(); - void setupWifi(); - ProjectConfig *configManager; - StateManager *stateManager; -private: - void setUpADHOC(); - void adhoc(const char *ssid, const char *password, uint8_t channel); - void iniSTA(); -}; -#endif // WIFIHANDLER_HPP diff --git a/ESP/backup/WifiHandler/wifiHandler.cpp b/ESP/backup/WifiHandler/wifiHandler.cpp deleted file mode 100644 index 42e366a..0000000 --- a/ESP/backup/WifiHandler/wifiHandler.cpp +++ /dev/null @@ -1,151 +0,0 @@ -#include "WifiHandler.hpp" -#include - -WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager) : configManager(configManager), - stateManager(stateManager) {} - -WiFiHandler::~WiFiHandler() {} - -void WiFiHandler::setupWifi() -{ - if (ENABLE_ADHOC || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) - { - this->setUpADHOC(); - return; - } - log_i("Initializing connection to wifi"); - stateManager->setState(WiFiState_e::WiFiState_Connecting); - - std::vector *networks = configManager->getWifiConfigs(); - int connection_timeout = 30000; // 30 seconds - - int count = 0; - unsigned long currentMillis = millis(); - unsigned long _previousMillis = currentMillis; - - for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) - { - log_i("Trying to connect to the %s network", networkIterator->ssid); - - WiFi.begin(networkIterator->ssid.c_str(), networkIterator->password.c_str()); - count++; - - if (!WiFi.isConnected()) - log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid); - else - { - log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->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) && count >= networks->size()) - { - 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 saved networks, check your Wifi credentials"); - stateManager->setState(WiFiState_e::WiFiState_Error); - this->iniSTA(); - log_i("[INFO]: Attempting to connect to hardcoded network from ini file"); - return; - } - } - } -} - -void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) -{ - log_i("[INFO]: Setting Access Point...\n"); - - log_i("[INFO]: Configuring access point...\n"); - WiFi.mode(WIFI_AP); - - Serial.printf("\r\nStarting AP. \r\nAP IP address: "); - IPAddress IP = WiFi.softAPIP(); - 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. - WiFi.softAP(ssid, password, channel); // AP mode with password - - WiFi.setTxPower(WIFI_POWER_11dBm); - stateManager->setState(WiFiState_e::WiFiState_ADHOC); -} - -/* -* * -*/ -void WiFiHandler::setUpADHOC() -{ - log_i("[INFO]: Setting Access Point...\n"); - size_t ssidLen = strlen(configManager->getAPWifiConfig()->ssid.c_str()); - size_t passwordLen = strlen(configManager->getAPWifiConfig()->password.c_str()); - char ssid[ssidLen + 1]; - char password[passwordLen + 1]; - uint8_t channel = configManager->getAPWifiConfig()->channel; - if (ssidLen > 0 || passwordLen > 0) - { - 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; - } - - this->adhoc(ssid, password, 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); -} - -void WiFiHandler::iniSTA() -{ - log_i("[INFO]: Setting up station...\n"); - int connection_timeout = 30000; // 30 seconds - unsigned long currentMillis = millis(); - unsigned long _previousMillis = currentMillis; - - log_i("Trying to connect to the %s network", WIFI_SSID); - - WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); - - 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->setUpADHOC(); - log_w("Setting up adhoc mode"); - log_w("Please use adhoc mode and the app to set your WiFi credentials and reboot the device"); - stateManager->setState(WiFiState_e::WiFiState_ADHOC); - return; - } - } -} \ No newline at end of file diff --git a/ESP/backup/webserver/webserverHandler.cpp b/ESP/backup/webserver/webserverHandler.cpp deleted file mode 100644 index b41c5f1..0000000 --- a/ESP/backup/webserver/webserverHandler.cpp +++ /dev/null @@ -1,271 +0,0 @@ -#include "webserverHandler.hpp" - -//! These have to be called before the constructor of the class because they are static -//! C++ 11 does not have inline variables, sadly. So we have to do this. -const char *APIServer::MIMETYPE_HTML{"text/html"}; -// const char *APIServer::MIMETYPE_CSS{"text/css"}; -// const char *APIServer::MIMETYPE_JS{"application/javascript"}; -// const char *APIServer::MIMETYPE_PNG{"image/png"}; -// const char *APIServer::MIMETYPE_JPG{"image/jpeg"}; -// const char *APIServer::MIMETYPE_ICO{"image/x-icon"}; -const char *APIServer::MIMETYPE_JSON{"application/json"}; - -bool APIServer::ssid_write = false; -bool APIServer::pass_write = false; -bool APIServer::channel_write = false; - -//********************************************************************************************* -//! API Server -//********************************************************************************************* - -APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network) : network(network), - server(new AsyncWebServer(CONTROL_PORT)), - cameraHandler(cameraHandler) {} - -void APIServer::startAPIServer() -{ - begin(); - /* this->server->on( - "/control", - HTTP_GET, - 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. - server->on("/", HTTP_GET, [&](AsyncWebServerRequest *request) - { request->send(200); }); - - // preflight cors check - server->on("/", HTTP_OPTIONS, [&](AsyncWebServerRequest *request) - { - AsyncWebServerResponse* response = request->beginResponse(204); - 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-Credentials", "true"); - request->send(response); }); - - DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); - - // std::bind(&APIServer::API_Utilities::notFound, &api_utilities, std::placeholders::_1); - server->onNotFound([&](AsyncWebServerRequest *request) - { api_utilities.notFound(request); }); - // Hex value of BUTT_PLUG_CONTROLLER == 425554545f504c55475f434f4e54524f4c4c4552 - this->server->on("/control", HTTP_GET, [&](AsyncWebServerRequest *request) - { command_handler(request); }); - - log_d("Initializing REST API"); - this->server->begin(); -} - -void APIServer::findParam(AsyncWebServerRequest *request, const char *param, String &value) -{ - if (request->hasParam(param)) - { - value = request->getParam(param)->value(); - } -} - -void APIServer::begin() -{ - command_map_wifi_conf.emplace("ssid", [this](const char *value) -> void - { setSSID(value); }); - command_map_wifi_conf.emplace("password", [this](const char *value) -> void - { setPass(value); }); - command_map_wifi_conf.emplace("channel", [this](const char *value) -> void - { setChannel(value); }); - - command_map_funct.emplace("reboot_device", [this](void) -> void - { rebootDevice(); }); - command_map_funct.emplace("reset_config", [this](void) -> void - { factoryReset(); }); - - command_map_json.emplace("data_json", [this](AsyncWebServerRequest *request) -> void - { setDataJson(request); }); - command_map_json.emplace("config_json", [this](AsyncWebServerRequest *request) -> void - { setConfigJson(request); }); - command_map_json.emplace("settings_json", [this](AsyncWebServerRequest *request) -> void - { setSettingsJson(request); }); -} - -void APIServer::command_handler(AsyncWebServerRequest *request) -{ - int params = request->params(); - for (int i = 0; i < params; 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_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()); - - if (it_wifi_conf != command_map_wifi_conf.end()) - { - command_map_wifi_conf.at(param->name().c_str())(param->value().c_str()); - auto &key_it = it_wifi_conf->first; - log_i("Command %s executed", key_it.c_str()); - } - else if (it_funct != command_map_funct.end()) - { - command_map_funct.at(param->name().c_str())(); - auto &key_it_funct = it_funct->first; - log_i("Command %s executed", key_it_funct.c_str()); - } - else if (it_json != command_map_json.end()) - { - command_map_json.at(param->name().c_str())(request); - auto &key_it_json = it_json->first; - log_i("Command %s executed", key_it_json.c_str()); - } - else - { - log_i("Command not found"); - } - } - log_i("GET[%s]: %s\n", param->name().c_str(), param->value().c_str()); - } -} - -//********************************************************************************************* -//! Command Functions -//********************************************************************************************* -void APIServer::setSSID(const char *value) -{ - if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) - this->wifiConfig.local_WifiConfig[0].ssid = value; - else - this->wifiConfig.local_WifiConfig[1].ssid = value; - ssid_write = true; -} - -void APIServer::setPass(const char *value) -{ - if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) - this->wifiConfig.local_WifiConfig[0].pass = value; - else - this->wifiConfig.local_WifiConfig[1].pass = value; - pass_write = true; -} - -void APIServer::setChannel(const char *value) -{ - if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) - this->wifiConfig.local_WifiConfig[0].channel = atoi(value); - else - this->wifiConfig.local_WifiConfig[1].channel = atoi(value); - 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, wifiConfig.local_WifiConfig[0].adhoc, 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, wifiConfig.local_WifiConfig[1].adhoc, true); - network->configManager->save(); - } -} - -void APIServer::setDataJson(AsyncWebServerRequest *request) -{ - network->configManager->getDeviceConfig()->data_json = true; - api_utilities.my_delay(1L); - String temp = network->configManager->getDeviceConfig()->data_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; -} - -void APIServer::setConfigJson(AsyncWebServerRequest *request) -{ - network->configManager->getDeviceConfig()->config_json = true; - api_utilities.my_delay(1L); - String temp = network->configManager->getDeviceConfig()->config_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; -} - -void APIServer::setSettingsJson(AsyncWebServerRequest *request) -{ - network->configManager->getDeviceConfig()->settings_json = true; - api_utilities.my_delay(1L); - String temp = network->configManager->getDeviceConfig()->settings_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; -} - -void APIServer::rebootDevice() -{ - delay(20000); - ESP.restart(); -} - -void APIServer::factoryReset() -{ - network->configManager->reset(); -} - -//********************************************************************************************* -//! API Utilities -//********************************************************************************************* - -APIServer::API_Utilities::API_Utilities() {} - -std::string APIServer::API_Utilities::shaEncoder(std::string data) -{ - const char *data_c = data.c_str(); - int size = 20; - uint8_t hash[size]; - mbedtls_md_context_t ctx; - mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1; - - const size_t len = strlen(data_c); - mbedtls_md_init(&ctx); - mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); - mbedtls_md_starts(&ctx); - mbedtls_md_update(&ctx, (const unsigned char *)data_c, len); - mbedtls_md_finish(&ctx, hash); - mbedtls_md_free(&ctx); - - std::string hash_string = ""; - for (uint16_t i = 0; i < size; i++) - { - std::string hex = String(hash[i], HEX).c_str(); - if (hex.length() < 2) - { - hex = "0" + hex; - } - hash_string += hex; - } - return hash_string; -} - -void APIServer::API_Utilities::notFound(AsyncWebServerRequest *request) -{ - try - { - log_i("%s", _networkMethodsMap[request->method()]); - } - catch (const std::exception &e) - { - log_i("UNKNOWN"); - } - - log_i(" http://%s%s/\n", request->host().c_str(), request->url().c_str()); - request->send(404, "text/plain", "Not found."); -} - -void APIServer::API_Utilities::my_delay(volatile long delay_time) -{ - delay_time = delay_time * 1e6L; - for (volatile long count = delay_time; count > 0L; count--) - ; -} - -APIServer::API_Utilities api_utilities; \ No newline at end of file diff --git a/ESP/backup/webserver/webserverHandler.hpp b/ESP/backup/webserver/webserverHandler.hpp deleted file mode 100644 index 9473028..0000000 --- a/ESP/backup/webserver/webserverHandler.hpp +++ /dev/null @@ -1,108 +0,0 @@ -#pragma once -#ifndef XWEBSERVERHANDLER_HPP -#define XWEBSERVERHANDLER_HPP -#include -#include - -#define WEBSERVER_H - -#define HTTP_GET 0b00000001 -#define HTTP_POST 0b00000010 -#define HTTP_DELETE 0b00000100 -#define HTTP_PUT 0b00001000 -#define HTTP_PATCH 0b00010000 -#define HTTP_HEAD 0b00100000 -#define HTTP_OPTIONS 0b01000000 -#define HTTP_ANY 0b01111111 - -#include -#include -#include "mbedtls/md.h" -#include "io/camera/cameraHandler.hpp" -#include "network/WifiHandler/WifiHandler.hpp" - -class APIServer -{ -private: - void command_handler(AsyncWebServerRequest *request); - - AsyncWebServer *server; - CameraHandler *cameraHandler; - WiFiHandler *network; - - /* Commands */ - void setSSID(const char *value); - void setPass(const char *value); - void setChannel(const char *value); - - void setDataJson(AsyncWebServerRequest *request); - void setConfigJson(AsyncWebServerRequest *request); - void setSettingsJson(AsyncWebServerRequest *request); - - void factoryReset(); - void rebootDevice(); - - typedef std::function wifi_conf_function; - typedef std::function function; - typedef std::function function_w_request; - - typedef std::unordered_map command_map_funct_t; - typedef std::unordered_map command_map_wifi_conf_t; - typedef std::unordered_map command_map_json_t; - - command_map_funct_t command_map_funct; - command_map_wifi_conf_t command_map_wifi_conf; - command_map_json_t command_map_json; - - static const char *MIMETYPE_HTML; - /* static const char *MIMETYPE_CSS; */ - /* static const char *MIMETYPE_JS; */ - /* static const char *MIMETYPE_PNG; */ - /* static const char *MIMETYPE_JPG; */ - /* static const char *MIMETYPE_ICO; */ - 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; - bool adhoc; - }; - - struct WifiConfig - { - std::vector local_WifiConfig; - }; - - WifiConfig wifiConfig; - -public: - APIServer(int CONTROL_PORT, CameraHandler *cameraHandler, WiFiHandler *network); - void begin(); - void startAPIServer(); - void triggerWifiConfigWrite(); - void findParam(AsyncWebServerRequest *request, const char *param, String &value); - - class API_Utilities - { - public: - API_Utilities(); - void notFound(AsyncWebServerRequest *request); - void my_delay(volatile long delay_time); - std::string shaEncoder(std::string data); - std::unordered_map _networkMethodsMap = { - {HTTP_GET, "GET"}, - {HTTP_POST, "POST"}, - {HTTP_PUT, "PUT"}, - {HTTP_DELETE, "DELETE"}, - {HTTP_PATCH, "PATCH"}, - {HTTP_OPTIONS, "OPTIONS"}, - }; - }; -}; -extern APIServer::API_Utilities api_utilities; -#endif // WEBSERVERHANDLER_HPP diff --git a/ESP/lib/src/data/utilities/enuminheritance.hpp b/ESP/lib/src/data/utilities/enuminheritance.hpp index 75ef21e..b26aecf 100644 --- a/ESP/lib/src/data/utilities/enuminheritance.hpp +++ b/ESP/lib/src/data/utilities/enuminheritance.hpp @@ -10,23 +10,20 @@ public: : enum_(e) { } - InheritEnum(BaseEnumT e) : baseEnum_(e) { } - explicit InheritEnum(int val) : enum_(static_cast(val)) { } - operator EnumT() const { return enum_; } private: - // Note - the value is declared as a union mainly for a debugging aid. If - // the union is undesired and you have other methods of debugging, change it - // to either of EnumT and do a cast for the constructor that accepts BaseEnumT. + //! Note - the value is declared as a union mainly for a debugging aid. If + //! the union is undesired and you have other methods of debugging, change it + //! to either of EnumT and do a cast for the constructor that accepts BaseEnumT. union { EnumT enum_; diff --git a/ESP/lib/src/data/utilities/helpers.cpp b/ESP/lib/src/data/utilities/helpers.cpp index 927f3e9..cb85828 100644 --- a/ESP/lib/src/data/utilities/helpers.cpp +++ b/ESP/lib/src/data/utilities/helpers.cpp @@ -36,7 +36,7 @@ void split(std::string str, std::string splitBy, std::vector &token { /* Store the original string in the array, so we can loop the rest * of the algorithm. */ - tokens.push_back(str); + tokens.emplace_back(str); // Store the split index in a 'size_t' (unsigned integer) type. size_t splitAt; @@ -63,7 +63,7 @@ void split(std::string str, std::string splitBy, std::vector &token tokens.back() = frag.substr(0, splitAt); /* Push everything from the right side of the split to the next empty * index in the vector. */ - tokens.push_back(frag.substr(splitAt + splitLen, frag.size() - (splitAt + splitLen))); + tokens.emplace_back(frag.substr(splitAt + splitLen, frag.size() - (splitAt + splitLen))); } } diff --git a/ESP/lib/src/data/utilities/makeunique.hpp b/ESP/lib/src/data/utilities/makeunique.hpp index f5d250c..3b33374 100644 --- a/ESP/lib/src/data/utilities/makeunique.hpp +++ b/ESP/lib/src/data/utilities/makeunique.hpp @@ -20,26 +20,22 @@ namespace std { typedef unique_ptr _Single_object; }; - template struct _Unique_if { typedef unique_ptr _Unknown_bound; }; - template struct _Unique_if { typedef void _Known_bound; }; - template typename _Unique_if::_Single_object make_unique(Args &&...args) { return unique_ptr(new T(std::forward(args)...)); } - template typename _Unique_if::_Unknown_bound make_unique(size_t n) @@ -47,7 +43,6 @@ namespace std typedef typename remove_extent::type U; return unique_ptr(new U[n]()); } - template typename _Unique_if::_Known_bound make_unique(Args &&...) = delete; diff --git a/ESP/lib/src/data/utilities/network_utilities.cpp b/ESP/lib/src/data/utilities/network_utilities.cpp index f8467cc..7a55b8b 100644 --- a/ESP/lib/src/data/utilities/network_utilities.cpp +++ b/ESP/lib/src/data/utilities/network_utilities.cpp @@ -6,7 +6,6 @@ void Network_Utilities::SetupWifiScan() WiFi.mode(WIFI_STA); WiFi.disconnect(); // Disconnect from the access point if connected before delay(100); - Serial.println("Setup done"); } @@ -16,7 +15,6 @@ bool Network_Utilities::LoopWifiScan() log_i("[INFO]: Beginning WiFi Scanner"); int networks = WiFi.scanNetworks(); log_i("[INFO]: scan done"); - log_i("%d networks found", networks); for (int i = networks; i--;) { @@ -25,7 +23,6 @@ bool Network_Utilities::LoopWifiScan() log_i("%d: %s (%d) %s\n", i - 1, WiFi.SSID(i), WiFi.RSSI(i), (WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*"); my_delay(0.02L); // delay 20ms } - // Wait a bit before scanning again delay(5000); return (networks > 0); @@ -35,13 +32,11 @@ bool Network_Utilities::LoopWifiScan() int Network_Utilities::getStrength(int points) // TODO: add to JSON doc { int32_t rssi = 0, averageRSSI = 0; - for (int i = 0; i < points; i++) { rssi += WiFi.RSSI(); delay(20); } - averageRSSI = rssi / points; return averageRSSI; } diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 8ce2866..0ffa154 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -6,6 +6,7 @@ #include #include "data/StateManager/StateManager.hpp" #include "data/config/project_config.hpp" +#include "data/utilities/makeunique.hpp" class WiFiHandler { diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index b93879e..df9de3c 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -65,32 +65,22 @@ void WiFiHandler::setupWifi() return; } } - if (!WiFi.isConnected()) - log_i("\n\rCould not connect to %s, trying another network\n\r", networkIterator->ssid); - else - { - log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid); - stateManager->setState(WiFiState_e::WiFiState_Connected); - return; - } + log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid); + stateManager->setState(WiFiState_e::WiFiState_Connected); } } void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) { log_i("[INFO]: Setting Access Point...\n"); - log_i("[INFO]: Configuring access point...\n"); WiFi.mode(WIFI_AP); - Serial.printf("\r\nStarting AP. \r\nAP IP address: "); IPAddress IP = WiFi.softAPIP(); 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. WiFi.softAP(ssid, password, channel); // AP mode with password WiFi.setTxPower(WIFI_POWER_11dBm); - stateManager->setState(WiFiState_e::WiFiState_ADHOC); } @@ -117,9 +107,7 @@ void WiFiHandler::setUpADHOC() strcpy(password, "12345678"); channel = 1; } - this->adhoc(ssid, password, channel); - log_i("[INFO]: Configuring access point...\n"); log_d("[DEBUG]: ssid: %s\n", ssid); log_d("[DEBUG]: password: %s\n", password); @@ -132,9 +120,7 @@ void WiFiHandler::iniSTA() int connection_timeout = 30000; // 30 seconds unsigned long currentMillis = millis(); unsigned long _previousMillis = currentMillis; - log_i("Trying to connect to the %s network", this->ssid.c_str()); - // check size of networks if (this->ssid.size() == 0) { @@ -144,7 +130,6 @@ void WiFiHandler::iniSTA() return; } WiFi.begin(this->ssid.c_str(), this->password.c_str(), this->channel); - while (WiFi.status() != WL_CONNECTED) { stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting); @@ -164,13 +149,6 @@ void WiFiHandler::iniSTA() return; } } - - if (!WiFi.isConnected()) - log_i("\n\rCould not connect to %s, please try another network\n\r", this->ssid.c_str()); - else - { - log_i("\n\rSuccessfully connected to %s\n\r", this->ssid.c_str()); - stateManager->setState(WiFiState_e::WiFiState_Connected); - return; - } + log_i("\n\rSuccessfully connected to %s\n\r", this->ssid.c_str()); + stateManager->setState(WiFiState_e::WiFiState_Connected); } From 110bab0b28a250517690797b312240b03b218778 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 22 Aug 2022 23:04:16 +0100 Subject: [PATCH 049/153] update - Added cool progress bar - lol --- ESP/lib/src/data/utilities/helpers.cpp | 19 +++++++++ ESP/lib/src/data/utilities/helpers.hpp | 2 + .../src/network/WifiHandler/WifiHandler.hpp | 2 +- .../src/network/WifiHandler/wifiHandler.cpp | 41 ++++++++++--------- ESP/platformio.ini | 2 +- 5 files changed, 45 insertions(+), 21 deletions(-) diff --git a/ESP/lib/src/data/utilities/helpers.cpp b/ESP/lib/src/data/utilities/helpers.cpp index cb85828..cdd6608 100644 --- a/ESP/lib/src/data/utilities/helpers.cpp +++ b/ESP/lib/src/data/utilities/helpers.cpp @@ -77,4 +77,23 @@ std::vector Helpers::split(const std::string &s, char delimiter) parts.push_back(part); } return parts; +} + +void Helpers::update_progress_bar(int progress, int total) +{ + int barWidth = 70; + + std::cout << "\r["; + int pos = barWidth * progress / total; + for (int i = 0; i < barWidth; ++i) + { + if (i < pos) + std::cout << "="; + else if (i == pos) + std::cout << ">"; + else + std::cout << " "; + } + std::cout << "] " << int(progress * 100.0 / total) << " %\r"; + std::cout.flush(); } \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/helpers.hpp b/ESP/lib/src/data/utilities/helpers.hpp index 058d73c..f9dc835 100644 --- a/ESP/lib/src/data/utilities/helpers.hpp +++ b/ESP/lib/src/data/utilities/helpers.hpp @@ -1,10 +1,12 @@ #include #include #include +#include namespace Helpers { char *itoa(int value, char *result, int base); void split(std::string str, std::string splitBy, std::vector &tokens); std::vector split(const std::string &s, char delimiter); + void update_progress_bar(int progress, int total); } \ No newline at end of file diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 0ffa154..686c35a 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -6,7 +6,7 @@ #include #include "data/StateManager/StateManager.hpp" #include "data/config/project_config.hpp" -#include "data/utilities/makeunique.hpp" +#include "data/utilities/helpers.hpp" class WiFiHandler { diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index df9de3c..9fbce9d 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -28,7 +28,7 @@ void WiFiHandler::setupWifi() std::vector *networks = configManager->getWifiConfigs(); // check size of networks - if (networks->size() == 0) + if (networks->empty()) { log_e("No networks found in config"); this->iniSTA(); @@ -41,7 +41,7 @@ void WiFiHandler::setupWifi() int count = 0; unsigned long currentMillis = millis(); unsigned long _previousMillis = currentMillis; - + int progress = 0; for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) { log_i("Trying to connect to the %s network", networkIterator->ssid); @@ -49,18 +49,19 @@ void WiFiHandler::setupWifi() count++; while (WiFi.status() != WL_CONNECTED) - { + { + progress++; stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting); currentMillis = millis(); - Serial.print("."); - delay(300); + Helpers::update_progress_bar(progress, 100); + delay(301); if (((currentMillis - _previousMillis) >= connection_timeout) && count >= networks->size()) { - log_i("[INFO]: WiFi connection timed out.\n"); + log_i("\n[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 saved networks, check your Wifi credentials"); + log_e("\nCould not connect to any of the saved networks, check your Wifi credentials"); stateManager->setState(WiFiState_e::WiFiState_Disconnected); - log_i("[INFO]: Attempting to connect to hardcoded network"); + log_i("\n[INFO]: Attempting to connect to hardcoded network"); this->iniSTA(); return; } @@ -72,8 +73,8 @@ void WiFiHandler::setupWifi() void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) { - log_i("[INFO]: Setting Access Point...\n"); - log_i("[INFO]: Configuring access point...\n"); + log_i("\n[INFO]: Setting Access Point...\n"); + log_i("\n[INFO]: Configuring access point...\n"); WiFi.mode(WIFI_AP); Serial.printf("\r\nStarting AP. \r\nAP IP address: "); IPAddress IP = WiFi.softAPIP(); @@ -89,7 +90,7 @@ void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) */ void WiFiHandler::setUpADHOC() { - log_i("[INFO]: Setting Access Point...\n"); + log_i("\n[INFO]: Setting Access Point...\n"); size_t ssidLen = strlen(configManager->getAPWifiConfig()->ssid.c_str()); size_t passwordLen = strlen(configManager->getAPWifiConfig()->password.c_str()); char ssid[ssidLen + 1]; @@ -108,18 +109,19 @@ void WiFiHandler::setUpADHOC() channel = 1; } this->adhoc(ssid, password, 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); + log_i("\n[INFO]: Configuring access point...\n"); + log_d("\n[DEBUG]: ssid: %s\n", ssid); + log_d("\n[DEBUG]: password: %s\n", password); + log_d("\n[DEBUG]: channel: %d\n", channel); } void WiFiHandler::iniSTA() { - log_i("[INFO]: Setting up station...\n"); + log_i("\n[INFO]: Setting up station...\n"); int connection_timeout = 30000; // 30 seconds unsigned long currentMillis = millis(); unsigned long _previousMillis = currentMillis; + int progress = 0; log_i("Trying to connect to the %s network", this->ssid.c_str()); // check size of networks if (this->ssid.size() == 0) @@ -129,16 +131,17 @@ void WiFiHandler::iniSTA() stateManager->setState(WiFiState_e::WiFiState_Error); return; } + WiFi.begin(this->ssid.c_str(), this->password.c_str(), this->channel); while (WiFi.status() != WL_CONNECTED) { stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting); currentMillis = millis(); - Serial.print("."); - delay(300); + Helpers::update_progress_bar(progress, 100); + delay(301); if ((currentMillis - _previousMillis) >= connection_timeout) { - log_i("[INFO]: WiFi connection timed out.\n"); + log_i("\n[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); diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 69457ce..7a603a5 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -21,7 +21,7 @@ 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 OTAServerPort=3232 -enableADHOC=1 ; 0 = disable, 1 = enable +enableADHOC=0 ; 0 = disable, 1 = enable adhocChannel=1 ; channel to use for adhoc network ; DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING From 3d6f8827a80491816a012e574b3c24bcb73b2ff5 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 23 Aug 2022 00:04:25 +0100 Subject: [PATCH 050/153] hehe update - Fix pathing issues with Utilities classes - Adding really nice ASCII art for boot image :) --- ESP/data/ascii.txt | 60 +++++++++++++ ESP/lib/src/data/utilities/helpers.cpp | 2 +- .../src/data/utilities/network_utilities.hpp | 3 +- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 1 + .../network/api/utilities/apiUtilities.cpp | 85 +++++++++++++++++-- .../network/api/utilities/apiUtilities.hpp | 9 +- ESP/src/main.cpp | 8 +- 7 files changed, 152 insertions(+), 16 deletions(-) create mode 100644 ESP/data/ascii.txt diff --git a/ESP/data/ascii.txt b/ESP/data/ascii.txt new file mode 100644 index 0000000..c515e2a --- /dev/null +++ b/ESP/data/ascii.txt @@ -0,0 +1,60 @@ + : === WELCOME === TO === : + =========================================================================================================================== + ██████╗ ██████╗ ███████╗███╗ ██╗██╗██████╗ ██╗███████╗ + ██╔═══██╗██╔══██╗██╔════╝████╗ ██║██║██╔══██╗██║██╔════╝ + ██║ ██║██████╔╝█████╗ ██╔██╗ ██║██║██████╔╝██║███████╗ + ██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║██║██╔══██╗██║╚════██║ + ╚██████╔╝██║ ███████╗██║ ╚████║██║██║ ██║██║███████║ + ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝╚═╝╚═╝ ╚═╝╚═╝╚══════╝ + + ██████████████ + ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░▒▒▓▓▓▓██ + ████▓▓░░░░▒▒░░░░░░▒▒░░░░░░▒▒░░████ + ██▓▓▒▒▓▓▓▓▒▒▒▒░░░░░░▒▒░░▒▒░░░░░░▒▒░░▒▒▓▓▓▓ + ██▓▓▒▒▒▒▒▒▒▒░░▒▒░░░░░░░░░░░░▒▒░░░░▒▒░░░░▒▒░░██ + ██▓▓▓▓░░░░▒▒░░░░▒▒▒▒░░░░░░░░░░▒▒░░ ░░░░░░░░▒▒░░██ + ██▓▓▓▓▓▓▓▓▓▓░░░░░░▒▒░░░░░░░░░░░░░░ ░░░░░░░░░░░░██ + ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░░░ ░░ ▒▒▒▒██ + ██▓▓▒▒▒▒▒▒▒▒░░░░▒▒░░░░░░░░░░░░░░░░░░ ░░░░██ + ▓▓▓▓▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░░░░░░░░░▓▓▓▓▓▓▓▓▓▓ ░░ ▒▒▓▓ + ██▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓▓▓ ░░██ + ▓▓▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░ ▓▓▒▒▒▒▒▒▒▒░░░░▒▒▒▒▓▓▒▒ ░░▒▒▓▓ + ██▓▓▒▒░░░░░░▒▒▒▒▒▒░░░░░░░░░░░░░░░░▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░▒▒▓▓▓▓ ░░██ + ██▓▓▓▓▒▒▒▒▒▒▒▒░░░░▒▒░░░░░░░░░░░░ ▒▒▒▒▒▒▒▒▒▒▒▒████▓▓░░░░▒▒▓▓ ░░██ + ██▓▓▒▒▒▒▒▒▓▓▒▒▓▓░░░░░░░░░░░░░░░░░░▓▓▒▒▒▒░░▒▒▒▒████ ▒▒██░░▒▒▓▓▓▓ ░░██ + ██▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▓▓░░▒▒▒▒▒▒██████▒▒ ▓▓▓▓░░▓▓▓▓ ░░██ + ██▓▓▒▒▒▒░░▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▓▓▒▒░░▒▒░░████████▓▓ ██▓▓▒▒▓▓ ░░██ + ██▓▓▓▓▓▓▓▓▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░▒▒░░▒▒░░▒▒██████████▒▒██▒▒▒▒▓▓ ░░██ + ██▓▓▒▒▒▒▒▒░░░░░░░░▒▒▒▒░░░░░░░░░░░░▒▒▒▒░░░░▒▒██▒▒██████ ██▒▒▒▒▓▓ ░░██ + ██▒▒▒▒▒▒░░▓▓▓▓▓▓▒▒░░░░░░░░░░░░░░░░▒▒░░ ▒▒░░██ ▒▒████▒▒██▒▒▒▒▓▓ ░░██ + ██▓▓▓▓▓▓▓▓░░▒▒▒▒░░▒▒░░░░░░░░░░░░░░▒▒▒▒░░░░░░▒▒██ ██████▒▒▒▒▒▒▓▓░░░░██ + ██▓▓██▓▓▒▒▒▒▓▓░░░░▒▒░░░░░░░░░░░░░░░░░░▒▒▒▒░░▒▒░░▒▒██████▒▒▒▒▒▒▓▓ ░░██ + ██▓▓██▒▒▒▒▒▒▒▒▓▓▓▓▒▒░░░░░░░░░░░░░░░░░░▒▒░░▒▒░░▒▒░░▒▒░░▒▒▒▒▒▒▒▒▓▓░░░░██ + ██▒▒▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░▒▒░░▒▒░░░░░░▒▒▒▒▒▒▒▒▓▓ ░░░░██ + ██▒▒▒▒▓▓██▓▓▓▓▒▒▒▒▒▒▒▒░░░░░░░░▒▒░░░░░░░░░░░░▒▒▒▒▒▒░░▒▒▒▒▒▒▓▓▓▓ ░░░░██ + ▓▓▓▓▒▒▒▒▓▓██▓▓▒▒▒▒▒▒░░░░▒▒▒▒░░▒▒░░░░░░░░░░░░░░░░░░▒▒▒▒▓▓▓▓▓▓░░░░░░░░▒▒██ + ██▒▒▒▒▓▓▒▒▓▓██▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░░░██ + ██▒▒▒▒▓▓░░▒▒▒▒██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▒▒░░▒▒██ + ██▒▒▒▒▓▓▒▒░░▓▓▒▒██▓▓▒▒▒▒▒▒▒▒░░▓▓▒▒▓▓▒▒░░░░▒▒░░░░░░░░░░░░░░░░░░░░░░▓▓██ + ██▒▒▒▒▒▒░░▒▒▒▒▒▒▓▓██▓▓▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▓▓░░░░░░░░░░▒▒░░░░▒▒░░▒▒▒▒██ + ██▒▒▒▒░░▒▒░░▒▒████ ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░▓▓▒▒▒▒▒▒▓▓▒▒██ + ██▒▒▓▓░░▒▒░░▓▓ ████▓▓▒▒▓▓▒▒▒▒▒▒░░▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒██▓▓ + ██▒▒▒▒▒▒▒▒ ██ ████▓▓▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒████ + ██▒▒▒▒▒▒▒▒░░██ ██████▓▓▒▒▒▒▒▒▒▒▓▓▓▓██████ + ██▒▒▒▒▒▒▒▒░░ ████ ██████████████ + ██▒▒▒▒▒▒▒▒░░ ░░████ + ████▒▒▒▒▒▒░░░░ ░░████ + ████▒▒▒▒▒▒░░░░ ░░██ + ████▒▒▒▒▒▒░░ ░░██ + ██▓▓▒▒▒▒░░ ▒▒▓▓ + ████▒▒░░ ▒▒██ + ▓▓▒▒░░░░██ + ██░░ ██ + ▓▓██ ██░░░░██ + ██░░██ ██░░░░██ + ██░░██ ██░░▒▒██ + ██░░▒▒████░░▒▒██ + ▓▓▒▒▒▒▒▒▒▒▓▓ + ████████ + + ============================================================================================================================ \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/helpers.cpp b/ESP/lib/src/data/utilities/helpers.cpp index cdd6608..4c24f26 100644 --- a/ESP/lib/src/data/utilities/helpers.cpp +++ b/ESP/lib/src/data/utilities/helpers.cpp @@ -96,4 +96,4 @@ void Helpers::update_progress_bar(int progress, int total) } std::cout << "] " << int(progress * 100.0 / total) << " %\r"; std::cout.flush(); -} \ No newline at end of file +} diff --git a/ESP/lib/src/data/utilities/network_utilities.hpp b/ESP/lib/src/data/utilities/network_utilities.hpp index bcb2fe4..972f25c 100644 --- a/ESP/lib/src/data/utilities/network_utilities.hpp +++ b/ESP/lib/src/data/utilities/network_utilities.hpp @@ -2,7 +2,7 @@ #ifndef UTILITIES_hpp #define UTILITIES_hpp #include -#include "network/wifihandler/WifiHandler.hpp" +#include #include namespace Network_Utilities { @@ -11,6 +11,5 @@ namespace Network_Utilities void my_delay(volatile long delay_time); int CheckWifiState(); int getStrength(int points); - String generateDeviceID(); } #endif // !UTILITIES_hpp \ No newline at end of file diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index c8efd36..3e3c994 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -2,6 +2,7 @@ #define BASEAPI_HPP #include "network/wifihandler/wifiHandler.hpp" #include "network/api/utilities/apiUtilities.hpp" +#include "data/utilities/network_utilities.hpp" class BaseAPI : public API_Utilities { diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index 764d6b3..42c8ee0 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -72,8 +72,19 @@ void API_Utilities::notFound(AsyncWebServerRequest *request) const } } +/* bool API_Utilities::initSPIFFS() +{ + if (!SPIFFS.begin(false)) + { + log_e("An error has occurred while mounting SPIFFS"); + return false; + } + log_i("SPIFFS mounted successfully"); + return true; +} */ + // Read File from SPIFFS -/* String API_Utilities::readFile(fs::FS &fs, std::string path) +/* std::string API_Utilities::readFile(fs::FS &fs, std::string path) { log_i("Reading file: %s\r\n", path.c_str()); @@ -81,20 +92,84 @@ void API_Utilities::notFound(AsyncWebServerRequest *request) const if (!file || file.isDirectory()) { log_e("[INFO]: Failed to open file for reading"); - return String(); + return std::string(); } - String fileContent; + std::string fileContent; while (file.available()) { - fileContent = file.readStringUntil('\n'); + fileContent = file.readStringUntil('#').c_str(); break; } return fileContent; +} */ + +void API_Utilities::printASCII() +{ + Serial.println(F(" : === WELCOME === TO === : ")); + Serial.println(F(" <===========================================================================================================================> ")); + Serial.println(F(" ██████╗ ██████╗ ███████╗███╗ ██╗██╗██████╗ ██╗███████╗ ")); + Serial.println(F(" ██╔═══██╗██╔══██╗██╔════╝████╗ ██║██║██╔══██╗██║██╔════╝ ")); + Serial.println(F(" ██║ ██║██████╔╝█████╗ ██╔██╗ ██║██║██████╔╝██║███████╗ ")); + Serial.println(F(" ██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║██║██╔══██╗██║╚════██║ ")); + Serial.println(F(" ╚██████╔╝██║ ███████╗██║ ╚████║██║██║ ██║██║███████║ ")); + Serial.println(F(" ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝╚═╝╚═╝ ╚═╝╚═╝╚══════╝ ")); + Serial.println(F(" ")); + Serial.println(F(" ██████████████ ")); + Serial.println(F(" ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░▒▒▓▓▓▓██ ")); + Serial.println(F(" ████▓▓░░░░▒▒░░░░░░▒▒░░░░░░▒▒░░████ ")); + Serial.println(F(" ██▓▓▒▒▓▓▓▓▒▒▒▒░░░░░░▒▒░░▒▒░░░░░░▒▒░░▒▒▓▓▓▓ ")); + Serial.println(F(" ██▓▓▒▒▒▒▒▒▒▒░░▒▒░░░░░░░░░░░░▒▒░░░░▒▒░░░░▒▒░░██ ")); + Serial.println(F(" ██▓▓▓▓░░░░▒▒░░░░▒▒▒▒░░░░░░░░░░▒▒░░ ░░░░░░░░▒▒░░██ ")); + Serial.println(F(" ██▓▓▓▓▓▓▓▓▓▓░░░░░░▒▒░░░░░░░░░░░░░░ ░░░░░░░░░░░░██ ")); + Serial.println(F(" ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░░░ ░░ ▒▒▒▒██ ")); + Serial.println(F(" ██▓▓▒▒▒▒▒▒▒▒░░░░▒▒░░░░░░░░░░░░░░░░░░ ░░░░██ ")); + Serial.println(F(" ▓▓▓▓▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░░░░░░░░░▓▓▓▓▓▓▓▓▓▓ ░░ ▒▒▓▓ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓▓▓ ░░██ ")); + Serial.println(F(" ▓▓▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░ ▓▓▒▒▒▒▒▒▒▒░░░░▒▒▒▒▓▓▒▒ ░░▒▒▓▓ ")); + Serial.println(F(" ██▓▓▒▒░░░░░░▒▒▒▒▒▒░░░░░░░░░░░░░░░░▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░▒▒▓▓▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▓▓▒▒▒▒▒▒▒▒░░░░▒▒░░░░░░░░░░░░ ▒▒▒▒▒▒▒▒▒▒▒▒████▓▓░░░░▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▒▒▒▒▒▒▓▓▒▒▓▓░░░░░░░░░░░░░░░░░░▓▓▒▒▒▒░░▒▒▒▒████ ▒▒██░░▒▒▓▓▓▓ ░░██ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▓▓░░▒▒▒▒▒▒██████▒▒ ▓▓▓▓░░▓▓▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▒▒▒▒░░▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▓▓▒▒░░▒▒░░████████▓▓ ██▓▓▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▓▓▓▓▓▓▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░▒▒░░▒▒░░▒▒██████████▒▒██▒▒▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▒▒▒▒▒▒░░░░░░░░▒▒▒▒░░░░░░░░░░░░▒▒▒▒░░░░▒▒██▒▒██████ ██▒▒▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▒▒▒▒▒▒░░▓▓▓▓▓▓▒▒░░░░░░░░░░░░░░░░▒▒░░ ▒▒░░██ ▒▒████▒▒██▒▒▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▓▓▓▓▓▓░░▒▒▒▒░░▒▒░░░░░░░░░░░░░░▒▒▒▒░░░░░░▒▒██ ██████▒▒▒▒▒▒▓▓░░░░██ ")); + Serial.println(F(" ██▓▓██▓▓▒▒▒▒▓▓░░░░▒▒░░░░░░░░░░░░░░░░░░▒▒▒▒░░▒▒░░▒▒██████▒▒▒▒▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▓▓██▒▒▒▒▒▒▒▒▓▓▓▓▒▒░░░░░░░░░░░░░░░░░░▒▒░░▒▒░░▒▒░░▒▒░░▒▒▒▒▒▒▒▒▓▓░░░░██ ")); + Serial.println(F(" ██▒▒▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░▒▒░░▒▒░░░░░░▒▒▒▒▒▒▒▒▓▓ ░░░░██ ")); + Serial.println(F(" ██▒▒▒▒▓▓██▓▓▓▓▒▒▒▒▒▒▒▒░░░░░░░░▒▒░░░░░░░░░░░░▒▒▒▒▒▒░░▒▒▒▒▒▒▓▓▓▓ ░░░░██ ")); + Serial.println(F(" ▓▓▓▓▒▒▒▒▓▓██▓▓▒▒▒▒▒▒░░░░▒▒▒▒░░▒▒░░░░░░░░░░░░░░░░░░▒▒▒▒▓▓▓▓▓▓░░░░░░░░▒▒██ ")); + Serial.println(F(" ██▒▒▒▒▓▓▒▒▓▓██▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░░░██ ")); + Serial.println(F(" ██▒▒▒▒▓▓░░▒▒▒▒██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▒▒░░▒▒██ ")); + Serial.println(F(" ██▒▒▒▒▓▓▒▒░░▓▓▒▒██▓▓▒▒▒▒▒▒▒▒░░▓▓▒▒▓▓▒▒░░░░▒▒░░░░░░░░░░░░░░░░░░░░░░▓▓██ ")); + Serial.println(F(" ██▒▒▒▒▒▒░░▒▒▒▒▒▒▓▓██▓▓▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▓▓░░░░░░░░░░▒▒░░░░▒▒░░▒▒▒▒██ ")); + Serial.println(F(" ██▒▒▒▒░░▒▒░░▒▒████ ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░▓▓▒▒▒▒▒▒▓▓▒▒██ ")); + Serial.println(F(" ██▒▒▓▓░░▒▒░░▓▓ ████▓▓▒▒▓▓▒▒▒▒▒▒░░▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒██▓▓ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒ ██ ████▓▓▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒████ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒░░██ ██████▓▓▒▒▒▒▒▒▒▒▓▓▓▓██████ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒░░ ████ ██████████████ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒░░ ░░████ ")); + Serial.println(F(" ████▒▒▒▒▒▒░░░░ ░░████ ")); + Serial.println(F(" ████▒▒▒▒▒▒░░░░ ░░██ ")); + Serial.println(F(" ████▒▒▒▒▒▒░░ ░░██ ")); + Serial.println(F(" ██▓▓▒▒▒▒░░ ▒▒▓▓ ")); + Serial.println(F(" ████▒▒░░ ▒▒██ ")); + Serial.println(F(" ▓▓▒▒░░░░██ ")); + Serial.println(F(" ██░░ ██ ")); + Serial.println(F(" ▓▓██ ██░░░░██ ")); + Serial.println(F(" ██░░██ ██░░░░██ ")); + Serial.println(F(" ██░░██ ██░░▒▒██ ")); + Serial.println(F(" ██░░▒▒████░░▒▒██ ")); + Serial.println(F(" ▓▓▒▒▒▒▒▒▒▒▓▓ ")); + Serial.println(F(" ████████ ")); + Serial.println(F(" ")); + Serial.println(F(" <============================================================================================================================> ")); } // Write file to SPIFFS -void API_Utilities::writeFile(fs::FS &fs, std::string path, std::string message) +/* void API_Utilities::writeFile(fs::FS &fs, std::string path, std::string message) { log_i("[Writing File]: Writing file: %s\r\n", path); Network_Utilities::my_delay(0.1L); diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index 44d141f..7565711 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -20,8 +20,9 @@ #include #include +//#include #include "mbedtls/md.h" -#include "data/utilities/network_utilities.hpp" +#include "network/wifihandler/WifiHandler.hpp" #include "data/StateManager/StateManager.hpp" #include "io/camera/cameraHandler.hpp" @@ -35,10 +36,12 @@ public: std::string api_url); virtual ~API_Utilities(); + static void printASCII(); + //static bool initSPIFFS(); protected: void notFound(AsyncWebServerRequest *request) const; - /* String readFile(fs::FS &fs, std::string path); - void writeFile(fs::FS &fs, std::string path, std::string message); */ + //static std::string readFile(fs::FS &fs, std::string path); + // void writeFile(fs::FS &fs, std::string path, std::string message); std::string shaEncoder(std::string data); std::unordered_map _networkMethodsMap = { {0b00000001, "GET"}, diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 987971e..f001f68 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -15,11 +15,6 @@ int STREAM_SERVER_PORT = 80; int CONTROL_SERVER_PORT = 81; -//! Create smart pointers to the various classes that will be used in the program to make sure that they are deleted when the program ends -//! This is done to make sure that the memory is freed when the program ends and we are not left with dangling pointers to memory that is no longer in use -//! Make unique is a templated function that takes a class and returns a unique pointer to that class - -//! it is used to create a unique pointer to a class and ensure exception safety - ProjectConfig deviceConfig; OTA ota(&deviceConfig); LEDManager ledManager(33); @@ -34,6 +29,9 @@ void setup() { Serial.begin(115200); Serial.setDebugOutput(true); + Serial.println("\n"); + API_Utilities::printASCII(); + ledManager.begin(); deviceConfig.initConfig(); deviceConfig.load(); From 1127f3d767365cb8cc8400460d05680ad9f6ddec Mon Sep 17 00:00:00 2001 From: DaOfficialWizard <45744329+ZanzyTHEbar@users.noreply.github.com> Date: Tue, 23 Aug 2022 01:05:51 +0100 Subject: [PATCH 051/153] Update apiUtilities.cpp --- .../src/network/api/utilities/apiUtilities.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index 42c8ee0..30f50da 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -19,14 +19,14 @@ bool API_Utilities::channel_write = false; //********************************************************************************************* API_Utilities::API_Utilities(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - std::string api_url) : server(new AsyncWebServer(CONTROL_PORT)), - stateManager(stateManager), - network(network), - camera(camera), - api_url(api_url) {} + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url) : server(new AsyncWebServer(CONTROL_PORT)), + stateManager(stateManager), + network(network), + camera(camera), + api_url(api_url) {} API_Utilities::~API_Utilities() {} std::string API_Utilities::shaEncoder(std::string data) { From 2ea338d0cd3175f25cdcf1afb4bc08d639849552 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 24 Aug 2022 18:24:41 +0100 Subject: [PATCH 052/153] update - Disable Brownout detection - Begin adding camera settings handlers to API - fix ADHOC stream server issue --- ESP/lib/src/io/camera/cameraHandler.cpp | 22 +++ ESP/lib/src/io/camera/cameraHandler.hpp | 1 + .../src/network/WifiHandler/wifiHandler.cpp | 2 +- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 134 ++++++++++++++++++ ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 12 +- ESP/lib/src/network/api/webserverHandler.cpp | 5 +- ESP/lib/src/network/stream/streamServer.cpp | 2 +- ESP/lib/src/network/stream/streamServer.hpp | 10 +- ESP/src/main.cpp | 2 - 9 files changed, 182 insertions(+), 8 deletions(-) diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index f833f88..a684d61 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -118,4 +118,26 @@ int CameraHandler::setVFlip(int direction) int CameraHandler::setHFlip(int direction) { return camera_sensor->set_hmirror(camera_sensor, direction); +} + +//! either hardware(1) or software(0) +// TODO: Add to API +void CameraHandler::resetCamera(bool type) +{ + if (type == 1) + { + // power cycle the camera module (handy if camera stops responding) + digitalWrite(PWDN_GPIO_NUM, HIGH); // turn power off to camera module + delay(300); + digitalWrite(PWDN_GPIO_NUM, LOW); + delay(300); + setupCamera(); + } + else + { + // reset via software (handy if you wish to change resolution or image type etc. - see test procedure) + esp_camera_deinit(); + delay(50); + setupCamera(); + } } \ No newline at end of file diff --git a/ESP/lib/src/io/camera/cameraHandler.hpp b/ESP/lib/src/io/camera/cameraHandler.hpp index 3471077..47d2440 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -19,4 +19,5 @@ public: int setHFlip(int direction); int setVieWindow(int offsetX, int offsetY, int outputX, int outputY); void update(ObserverEvent::Event event); + void resetCamera(bool type = 0); }; diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 9fbce9d..a56a11d 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -127,8 +127,8 @@ void WiFiHandler::iniSTA() if (this->ssid.size() == 0) { log_e("No networks passed into the constructor"); - this->setUpADHOC(); stateManager->setState(WiFiState_e::WiFiState_Error); + this->setUpADHOC(); return; } diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index f303e60..7558448 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -294,4 +294,138 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) break; } } +} + +//! TODO: Optimize this!! +void BaseAPI::getCameraStatus(AsyncWebServerRequest *request) +{ + static char json_response[1024]; + + sensor_t *s = esp_camera_sensor_get(); + if (s == NULL) + { + request->send(501); + return; + } + char *p = json_response; + *p++ = '{'; + + p += sprintf(p, "\"framesize\":%u,", s->status.framesize); + p += sprintf(p, "\"quality\":%u,", s->status.quality); + p += sprintf(p, "\"brightness\":%d,", s->status.brightness); + p += sprintf(p, "\"contrast\":%d,", s->status.contrast); + p += sprintf(p, "\"saturation\":%d,", s->status.saturation); + p += sprintf(p, "\"sharpness\":%d,", s->status.sharpness); + p += sprintf(p, "\"special_effect\":%u,", s->status.special_effect); + p += sprintf(p, "\"wb_mode\":%u,", s->status.wb_mode); + p += sprintf(p, "\"awb\":%u,", s->status.awb); + p += sprintf(p, "\"awb_gain\":%u,", s->status.awb_gain); + p += sprintf(p, "\"aec\":%u,", s->status.aec); + p += sprintf(p, "\"aec2\":%u,", s->status.aec2); + p += sprintf(p, "\"denoise\":%u,", s->status.denoise); + p += sprintf(p, "\"ae_level\":%d,", s->status.ae_level); + p += sprintf(p, "\"aec_value\":%u,", s->status.aec_value); + p += sprintf(p, "\"agc\":%u,", s->status.agc); + p += sprintf(p, "\"agc_gain\":%u,", s->status.agc_gain); + p += sprintf(p, "\"gainceiling\":%u,", s->status.gainceiling); + p += sprintf(p, "\"bpc\":%u,", s->status.bpc); + p += sprintf(p, "\"wpc\":%u,", s->status.wpc); + p += sprintf(p, "\"raw_gma\":%u,", s->status.raw_gma); + p += sprintf(p, "\"lenc\":%u,", s->status.lenc); + p += sprintf(p, "\"hmirror\":%u,", s->status.hmirror); + p += sprintf(p, "\"vflip\":%u,", s->status.vflip); + p += sprintf(p, "\"dcw\":%u,", s->status.dcw); + p += sprintf(p, "\"colorbar\":%u", s->status.colorbar); + *p++ = '}'; + *p++ = 0; + + AsyncWebServerResponse *response = request->beginResponse(200, MIMETYPE_JSON, json_response); + response->addHeader("Access-Control-Allow-Origin", "*"); + request->send(response); +} + +//! TODO: Optimize this!! +void BaseAPI::setCameraVar(AsyncWebServerRequest *request) +{ + if (!request->hasArg("var") || !request->hasArg("val")) + { + request->send(404); + return; + } + String var = request->arg("var"); + const char *variable = var.c_str(); + int val = atoi(request->arg("val").c_str()); + + sensor_t *s = esp_camera_sensor_get(); + if (s == NULL) + { + request->send(501); + return; + } + + int res = 0; + if (!strcmp(variable, "framesize")) + res = s->set_framesize(s, (framesize_t)val); + else if (!strcmp(variable, "quality")) + res = s->set_quality(s, val); + else if (!strcmp(variable, "contrast")) + res = s->set_contrast(s, val); + else if (!strcmp(variable, "brightness")) + res = s->set_brightness(s, val); + else if (!strcmp(variable, "saturation")) + res = s->set_saturation(s, val); + else if (!strcmp(variable, "sharpness")) + res = s->set_sharpness(s, val); + else if (!strcmp(variable, "gainceiling")) + res = s->set_gainceiling(s, (gainceiling_t)val); + else if (!strcmp(variable, "colorbar")) + res = s->set_colorbar(s, val); + else if (!strcmp(variable, "awb")) + res = s->set_whitebal(s, val); + else if (!strcmp(variable, "agc")) + res = s->set_gain_ctrl(s, val); + else if (!strcmp(variable, "aec")) + res = s->set_exposure_ctrl(s, val); + else if (!strcmp(variable, "hmirror")) + res = s->set_hmirror(s, val); + else if (!strcmp(variable, "vflip")) + res = s->set_vflip(s, val); + else if (!strcmp(variable, "awb_gain")) + res = s->set_awb_gain(s, val); + else if (!strcmp(variable, "agc_gain")) + res = s->set_agc_gain(s, val); + else if (!strcmp(variable, "aec_value")) + res = s->set_aec_value(s, val); + else if (!strcmp(variable, "aec2")) + res = s->set_aec2(s, val); + else if (!strcmp(variable, "denoise")) + res = s->set_denoise(s, val); + else if (!strcmp(variable, "dcw")) + res = s->set_dcw(s, val); + else if (!strcmp(variable, "bpc")) + res = s->set_bpc(s, val); + else if (!strcmp(variable, "wpc")) + res = s->set_wpc(s, val); + else if (!strcmp(variable, "raw_gma")) + res = s->set_raw_gma(s, val); + else if (!strcmp(variable, "lenc")) + res = s->set_lenc(s, val); + else if (!strcmp(variable, "special_effect")) + res = s->set_special_effect(s, val); + else if (!strcmp(variable, "wb_mode")) + res = s->set_wb_mode(s, val); + else if (!strcmp(variable, "ae_level")) + res = s->set_ae_level(s, val); + + else + { + log_e("unknown setting %s", var.c_str()); + request->send(404); + return; + } + log_d("Got setting %s with value %d. Res: %d", var.c_str(), val, res); + + AsyncWebServerResponse *response = request->beginResponse(200); + response->addHeader("Access-Control-Allow-Origin", "*"); + request->send(response); } \ No newline at end of file diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index 3e3c994..a5de8ee 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -7,6 +7,7 @@ class BaseAPI : public API_Utilities { protected: + struct LocalWifiConfig { std::string ssid; @@ -55,11 +56,18 @@ protected: void rebootDevice(AsyncWebServerRequest *request); void deleteRoute(AsyncWebServerRequest *request); + /* Camera Handler */ + void sendBMP(AsyncWebServerRequest *request); + void sendJpg(AsyncWebServerRequest *request); + void streamJpg(AsyncWebServerRequest *request); + void getCameraStatus(AsyncWebServerRequest *request); + void setCameraVar(AsyncWebServerRequest *request); + /* Camera Handler */ void setCamera(AsyncWebServerRequest *request); - using call_back_function_t = void (BaseAPI::*)(AsyncWebServerRequest *); - typedef call_back_function_t (*call_back_function_ptr)(AsyncWebServerRequest *); + //using call_back_function_t = void (BaseAPI::*)(AsyncWebServerRequest *); + //typedef call_back_function_t (*call_back_function_ptr)(AsyncWebServerRequest *); /* Route Command types */ using route_method = void (BaseAPI::*)(AsyncWebServerRequest *); diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 0db3ff8..2af43eb 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -41,8 +41,11 @@ void APIServer::setupServer() routes.emplace("setCamera", &APIServer::setCamera); routes.emplace("deleteRoute", &APIServer::deleteRoute); + // Camera Routes + + //! reserve enough memory for all routes - must be called after adding routes and before adding routes to route_map - indexes.reserve(routes.size()); // this is done to avoid reallocation of memory and copying of data + indexes.reserve(routes.size()); // this is done to avoid reallocation of memory and copying of data addRouteMap("builtin", routes, indexes); // add new route map to the route_map } diff --git a/ESP/lib/src/network/stream/streamServer.cpp b/ESP/lib/src/network/stream/streamServer.cpp index 5bfc272..ee04068 100644 --- a/ESP/lib/src/network/stream/streamServer.cpp +++ b/ESP/lib/src/network/stream/streamServer.cpp @@ -61,7 +61,6 @@ esp_err_t StreamHelpers::stream(httpd_req_t *req) fb = NULL; _jpg_buf = NULL; } - else if (_jpg_buf) { free(_jpg_buf); @@ -84,6 +83,7 @@ esp_err_t StreamHelpers::stream(httpd_req_t *req) int StreamServer::startStreamServer() { + WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //! Turn-off the 'brownout detector' httpd_config_t config = HTTPD_DEFAULT_CONFIG(); config.max_uri_handlers = 1; config.server_port = this->STREAM_SERVER_PORT; diff --git a/ESP/lib/src/network/stream/streamServer.hpp b/ESP/lib/src/network/stream/streamServer.hpp index 2d19cae..68a3727 100644 --- a/ESP/lib/src/network/stream/streamServer.hpp +++ b/ESP/lib/src/network/stream/streamServer.hpp @@ -3,9 +3,17 @@ #define STREAM_SERVER_HPP #define PART_BOUNDARY "123456789000000000000987654321" #include +// Used to disable brownout detection +#include "soc/soc.h" +#include "soc/rtc_cntl_reg.h" + +// Camera includes #include "esp_camera.h" #include "esp_http_server.h" - +#include "esp_timer.h" +#include "fb_gfx.h" +#include "img_converters.h" +//#include "fd_forward.h" namespace StreamHelpers { esp_err_t stream(httpd_req_t *req); diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index f001f68..9b9da25 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -53,8 +53,6 @@ void setup() break; } case WiFiState_e::WiFiState_ADHOC: - { - } case WiFiState_e::WiFiState_Connected: { streamServer.startStreamServer(); From e1936c6212add7b44ec5380cc790f986bd7f6b86 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 25 Aug 2022 14:30:09 +0100 Subject: [PATCH 053/153] update - some minor formatting --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 1 + .../network/api/utilities/apiUtilities.cpp | 65 ++++++++++--------- ESP/lib/src/network/api/webserverHandler.cpp | 1 - 3 files changed, 34 insertions(+), 33 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 7558448..681c9a6 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -345,6 +345,7 @@ void BaseAPI::getCameraStatus(AsyncWebServerRequest *request) } //! TODO: Optimize this!! +//! Change this to a hashmap and a switch-case to remove the string comparisons and if statements void BaseAPI::setCameraVar(AsyncWebServerRequest *request) { if (!request->hasArg("var") || !request->hasArg("val")) diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index 30f50da..b62aa58 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -28,6 +28,7 @@ API_Utilities::API_Utilities(int CONTROL_PORT, camera(camera), api_url(api_url) {} API_Utilities::~API_Utilities() {} + std::string API_Utilities::shaEncoder(std::string data) { const char *data_c = data.c_str(); @@ -72,38 +73,6 @@ void API_Utilities::notFound(AsyncWebServerRequest *request) const } } -/* bool API_Utilities::initSPIFFS() -{ - if (!SPIFFS.begin(false)) - { - log_e("An error has occurred while mounting SPIFFS"); - return false; - } - log_i("SPIFFS mounted successfully"); - return true; -} */ - -// Read File from SPIFFS -/* std::string API_Utilities::readFile(fs::FS &fs, std::string path) -{ - log_i("Reading file: %s\r\n", path.c_str()); - - File file = fs.open(path.c_str()); - if (!file || file.isDirectory()) - { - log_e("[INFO]: Failed to open file for reading"); - return std::string(); - } - - std::string fileContent; - while (file.available()) - { - fileContent = file.readStringUntil('#').c_str(); - break; - } - return fileContent; -} */ - void API_Utilities::printASCII() { Serial.println(F(" : === WELCOME === TO === : ")); @@ -168,6 +137,38 @@ void API_Utilities::printASCII() Serial.println(F(" <============================================================================================================================> ")); } +/* bool API_Utilities::initSPIFFS() +{ + if (!SPIFFS.begin(false)) + { + log_e("An error has occurred while mounting SPIFFS"); + return false; + } + log_i("SPIFFS mounted successfully"); + return true; +} */ + +// Read File from SPIFFS +/* std::string API_Utilities::readFile(fs::FS &fs, std::string path) +{ + log_i("Reading file: %s\r\n", path.c_str()); + + File file = fs.open(path.c_str()); + if (!file || file.isDirectory()) + { + log_e("[INFO]: Failed to open file for reading"); + return std::string(); + } + + std::string fileContent; + while (file.available()) + { + fileContent = file.readStringUntil('#').c_str(); + break; + } + return fileContent; +} */ + // Write file to SPIFFS /* void API_Utilities::writeFile(fs::FS &fs, std::string path, std::string message) { diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 2af43eb..ad15d86 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -33,7 +33,6 @@ void APIServer::begin() void APIServer::setupServer() { - // Set case NULL_METHOD routes routes.emplace("wifi", &APIServer::setWiFi); routes.emplace("resetConfig", &APIServer::factoryReset); routes.emplace("rebootDevice", &APIServer::rebootDevice); From 37f501c4425baeb8dba228da9afb95bbff77be15 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 25 Aug 2022 17:21:58 +0100 Subject: [PATCH 054/153] update - remove extranious methods --- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index a5de8ee..dcefd7e 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -56,22 +56,13 @@ protected: void rebootDevice(AsyncWebServerRequest *request); void deleteRoute(AsyncWebServerRequest *request); - /* Camera Handler */ - void sendBMP(AsyncWebServerRequest *request); - void sendJpg(AsyncWebServerRequest *request); - void streamJpg(AsyncWebServerRequest *request); + /* Camera Handlers */ void getCameraStatus(AsyncWebServerRequest *request); void setCameraVar(AsyncWebServerRequest *request); - - /* Camera Handler */ void setCamera(AsyncWebServerRequest *request); - //using call_back_function_t = void (BaseAPI::*)(AsyncWebServerRequest *); - //typedef call_back_function_t (*call_back_function_ptr)(AsyncWebServerRequest *); - /* Route Command types */ using route_method = void (BaseAPI::*)(AsyncWebServerRequest *); - // typedef void (*callback)(AsyncWebServerRequest *); typedef std::unordered_map route_t; typedef std::unordered_map route_map_t; @@ -84,6 +75,7 @@ public: CameraHandler *camera, StateManager *stateManager, std::string api_url); + virtual ~BaseAPI(); virtual void begin(); virtual void setupServer(); From d802b4a5d70bf1fe18a9882cb29dc2a49582df2b Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 28 Aug 2022 15:02:58 +0100 Subject: [PATCH 055/153] Update - Optimize the dependency injection model for the API classes - Removed the constructor params from the base-classes of APIServer - Allocate data to the base-class members in the Constructor of APIServer --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 10 +--------- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 6 +----- .../src/network/api/utilities/apiUtilities.cpp | 10 +--------- .../src/network/api/utilities/apiUtilities.hpp | 7 ++----- ESP/lib/src/network/api/webserverHandler.cpp | 16 +++++++++------- ESP/lib/src/network/api/webserverHandler.hpp | 2 +- 6 files changed, 15 insertions(+), 36 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 681c9a6..b2b222e 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -1,14 +1,6 @@ #include "baseAPI.hpp" -BaseAPI::BaseAPI(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - std::string api_url) : API_Utilities(CONTROL_PORT, - network, - camera, - stateManager, - api_url) {} +BaseAPI::BaseAPI() {} BaseAPI::~BaseAPI() {} diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index dcefd7e..538bdcf 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -70,11 +70,7 @@ protected: route_map_t route_map; public: - BaseAPI(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - std::string api_url); + BaseAPI(); virtual ~BaseAPI(); virtual void begin(); diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index b62aa58..1287eca 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -18,15 +18,7 @@ bool API_Utilities::channel_write = false; //! API Utilities //********************************************************************************************* -API_Utilities::API_Utilities(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - std::string api_url) : server(new AsyncWebServer(CONTROL_PORT)), - stateManager(stateManager), - network(network), - camera(camera), - api_url(api_url) {} +API_Utilities::API_Utilities() : server(new AsyncWebServer(_control_port)) {} API_Utilities::~API_Utilities() {} std::string API_Utilities::shaEncoder(std::string data) diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index 7565711..a39ccee 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -29,11 +29,7 @@ class API_Utilities { public: - API_Utilities(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - std::string api_url); + API_Utilities(); virtual ~API_Utilities(); static void printASCII(); @@ -80,6 +76,7 @@ protected: protected: std::string api_url; + byte _control_port; static bool ssid_write; static bool pass_write; diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index ad15d86..5b58a37 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -4,15 +4,18 @@ //! API Server //********************************************************************************************* -APIServer::APIServer(int CONTROL_PORT, +APIServer::APIServer(byte control_port, WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, - std::string api_url) : BaseAPI(CONTROL_PORT, - network, - camera, - stateManager, - api_url) {} + std::string api_url) +{ + this->_control_port = control_port; + this->network = network; + this->camera = camera; + this->stateManager = stateManager; + this->api_url = api_url; +} APIServer::~APIServer() {} @@ -41,7 +44,6 @@ void APIServer::setupServer() routes.emplace("deleteRoute", &APIServer::deleteRoute); // Camera Routes - //! reserve enough memory for all routes - must be called after adding routes and before adding routes to route_map indexes.reserve(routes.size()); // this is done to avoid reallocation of memory and copying of data diff --git a/ESP/lib/src/network/api/webserverHandler.hpp b/ESP/lib/src/network/api/webserverHandler.hpp index 806f6b3..9cdb2a6 100644 --- a/ESP/lib/src/network/api/webserverHandler.hpp +++ b/ESP/lib/src/network/api/webserverHandler.hpp @@ -7,7 +7,7 @@ class APIServer : public BaseAPI { public: - APIServer(int CONTROL_PORT, + APIServer(byte control_port, WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, From 91c3918fdcf7dd722182e35df116eb8f31b3a594 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 28 Aug 2022 15:07:01 +0100 Subject: [PATCH 056/153] Update - Turn off Power Saving mode for the wifi chip This is to try and prevent freezing --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index a56a11d..d3a389e 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -42,6 +42,9 @@ void WiFiHandler::setupWifi() unsigned long currentMillis = millis(); unsigned long _previousMillis = currentMillis; int progress = 0; + + WiFi.mode(WIFI_STA); + WiFi.setSleep(WIFI_PS_NONE); for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) { log_i("Trying to connect to the %s network", networkIterator->ssid); @@ -76,6 +79,7 @@ void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) log_i("\n[INFO]: Setting Access Point...\n"); log_i("\n[INFO]: Configuring access point...\n"); WiFi.mode(WIFI_AP); + WiFi.setSleep(WIFI_PS_NONE); Serial.printf("\r\nStarting AP. \r\nAP IP address: "); IPAddress IP = WiFi.softAPIP(); Serial.printf("[INFO]: AP IP address: %s.\r\n", IP.toString().c_str()); @@ -132,6 +136,9 @@ void WiFiHandler::iniSTA() return; } + WiFi.mode(WIFI_STA); + WiFi.setSleep(WIFI_PS_NONE); + WiFi.begin(this->ssid.c_str(), this->password.c_str(), this->channel); while (WiFi.status() != WL_CONNECTED) { From c95666307cc49b7e17d0a94958cb92e12de22446 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 28 Aug 2022 15:26:30 +0100 Subject: [PATCH 057/153] update - Add TODO regarding the POST request for JSON handling - Modify try-catch for handleRequest to catch all exceptions --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 1 + ESP/lib/src/network/api/webserverHandler.cpp | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index b2b222e..6b9ced3 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -106,6 +106,7 @@ void BaseAPI::triggerWifiConfigWrite() } } +//! TODO: Add JSON handling to the POST request void BaseAPI::handleJson(AsyncWebServerRequest *request) { std::string type = request->pathArg(0).c_str(); diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 5b58a37..d9d68a3 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -120,8 +120,8 @@ void APIServer::handleRequest(AsyncWebServerRequest *request) } request->send(200, MIMETYPE_JSON, "{\"msg\":\"Command executed\"}"); } - catch (const std::exception &e) + catch (...) // catch all exceptions { - log_e("Error: %s", e.what()); + request->send(400, MIMETYPE_JSON, "{\"msg\":\"An Error has occurred\"}"); } } From a5820c674a378676706e3f74f1be6e91ab968583 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 28 Aug 2022 17:14:10 +0100 Subject: [PATCH 058/153] update - Revert Constructors for now to fix APIServer not working - Begin implementation of the Preferences Lib --- ESP/lib/src/data/config/project_config.cpp | 77 +++++-------------- ESP/lib/src/data/config/project_config.hpp | 4 +- .../src/network/WifiHandler/wifiHandler.cpp | 3 +- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 12 ++- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 6 +- .../network/api/utilities/apiUtilities.cpp | 11 ++- .../network/api/utilities/apiUtilities.hpp | 7 +- ESP/lib/src/network/api/webserverHandler.cpp | 16 ++-- ESP/lib/src/network/api/webserverHandler.hpp | 2 +- ESP/lib/src/network/stream/streamServer.cpp | 2 +- ESP/src/main.cpp | 6 ++ 11 files changed, 66 insertions(+), 80 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index e2448ab..4430aad 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -1,8 +1,6 @@ #include "project_config.hpp" -Preferences preferences; - -ProjectConfig::ProjectConfig() : Config(&preferences, "config"), _already_loaded(false) {} +ProjectConfig::ProjectConfig() : _already_loaded(false) {} ProjectConfig::~ProjectConfig() {} @@ -12,9 +10,9 @@ ProjectConfig::~ProjectConfig() {} */ void ProjectConfig::initConfig() { - begin(); + begin("projectConf"); this->config.device = { - "EyeTrackVR", + "eyetrackvr", "", 3232, false, @@ -58,44 +56,25 @@ void ProjectConfig::load() return; } - bool device_name_success = this->read("device_name", this->config.device.name); - bool device_otapassword_success = this->read("ota_pass", this->config.device.OTAPassword); - 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++) + size_t configLen = getBytesLength("config"); + if (configLen == 0) { - 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); - bool networks_adhoc_success = this->read(buff, this->config.networks[i].adhoc); - - network_info_success = networks_name_success && networks_ssid_success && networks_password_success && networks_channel_success && networks_adhoc_success; - } - - if (!device_success || !camera_success || !network_info_success) - { - log_e("Failed to load project config - Generating config and restarting"); + log_e("Project config not found - Generating config and restarting"); save(); delay(1000); ESP.restart(); return; } + else + { + log_d("Project config found - Config length: %d", configLen); + } + + char buff[configLen]; + getBytes("config", buff, configLen); + + for (int i = 0; i < configLen; i++) + Serial.printf("%02X ", buff[i]); this->_already_loaded = true; this->notify(ObserverEvent::configLoaded); @@ -105,28 +84,8 @@ void ProjectConfig::save() { log_d("Saving project config"); - this->write("device_name", this->config.device.name); - 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); - this->write(buff, this->config.networks[i].adhoc); - } + TrackerConfig_t *tracker_config = (TrackerConfig_t *)&this->config; + putBytes("config", tracker_config, 3 * sizeof(TrackerConfig_t)); log_i("Project config saved and system is rebooting"); delay(20000); diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index ce60c64..5f1e2de 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -2,13 +2,13 @@ #ifndef PROJECT_CONFIG_HPP #define PROJECT_CONFIG_HPP #include -#include +#include #include #include #include "data/utilities/Observer.hpp" -class ProjectConfig : public Config, public ISubject +class ProjectConfig : public Preferences, public ISubject { public: ProjectConfig(); diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index d3a389e..0382357 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -76,6 +76,7 @@ void WiFiHandler::setupWifi() void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) { + stateManager->setState(WiFiState_e::WiFiState_ADHOC); log_i("\n[INFO]: Setting Access Point...\n"); log_i("\n[INFO]: Configuring access point...\n"); WiFi.mode(WIFI_AP); @@ -86,7 +87,6 @@ void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) // You can remove the password parameter if you want the AP to be open. WiFi.softAP(ssid, password, channel); // AP mode with password WiFi.setTxPower(WIFI_POWER_11dBm); - stateManager->setState(WiFiState_e::WiFiState_ADHOC); } /* @@ -155,7 +155,6 @@ void WiFiHandler::iniSTA() this->setUpADHOC(); log_w("Setting up adhoc mode"); log_w("Please use adhoc mode and the app to set your WiFi credentials and reboot the device"); - stateManager->setState(WiFiState_e::WiFiState_ADHOC); return; } } diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 6b9ced3..342727b 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -1,6 +1,14 @@ #include "baseAPI.hpp" -BaseAPI::BaseAPI() {} +BaseAPI::BaseAPI(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url) : API_Utilities(CONTROL_PORT, + network, + camera, + stateManager, + api_url) {} BaseAPI::~BaseAPI() {} @@ -106,7 +114,7 @@ void BaseAPI::triggerWifiConfigWrite() } } -//! TODO: Add JSON handling to the POST request +//! TODO: ADD JSON handlers for the POST requests void BaseAPI::handleJson(AsyncWebServerRequest *request) { std::string type = request->pathArg(0).c_str(); diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index 538bdcf..dcefd7e 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -70,7 +70,11 @@ protected: route_map_t route_map; public: - BaseAPI(); + BaseAPI(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url); virtual ~BaseAPI(); virtual void begin(); diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index 1287eca..2096577 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -18,7 +18,16 @@ bool API_Utilities::channel_write = false; //! API Utilities //********************************************************************************************* -API_Utilities::API_Utilities() : server(new AsyncWebServer(_control_port)) {} +API_Utilities::API_Utilities(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url) : server(new AsyncWebServer(CONTROL_PORT)), + stateManager(stateManager), + network(network), + camera(camera), + api_url(api_url) {} + API_Utilities::~API_Utilities() {} std::string API_Utilities::shaEncoder(std::string data) diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index a39ccee..7565711 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -29,7 +29,11 @@ class API_Utilities { public: - API_Utilities(); + API_Utilities(int CONTROL_PORT, + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + std::string api_url); virtual ~API_Utilities(); static void printASCII(); @@ -76,7 +80,6 @@ protected: protected: std::string api_url; - byte _control_port; static bool ssid_write; static bool pass_write; diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index d9d68a3..c9223d6 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -4,18 +4,15 @@ //! API Server //********************************************************************************************* -APIServer::APIServer(byte control_port, +APIServer::APIServer(int CONTROL_PORT, WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, - std::string api_url) -{ - this->_control_port = control_port; - this->network = network; - this->camera = camera; - this->stateManager = stateManager; - this->api_url = api_url; -} + std::string api_url) : BaseAPI(CONTROL_PORT, + network, + camera, + stateManager, + api_url) {} APIServer::~APIServer() {} @@ -44,6 +41,7 @@ void APIServer::setupServer() routes.emplace("deleteRoute", &APIServer::deleteRoute); // Camera Routes + //! reserve enough memory for all routes - must be called after adding routes and before adding routes to route_map indexes.reserve(routes.size()); // this is done to avoid reallocation of memory and copying of data diff --git a/ESP/lib/src/network/api/webserverHandler.hpp b/ESP/lib/src/network/api/webserverHandler.hpp index 9cdb2a6..806f6b3 100644 --- a/ESP/lib/src/network/api/webserverHandler.hpp +++ b/ESP/lib/src/network/api/webserverHandler.hpp @@ -7,7 +7,7 @@ class APIServer : public BaseAPI { public: - APIServer(byte control_port, + APIServer(int CONTROL_PORT, WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, diff --git a/ESP/lib/src/network/stream/streamServer.cpp b/ESP/lib/src/network/stream/streamServer.cpp index ee04068..9ba939e 100644 --- a/ESP/lib/src/network/stream/streamServer.cpp +++ b/ESP/lib/src/network/stream/streamServer.cpp @@ -15,7 +15,7 @@ esp_err_t StreamHelpers::stream(httpd_req_t *req) size_t _jpg_buf_len = 0; uint8_t *_jpg_buf = NULL; - char *part_buf[128]; + char *part_buf[256]; static int64_t last_frame = 0; if (!last_frame) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 9b9da25..501fa5d 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -53,6 +53,12 @@ void setup() break; } case WiFiState_e::WiFiState_ADHOC: + { + streamServer.startStreamServer(); + apiServer.begin(); + log_d("[SETUP]: Starting Stream Server"); + break; + } case WiFiState_e::WiFiState_Connected: { streamServer.startStreamServer(); From e373cc704f446f3b99bb3ec902151f152f3bd238 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 28 Aug 2022 18:31:48 +0100 Subject: [PATCH 059/153] update - Edited the Wifi Scanner in NetworkUtils namespace - Added config.grab_mode = CAMERA_GRAB_LATEST; to camera config to grab the latest frames - Set httpd stack size to 20480 --- ESP/lib/src/data/utilities/network_utilities.cpp | 6 ++---- ESP/lib/src/io/camera/cameraHandler.cpp | 3 ++- ESP/lib/src/network/stream/streamServer.cpp | 1 + 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ESP/lib/src/data/utilities/network_utilities.cpp b/ESP/lib/src/data/utilities/network_utilities.cpp index 7a55b8b..06d08fc 100644 --- a/ESP/lib/src/data/utilities/network_utilities.cpp +++ b/ESP/lib/src/data/utilities/network_utilities.cpp @@ -13,18 +13,16 @@ bool Network_Utilities::LoopWifiScan() { // WiFi.scanNetworks will return the number of networks found log_i("[INFO]: Beginning WiFi Scanner"); - int networks = WiFi.scanNetworks(); + int networks = WiFi.scanNetworks(true, true); log_i("[INFO]: scan done"); log_i("%d networks found", networks); for (int i = networks; i--;) { // Print SSID and RSSI for each network found - //! Add method here to interface with the API and forward the scanned networks to the API + //! TODO: Add method here to interface with the API and forward the scanned networks to the API log_i("%d: %s (%d) %s\n", i - 1, WiFi.SSID(i), WiFi.RSSI(i), (WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*"); my_delay(0.02L); // delay 20ms } - // Wait a bit before scanning again - delay(5000); return (networks > 0); } diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index a684d61..6be5975 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -6,6 +6,7 @@ int CameraHandler::setupCamera() config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; + config.grab_mode = CAMERA_GRAB_LATEST; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; @@ -22,7 +23,7 @@ int CameraHandler::setupCamera() config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; - config.xclk_freq_hz = 20000000; // 10000000 stable, + config.xclk_freq_hz = 16500000; // 10000000 stable, // 16500000 optimal, // 20000000 max fps config.pixel_format = PIXFORMAT_JPEG; diff --git a/ESP/lib/src/network/stream/streamServer.cpp b/ESP/lib/src/network/stream/streamServer.cpp index 9ba939e..7429345 100644 --- a/ESP/lib/src/network/stream/streamServer.cpp +++ b/ESP/lib/src/network/stream/streamServer.cpp @@ -88,6 +88,7 @@ int StreamServer::startStreamServer() config.max_uri_handlers = 1; config.server_port = this->STREAM_SERVER_PORT; config.ctrl_port = this->STREAM_SERVER_PORT; + config.stack_size = 20480; httpd_uri_t stream_page = { .uri = "/", From d65532a6b12f89b15423de622c7b867c9270effb Mon Sep 17 00:00:00 2001 From: Lorow Date: Sun, 28 Aug 2022 20:58:38 +0200 Subject: [PATCH 060/153] Bump the httpd buffer to 20480 to fix freezing / buffer overflow issue --- ESP/lib/src/network/stream/streamServer.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/ESP/lib/src/network/stream/streamServer.cpp b/ESP/lib/src/network/stream/streamServer.cpp index ee04068..b038126 100644 --- a/ESP/lib/src/network/stream/streamServer.cpp +++ b/ESP/lib/src/network/stream/streamServer.cpp @@ -85,6 +85,7 @@ int StreamServer::startStreamServer() { WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //! Turn-off the 'brownout detector' httpd_config_t config = HTTPD_DEFAULT_CONFIG(); + config.stack_size = 20480; config.max_uri_handlers = 1; config.server_port = this->STREAM_SERVER_PORT; config.ctrl_port = this->STREAM_SERVER_PORT; From c220bf66066cc27da63c04cce65a716e4d5627ca Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 29 Aug 2022 13:23:55 +0100 Subject: [PATCH 061/153] update - Fixed bug in request handler - needed to add support for non-param URL requests --- ESP/lib/src/data/config/project_config.cpp | 6 +- ESP/lib/src/network/api/webserverHandler.cpp | 69 +++++++++++++------- 2 files changed, 47 insertions(+), 28 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 4430aad..3966213 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -65,10 +65,8 @@ void ProjectConfig::load() ESP.restart(); return; } - else - { - log_d("Project config found - Config length: %d", configLen); - } + + log_d("Project config found - Config length: %d", configLen); char buff[configLen]; getBytes("config", buff, configLen); diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index c9223d6..39f067d 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -41,7 +41,6 @@ void APIServer::setupServer() routes.emplace("deleteRoute", &APIServer::deleteRoute); // Camera Routes - //! reserve enough memory for all routes - must be called after adding routes and before adding routes to route_map indexes.reserve(routes.size()); // this is done to avoid reallocation of memory and copying of data @@ -80,46 +79,68 @@ void APIServer::handleRequest(AsyncWebServerRequest *request) { try { + size_t params = request->params(); // Get the route log_i("Request URL: %s", request->url().c_str()); - int params = request->params(); - auto it_map = route_map.find(request->pathArg(0).c_str()); - log_i("Request First Arg: %s", request->pathArg(0).c_str()); - auto it_method = it_map->second.find(request->pathArg(1).c_str()); - log_i("Request Second Arg: %s", request->pathArg(1).c_str()); + log_i("Request: %s", request->pathArg(0).c_str()); + log_i("Request: %s", request->pathArg(1).c_str()); - for (int i = 0; i < params; i++) + auto it_map = route_map.find(request->pathArg(0).c_str()); + auto it_method = it_map->second.find(request->pathArg(1).c_str()); + + log_d("Params: %d", params); + if (params > 0) { - AsyncWebParameter *param = request->getParam(i); + log_d("We have params!"); + for (size_t i = 0; i < params; i++) { + log_d("We are executing the for loop"); + AsyncWebParameter *param = request->getParam(i); + if (it_map != route_map.end()) { - if (it_map != route_map.end()) + if (it_method != it_map->second.end()) { - if (it_method != it_map->second.end()) - { - (*this.*(it_method->second))(request); - } - else - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Command\"}"); - request->redirect("/"); - return; - } + (*this.*(it_method->second))(request); } else { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Map Index\"}"); - request->redirect("/"); + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Command\"}"); return; } } + else + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Map Index\"}"); + return; + } log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } } - request->send(200, MIMETYPE_JSON, "{\"msg\":\"Command executed\"}"); + else + { + log_d("No params, so we skipped the for loop"); + if (it_map != route_map.end()) + { + if (it_method != it_map->second.end()) + { + log_d("We are trying to execute the function"); + (*this.*(it_method->second))(request); + } + else + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Command\"}"); + return; + } + } + else + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Map Index\"}"); + return; + } + } } - catch (...) // catch all exceptions + catch (...) { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"An Error has occurred\"}"); + log_e("Error handling request"); } } From 41fe047f7a1904548dbf9254fd30986e8242dcfd Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 29 Aug 2022 13:38:58 +0100 Subject: [PATCH 062/153] update - Change the handle request to only handle the request itself - Allow each function to handle their own parameters --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 5 +- ESP/lib/src/network/api/webserverHandler.cpp | 57 +++++--------------- 2 files changed, 16 insertions(+), 46 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 342727b..ad6e486 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -61,8 +61,8 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) { case POST: { - int params = request->params(); - for (int i = 0; i < params; i++) + size_t params = request->params(); + for (size_t i = 0; i < params; i++) { AsyncWebParameter *param = request->getParam(i); if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) @@ -79,6 +79,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) localWifiConfig.channel = atoi(param->value().c_str()); localWifiConfig.adhoc = atoi(param->value().c_str()); } + log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } ssid_write = true; pass_write = true; diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 39f067d..514c6c8 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -79,7 +79,6 @@ void APIServer::handleRequest(AsyncWebServerRequest *request) { try { - size_t params = request->params(); // Get the route log_i("Request URL: %s", request->url().c_str()); log_i("Request: %s", request->pathArg(0).c_str()); @@ -88,55 +87,25 @@ void APIServer::handleRequest(AsyncWebServerRequest *request) auto it_map = route_map.find(request->pathArg(0).c_str()); auto it_method = it_map->second.find(request->pathArg(1).c_str()); - log_d("Params: %d", params); - if (params > 0) + if (it_map != route_map.end()) { - log_d("We have params!"); - for (size_t i = 0; i < params; i++) + if (it_method != it_map->second.end()) { - log_d("We are executing the for loop"); - AsyncWebParameter *param = request->getParam(i); - if (it_map != route_map.end()) - { - if (it_method != it_map->second.end()) - { - (*this.*(it_method->second))(request); - } - else - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Command\"}"); - return; - } - } - else - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Map Index\"}"); - return; - } - log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); + log_d("We are trying to execute the function"); + (*this.*(it_method->second))(request); + } + else + { + log_e("Invalid Command"); + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Command\"}"); + return; } } else { - log_d("No params, so we skipped the for loop"); - if (it_map != route_map.end()) - { - if (it_method != it_map->second.end()) - { - log_d("We are trying to execute the function"); - (*this.*(it_method->second))(request); - } - else - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Command\"}"); - return; - } - } - else - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Map Index\"}"); - return; - } + log_e("Invalid Map Index"); + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Map Index\"}"); + return; } } catch (...) From 19733adcf83eb363f4be8fe647fd35e92459a2a2 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 29 Aug 2022 15:02:40 +0100 Subject: [PATCH 063/153] update - Optimize std::string in function params by passing in a const reference --- ESP/lib/src/data/config/project_config.cpp | 6 +++--- ESP/lib/src/data/utilities/helpers.cpp | 2 +- ESP/lib/src/network/WifiHandler/WifiHandler.hpp | 4 ++-- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 6 +++--- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 2 +- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 2 +- .../src/network/api/utilities/apiUtilities.cpp | 2 +- .../src/network/api/utilities/apiUtilities.hpp | 2 +- ESP/lib/src/network/api/webserverHandler.cpp | 16 ++++++++-------- ESP/lib/src/network/api/webserverHandler.hpp | 6 +++--- 10 files changed, 24 insertions(+), 24 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 3966213..246fdad 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -65,11 +65,11 @@ void ProjectConfig::load() ESP.restart(); return; } - + log_d("Project config found - Config length: %d", configLen); char buff[configLen]; - getBytes("config", buff, configLen); + getBytes("projectConf", buff, configLen); for (int i = 0; i < configLen; i++) Serial.printf("%02X ", buff[i]); @@ -83,7 +83,7 @@ void ProjectConfig::save() log_d("Saving project config"); TrackerConfig_t *tracker_config = (TrackerConfig_t *)&this->config; - putBytes("config", tracker_config, 3 * sizeof(TrackerConfig_t)); + putBytes("projectConf", tracker_config, 3 * sizeof(TrackerConfig_t)); log_i("Project config saved and system is rebooting"); delay(20000); diff --git a/ESP/lib/src/data/utilities/helpers.cpp b/ESP/lib/src/data/utilities/helpers.cpp index 4c24f26..0950cd2 100644 --- a/ESP/lib/src/data/utilities/helpers.cpp +++ b/ESP/lib/src/data/utilities/helpers.cpp @@ -32,7 +32,7 @@ char *Helpers::itoa(int value, char *result, int base) return result; } -void split(std::string str, std::string splitBy, std::vector &tokens) +void split(const std::string &str, const std::string &splitBy, std::vector &tokens) { /* Store the original string in the array, so we can loop the rest * of the algorithm. */ diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 686c35a..3a503c2 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -12,8 +12,8 @@ class WiFiHandler { public: WiFiHandler(ProjectConfig *configManager, StateManager *stateManager, - std::string ssid, - std::string password, + const std::string &ssid, + const std::string &password, uint8_t channel); virtual ~WiFiHandler(); void setupWifi(); diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 0382357..2b53633 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -3,8 +3,8 @@ WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager, - std::string ssid, - std::string password, + const std::string &ssid, + const std::string &password, uint8_t channel) : configManager(configManager), stateManager(stateManager), ssid(ssid), @@ -52,7 +52,7 @@ void WiFiHandler::setupWifi() count++; while (WiFi.status() != WL_CONNECTED) - { + { progress++; stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting); currentMillis = millis(); diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index ad6e486..bae7097 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -4,7 +4,7 @@ BaseAPI::BaseAPI(int CONTROL_PORT, WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, - std::string api_url) : API_Utilities(CONTROL_PORT, + const std::string &api_url) : API_Utilities(CONTROL_PORT, network, camera, stateManager, diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index dcefd7e..b54db87 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -74,7 +74,7 @@ public: WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, - std::string api_url); + const std::string &api_url); virtual ~BaseAPI(); virtual void begin(); diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index 2096577..4f2fd54 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -22,7 +22,7 @@ API_Utilities::API_Utilities(int CONTROL_PORT, WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, - std::string api_url) : server(new AsyncWebServer(CONTROL_PORT)), + const std::string &api_url) : server(new AsyncWebServer(CONTROL_PORT)), stateManager(stateManager), network(network), camera(camera), diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index 7565711..bb67c7f 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -33,7 +33,7 @@ public: WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, - std::string api_url); + const std::string &api_url); virtual ~API_Utilities(); static void printASCII(); diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 514c6c8..fe441a0 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -8,11 +8,11 @@ APIServer::APIServer(int CONTROL_PORT, WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, - std::string api_url) : BaseAPI(CONTROL_PORT, - network, - camera, - stateManager, - api_url) {} + const std::string &api_url) : BaseAPI(CONTROL_PORT, + network, + camera, + stateManager, + api_url) {} APIServer::~APIServer() {} @@ -47,11 +47,11 @@ void APIServer::setupServer() addRouteMap("builtin", routes, indexes); // add new route map to the route_map } -void APIServer::findParam(AsyncWebServerRequest *request, const char *param, String &value) +void APIServer::findParam(AsyncWebServerRequest *request, const char *param, std::string &value) { if (request->hasParam(param)) { - value = request->getParam(param)->value(); + value = request->getParam(param)->value().c_str(); } } @@ -65,7 +65,7 @@ void APIServer::findParam(AsyncWebServerRequest *request, const char *param, Str * @return void * */ -void APIServer::addRouteMap(std::string index, route_t route, std::vector &indexes) +void APIServer::addRouteMap(const std::string &index, route_t route, std::vector &indexes) { route_map.emplace(index, route); diff --git a/ESP/lib/src/network/api/webserverHandler.hpp b/ESP/lib/src/network/api/webserverHandler.hpp index 806f6b3..ddbdc43 100644 --- a/ESP/lib/src/network/api/webserverHandler.hpp +++ b/ESP/lib/src/network/api/webserverHandler.hpp @@ -11,13 +11,13 @@ public: WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, - std::string api_url); + const std::string &api_url); virtual ~APIServer(); void begin(); void setupServer(); - void findParam(AsyncWebServerRequest *request, const char *param, String &value); - void addRouteMap(std::string index, route_t route, std::vector &indexes); + void findParam(AsyncWebServerRequest *request, const char *param, std::string &value); + void addRouteMap(const std::string &index, route_t route, std::vector &indexes); void handleRequest(AsyncWebServerRequest *request); public: From 10e88015cf6d36a415423d95d244e9a9a8a6fe7f Mon Sep 17 00:00:00 2001 From: DaOfficialWizard <45744329+ZanzyTHEbar@users.noreply.github.com> Date: Tue, 30 Aug 2022 15:18:20 +0100 Subject: [PATCH 064/153] Update baseAPI.cpp --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index bae7097..ef5e247 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -5,10 +5,10 @@ BaseAPI::BaseAPI(int CONTROL_PORT, CameraHandler *camera, StateManager *stateManager, const std::string &api_url) : API_Utilities(CONTROL_PORT, - network, - camera, - stateManager, - api_url) {} + network, + camera, + stateManager, + api_url) {} BaseAPI::~BaseAPI() {} @@ -431,4 +431,4 @@ void BaseAPI::setCameraVar(AsyncWebServerRequest *request) AsyncWebServerResponse *response = request->beginResponse(200); response->addHeader("Access-Control-Allow-Origin", "*"); request->send(response); -} \ No newline at end of file +} From 583a2545f8926c89d22d0c17c310002c146c339b Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 00:45:30 +0100 Subject: [PATCH 065/153] Update - Finally fix preferences lib - Setup API to use the preferences lib - Setup the WiFiHandler to use the preferences lib - Remove the triggerWifiConfigWrite in favour of handling that in the setWiFi method itself --- ESP/lib/src/data/config/project_config.cpp | 250 +++++++++++------- ESP/lib/src/data/config/project_config.hpp | 21 +- .../src/network/WifiHandler/wifiHandler.cpp | 14 +- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 143 +++++----- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 21 -- ESP/src/main.cpp | 1 - 6 files changed, 250 insertions(+), 200 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 246fdad..1be1fb2 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -1,6 +1,6 @@ #include "project_config.hpp" -ProjectConfig::ProjectConfig() : _already_loaded(false) {} +ProjectConfig::ProjectConfig(const std::string &name) : _name(std::move(name)), _already_loaded(false) {} ProjectConfig::~ProjectConfig() {} @@ -10,43 +10,99 @@ ProjectConfig::~ProjectConfig() {} */ void ProjectConfig::initConfig() { - begin("projectConf"); + if (_name.empty()) + { + log_e("Config name is null\n"); + _name = "openiris"; + } + + bool success = begin(_name.c_str()); + + log_i("Config name: %s", _name.c_str()); + log_i("Config loaded: %s", success ? "true" : "false"); + this->config.device = { - "eyetrackvr", - "", + _name, + "12345678", 3232, false, false, false, - "", - "", - ""}; - - this->config.camera = { - 0, - 0, - 0, - 0, - }; - - this->config.networks = { - { - "", - "", - "", - 0, - false, - }, + std::string(), + std::string(), + std::string(), }; this->config.ap_network = { - "", - "", + std::string(), + std::string(), 0, - false, }; } +void ProjectConfig::save() +{ + log_d("Saving project config"); + deviceConfigSave(); + cameraConfigSave(); + wifiConfigSave(); + end(); +} + +void ProjectConfig::wifiConfigSave() +{ + log_d("Saving wifi config"); + + /* WiFi Config */ + putInt("networkCount", this->config.networks.size()); + + for (int i = 0; i < this->config.networks.size(); i++) + { + const std::string &name = std::to_string(i) + "name"; + const std::string &ssid = std::to_string(i) + "ssid"; + const std::string &password = std::to_string(i) + "pass"; + const std::string &channel = std::to_string(i) + "channel"; + + putString(name.c_str(), this->config.networks[i].name.c_str()); + putString(ssid.c_str(), this->config.networks[i].ssid.c_str()); + putString(password.c_str(), this->config.networks[i].password.c_str()); + putInt(channel.c_str(), this->config.networks[i].channel); + } + + /* AP Config */ + putString("apSSID", this->config.ap_network.ssid.c_str()); + putString("apPass", this->config.ap_network.password.c_str()); + putUInt("apChannel", this->config.ap_network.channel); + + log_i("Project config saved and system is rebooting"); + delay(5000); + ESP.restart(); +} + +void ProjectConfig::deviceConfigSave() +{ + /* Device Config */ + putString("deviceName", this->config.device.name.c_str()); + putString("OTAPassword", this->config.device.OTAPassword.c_str()); + putInt("OTAPort", this->config.device.OTAPort); + //! No need to save the JSON strings or bools, they are generated and used on the fly +} + +void ProjectConfig::cameraConfigSave() +{ + /* Camera Config */ + putInt("vflip", this->config.camera.vflip); + putInt("framesize", this->config.camera.framesize); + putInt("href", this->config.camera.href); + putInt("quality", this->config.camera.quality); +} + +bool ProjectConfig::reset() +{ + log_w("Resetting project config"); + return clear(); +} + void ProjectConfig::load() { log_d("Loading project config"); @@ -56,57 +112,54 @@ void ProjectConfig::load() return; } - size_t configLen = getBytesLength("config"); - if (configLen == 0) + /* Device Config */ + this->config.device.name = getString("deviceName", "easynetwork").c_str(); + this->config.device.OTAPassword = getString("OTAPassword", "12345678").c_str(); + this->config.device.OTAPort = getInt("OTAPort", 3232); + //! No need to load the JSON strings or bools, they are generated and used on the fly + + /* WiFi Config */ + int networkCount = getInt("networkCount", 0); + for (int i = 0; i < networkCount; i++) { - log_e("Project config not found - Generating config and restarting"); - save(); - delay(1000); - ESP.restart(); - return; + const std::string &name = std::to_string(i) + "name"; + const std::string &ssid = std::to_string(i) + "ssid"; + const std::string &password = std::to_string(i) + "pass"; + const std::string &channel = std::to_string(i) + "channel"; + + const std::string &temp_1 = getString(name.c_str()).c_str(); + const std::string &temp_2 = getString(ssid.c_str()).c_str(); + const std::string &temp_3 = getString(password.c_str()).c_str(); + uint8_t temp_4 = getUInt(channel.c_str()); + + //! push_back creates a copy of the object, so we need to use emplace_back + this->config.networks.emplace_back( + temp_1, + temp_2, + temp_3, + temp_4); } - log_d("Project config found - Config length: %d", configLen); - - char buff[configLen]; - getBytes("projectConf", buff, configLen); - - for (int i = 0; i < configLen; i++) - Serial.printf("%02X ", buff[i]); + /* AP Config */ + this->config.ap_network.ssid = getString("apSSID", "easynetwork").c_str(); + this->config.ap_network.password = getString("apPass", "12345678").c_str(); + this->config.ap_network.channel = getUInt("apChannel", 0); this->_already_loaded = true; this->notify(ObserverEvent::configLoaded); } -void ProjectConfig::save() -{ - log_d("Saving project config"); - - TrackerConfig_t *tracker_config = (TrackerConfig_t *)&this->config; - putBytes("projectConf", tracker_config, 3 * sizeof(TrackerConfig_t)); - - log_i("Project config saved and system is rebooting"); - delay(20000); - ESP.restart(); -} - -void ProjectConfig::reset() -{ - log_w("Resetting project config"); - this->clear(); -} - //********************************************************************************************************************** //* -//* DeviceConfig +//! DeviceConfig //* //********************************************************************************************************************** -void ProjectConfig::setDeviceConfig(const char *name, const char *OTAPassword, int *OTAPort, bool shouldNotify) +void ProjectConfig::setDeviceConfig(const std::string &name, const std::string &OTAPassword, int *OTAPort, bool shouldNotify) { log_d("Updating device config"); this->config.device = { - (char *)name, - (char *)OTAPassword, + name, + OTAPassword, *OTAPort, }; if (shouldNotify) @@ -115,56 +168,51 @@ void ProjectConfig::setDeviceConfig(const char *name, const char *OTAPassword, i } } -void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, bool shouldNotify) -{ - this->config.camera = { - *vflip, - *framesize, - *href, - *quality, - }; - - log_d("Updating camera config"); - if (shouldNotify) - { - this->notify(ObserverEvent::cameraConfigUpdated); - } -} - -void ProjectConfig::setWifiConfig(const char *networkName, const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify) +void ProjectConfig::setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify) { WiFiConfig_t *networkToUpdate = nullptr; - for (int i = 0; i < this->config.networks.size(); i++) + size_t size = this->config.networks.size(); + if (size > 0) { - if (strcmp(this->config.networks[i].name.c_str(), networkName) == 0) - networkToUpdate = &this->config.networks[i]; + for (int i = 0; i < size; i++) + { + if (strcmp(this->config.networks[i].name.c_str(), networkName.c_str()) == 0) + networkToUpdate = &this->config.networks[i]; + + //! push_back creates a copy of the object, so we need to use emplace_back + if (networkToUpdate != nullptr) + { + this->config.networks.emplace_back( + networkName, + ssid, + password, + *channel); + } + log_d("Updating wifi config"); + } + } + else + { + //! push_back creates a copy of the object, so we need to use emplace_back + this->config.networks.emplace_back( + networkName, + ssid, + password, + *channel); + networkToUpdate = &this->config.networks[0]; } - if (networkToUpdate != nullptr) - { - this->config.networks = { - { - (char *)networkName, - (char *)ssid, - (char *)password, - *channel, - adhoc, - }, - }; - if (shouldNotify) - this->notify(ObserverEvent::networksConfigUpdated); - } - log_d("Updating wifi config"); + if (shouldNotify) + this->notify(ObserverEvent::networksConfigUpdated); } -void ProjectConfig::setAPWifiConfig(const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify) +void ProjectConfig::setAPWifiConfig(const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify) { this->config.ap_network = { - (char *)ssid, - (char *)password, + ssid, + password, *channel, - adhoc, }; log_d("Updating access point config"); diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 5f1e2de..0b40c27 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -11,11 +11,14 @@ class ProjectConfig : public Preferences, public ISubject { public: - ProjectConfig(); + ProjectConfig(const std::string &name = std::string()); virtual ~ProjectConfig(); void load(); void save(); - void reset(); + void wifiConfigSave(); + void cameraConfigSave(); + void deviceConfigSave(); + bool reset(); void initConfig(); struct DeviceConfig_t @@ -26,9 +29,9 @@ public: bool data_json; bool config_json; bool settings_json; - String data_json_string; - String config_json_string; - String settings_json_string; + std::string data_json_string; + std::string config_json_string; + std::string settings_json_string; }; struct CameraConfig_t @@ -69,15 +72,15 @@ public: std::vector *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 std::string &name, const std::string &OTAPassword, int *OTAPort, 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, uint8_t *channel, bool adhoc, bool shouldNotify); - void setAPWifiConfig(const char *ssid, const char *password, uint8_t *channel, bool adhoc, bool shouldNotify); + void setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify); + void setAPWifiConfig(const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify); private: - const char *configFileName; TrackerConfig_t config; bool _already_loaded; + std::string _name; }; #endif // PROJECT_CONFIG_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 2b53633..d3334d6 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -28,12 +28,22 @@ void WiFiHandler::setupWifi() std::vector *networks = configManager->getWifiConfigs(); // check size of networks - if (networks->empty()) + log_i("Found %d networks", networks->size()); + + /* if (networks->empty()) { log_e("No networks found in config"); this->iniSTA(); stateManager->setState(WiFiState_e::WiFiState_Error); return; + } */ + + if (networks->size() == 0) + { + log_e("No networks found in config"); + stateManager->setState(WiFiState_e::WiFiState_Error); + this->iniSTA(); + return; } int connection_timeout = 30000; // 30 seconds @@ -58,7 +68,7 @@ void WiFiHandler::setupWifi() currentMillis = millis(); Helpers::update_progress_bar(progress, 100); delay(301); - if (((currentMillis - _previousMillis) >= connection_timeout) && count >= networks->size()) + if (((currentMillis - _previousMillis) >= connection_timeout) && (count <= networks->size())) { log_i("\n[INFO]: WiFi connection timed out.\n"); // we've tried all saved networks, none worked, let's error out diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index ef5e247..7e8d491 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -5,16 +5,15 @@ BaseAPI::BaseAPI(int CONTROL_PORT, CameraHandler *camera, StateManager *stateManager, const std::string &api_url) : API_Utilities(CONTROL_PORT, - network, - camera, - stateManager, - api_url) {} + network, + camera, + stateManager, + api_url) {} BaseAPI::~BaseAPI() {} void BaseAPI::begin() { - this->setupServer(); //! i have changed this to use lambdas instead of std::bind to avoid the overhead. Lambdas are always more preferable. server->on("/", 0b00000001, [&](AsyncWebServerRequest *request) { request->send(200); }); @@ -35,23 +34,6 @@ void BaseAPI::begin() { notFound(request); }); } -void BaseAPI::setupServer() -{ - localWifiConfig = { - .ssid = "", - .pass = "", - .channel = 0, - .adhoc = false, - }; - - localAPWifiConfig = { - .ssid = "", - .pass = "", - .channel = 0, - .adhoc = false, - }; -} - //********************************************************************************************* //! Command Functions //********************************************************************************************* @@ -62,29 +44,46 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) case POST: { size_t params = request->params(); + + std::string ssid = std::string(); + std::string password = std::string(); + int channel = 0; + bool adhoc = false; + + log_d("Number of Params: %d", params); for (size_t i = 0; i < params; i++) { AsyncWebParameter *param = request->getParam(i); - if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + if (param->name() == "ssid") { - localAPWifiConfig.ssid = param->value().c_str(); - localAPWifiConfig.pass = param->value().c_str(); - localAPWifiConfig.channel = atoi(param->value().c_str()); - localAPWifiConfig.adhoc = atoi(param->value().c_str()); + ssid = param->value().c_str(); } - else + else if (param->name() == "password") { - localWifiConfig.ssid = param->value().c_str(); - localWifiConfig.pass = param->value().c_str(); - localWifiConfig.channel = atoi(param->value().c_str()); - localWifiConfig.adhoc = atoi(param->value().c_str()); + password = param->value().c_str(); + } + else if (param->name() == "channel") + { + channel = atoi(param->value().c_str()); + } + else if (param->name() == "adhoc") + { + adhoc = atoi(param->value().c_str()); } log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } - ssid_write = true; - pass_write = true; - channel_write = true; + + if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + { + network->configManager->setAPWifiConfig(ssid, password, (uint8_t *)channel, adhoc, true); + } + else + { + network->configManager->setWifiConfig(ssid, ssid, password, (uint8_t *)channel, adhoc, true); + } + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); + network->configManager->wifiConfigSave(); break; } default: @@ -96,25 +95,6 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) } } -/** - * * 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 BaseAPI::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->setAPWifiConfig(localAPWifiConfig.ssid.c_str(), localAPWifiConfig.pass.c_str(), &localAPWifiConfig.channel, localAPWifiConfig.adhoc, true); - else - network->configManager->setWifiConfig(localWifiConfig.ssid.c_str(), localWifiConfig.ssid.c_str(), localWifiConfig.pass.c_str(), &localWifiConfig.channel, localAPWifiConfig.adhoc, true); - network->configManager->save(); - } -} - //! TODO: ADD JSON handlers for the POST requests void BaseAPI::handleJson(AsyncWebServerRequest *request) { @@ -151,27 +131,27 @@ void BaseAPI::handleJson(AsyncWebServerRequest *request) { network->configManager->getDeviceConfig()->data_json = true; Network_Utilities::my_delay(1L); - String temp = network->configManager->getDeviceConfig()->data_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; + std::string temp = network->configManager->getDeviceConfig()->data_json_string; + request->send(200, MIMETYPE_JSON, temp.c_str()); + temp = std::string(); break; } case SETTINGS: { network->configManager->getDeviceConfig()->config_json = true; Network_Utilities::my_delay(1L); - String temp = network->configManager->getDeviceConfig()->config_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; + std::string temp = network->configManager->getDeviceConfig()->config_json_string; + request->send(200, MIMETYPE_JSON, temp.c_str()); + temp = std::string(); break; } case CONFIG: { network->configManager->getDeviceConfig()->settings_json = true; Network_Utilities::my_delay(1L); - String temp = network->configManager->getDeviceConfig()->settings_json_string; - request->send(200, MIMETYPE_JSON, temp); - temp = ""; + std::string temp = network->configManager->getDeviceConfig()->settings_json_string; + request->send(200, MIMETYPE_JSON, temp.c_str()); + temp = std::string(); break; } default: @@ -278,14 +258,45 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) { case GET: { + // create temporary variables to store the values + int temp_camera_framesize = 0; + int temp_camera_vflip = 0; + int temp_camera_hflip = 0; + int temp_camera_quality = 0; + int params = request->params(); for (int i = 0; i < params; i++) { AsyncWebParameter *param = request->getParam(i); - camera->setCameraResolution((framesize_t)atoi(param->value().c_str())); - camera->setVFlip(atoi(param->value().c_str())); - camera->setHFlip(atoi(param->value().c_str())); + if (param->name() == "framesize") + { + temp_camera_framesize = param->value().toInt(); + } + else if (param->name() == "vflip") + { + temp_camera_vflip = param->value().toInt(); + } + else if (param->name() == "hflip") + { + temp_camera_hflip = param->value().toInt(); + } + else if (param->name() == "quality") + { + temp_camera_quality = param->value().toInt(); + } } + + // set the values for this instance + camera->setCameraResolution((framesize_t)temp_camera_framesize); + camera->setVFlip(temp_camera_vflip); + camera->setHFlip(temp_camera_hflip); + //! TODO: Need to add -> camera->setQuality(temp_camera_quality); + + network->configManager->setCameraConfig((uint8_t *)temp_camera_vflip, (uint8_t *)temp_camera_framesize, (uint8_t *)temp_camera_hflip, (uint8_t *)temp_camera_quality, true); + network->configManager->cameraConfigSave(); + + + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera Settings have been set.\"}"); break; } diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index b54db87..8c5e088 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -8,25 +8,6 @@ class BaseAPI : public API_Utilities { protected: - struct LocalWifiConfig - { - std::string ssid; - std::string pass; - uint8_t channel; - bool adhoc; - }; - - LocalWifiConfig localWifiConfig; - - struct LocalAPWifiConfig - { - std::string ssid; - std::string pass; - uint8_t channel; - }; - - LocalWifiConfig localAPWifiConfig; - enum JSON_TYPES { CONFIG, @@ -78,8 +59,6 @@ public: virtual ~BaseAPI(); virtual void begin(); - virtual void setupServer(); - void triggerWifiConfigWrite(); }; #endif // BASEAPI_HPP \ No newline at end of file diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 501fa5d..944b517 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -82,6 +82,5 @@ void loop() { ota.HandleOTAUpdate(); ledManager.displayStatus(); - apiServer.triggerWifiConfigWrite(); // serialManager.handleSerial(); } \ No newline at end of file From b26f7d7a2202dc3a79055502548f585e07e4a2af Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 00:51:37 +0100 Subject: [PATCH 066/153] oopsie update - Forgot to add constructor for WiFiConfig_t struct. Woops. --- ESP/lib/src/data/config/project_config.hpp | 10 ++++++++++ ESP/src/main.cpp | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 0b40c27..e4a2500 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -44,6 +44,16 @@ public: struct WiFiConfig_t { + //! Constructor for WiFiConfig_t - allows us to use emplace_back + WiFiConfig_t(const std::string &name, + const std::string &ssid, + const std::string &password, + uint8_t channel, + bool adhoc) : name(std::move(name)), + ssid(std::move(ssid)), + password(std::move(password)), + channel(channel), + adhoc(adhoc) {} std::string name; std::string ssid; std::string password; diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 944b517..55fe156 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -46,10 +46,12 @@ void setup() { case WiFiState_e::WiFiState_Disconnected: { + //! TODO: Implement break; } case WiFiState_e::WiFiState_Disconnecting: { + //! TODO: Implement break; } case WiFiState_e::WiFiState_ADHOC: @@ -68,10 +70,12 @@ void setup() } case WiFiState_e::WiFiState_Connecting: { + //! TODO: Implement break; } case WiFiState_e::WiFiState_Error: { + //! TODO: Implement break; } } From 23a5b18dcd9cbe8345119214228864647cfd5808 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 00:53:21 +0100 Subject: [PATCH 067/153] update - Fix WiFiHandler logging network name issue --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index d3334d6..c0676b0 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -57,7 +57,7 @@ void WiFiHandler::setupWifi() WiFi.setSleep(WIFI_PS_NONE); 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.c_str()); WiFi.begin(networkIterator->ssid.c_str(), networkIterator->password.c_str()); count++; From 7e2a96b9678666154c5b7b93b233b381613e45be Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 00:59:27 +0100 Subject: [PATCH 068/153] update - fix wifihandler while-loop break statement bug. Symbol was checking <= when it needs to be >= --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index c0676b0..5526bcb 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -28,8 +28,9 @@ void WiFiHandler::setupWifi() std::vector *networks = configManager->getWifiConfigs(); // check size of networks - log_i("Found %d networks", networks->size()); - + log_i("Found %d networks stored in the config", networks->size()); + + //? Maybe this way is better? I don't know /* if (networks->empty()) { log_e("No networks found in config"); @@ -38,6 +39,7 @@ void WiFiHandler::setupWifi() return; } */ + //* Check if there are networks in the config, if not move on to values used in ini file. if (networks->size() == 0) { log_e("No networks found in config"); @@ -68,7 +70,7 @@ void WiFiHandler::setupWifi() currentMillis = millis(); Helpers::update_progress_bar(progress, 100); delay(301); - if (((currentMillis - _previousMillis) >= connection_timeout) && (count <= networks->size())) + if (((currentMillis - _previousMillis) >= connection_timeout) && (count >= networks->size())) { log_i("\n[INFO]: WiFi connection timed out.\n"); // we've tried all saved networks, none worked, let's error out From 80d7e34f3add659d97de1c685de49bbeb6f106a1 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 13:23:21 +0100 Subject: [PATCH 069/153] update - Fix ESP crashing when camera probe fails --- ESP/lib/src/io/camera/cameraHandler.cpp | 26 ++++++++++++------------- ESP/lib/src/io/camera/cameraHandler.hpp | 2 +- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index 6be5975..348db73 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -1,6 +1,6 @@ #include "cameraHandler.hpp" -int CameraHandler::setupCamera() +bool CameraHandler::setupCamera() { log_d("Setting up camera \r\n"); @@ -45,6 +45,17 @@ int CameraHandler::setupCamera() esp_err_t err = esp_camera_init(&config); + if (err != ESP_OK) + { + log_e("Camera initialization failed with error: 0x%x \r\n", err); + log_e("Camera most likely not seated properly in the socket. Please fix the camera and reboot the device.\r\n"); + //! TODO add led blinking here + return false; + } + + log_d("Sucessfully initialized the camera!"); + //! TODO add led blinking here + camera_sensor = esp_camera_sensor_get(); // fixes corrupted jpegs, https://github.com/espressif/esp32-camera/issues/203 camera_sensor->set_reg(camera_sensor, 0xff, 0xff, 0x00); // banksel @@ -68,18 +79,7 @@ int CameraHandler::setupCamera() camera_sensor->set_colorbar(camera_sensor, 0); // 0 = disable , 1 = enable camera_sensor->set_special_effect(camera_sensor, 2); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 4 - Green Tint, 5 - Blue Tint, 6 - Sepia) - if (err != ESP_OK) - { - log_e("Camera initialization failed with error: 0x%x \r\n", err); - //! TODO add led blinking here - return -1; - } - else - { - log_d("Sucessfully initialized the camera!"); - //! TODO add led blinking here - return 0; - } + return true; } void CameraHandler::update(ObserverEvent::Event event) diff --git a/ESP/lib/src/io/camera/cameraHandler.hpp b/ESP/lib/src/io/camera/cameraHandler.hpp index 47d2440..2e93b05 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -13,7 +13,7 @@ private: public: CameraHandler(ProjectConfig *configManager) : configManager(configManager) {} - int setupCamera(); + bool setupCamera(); int setCameraResolution(framesize_t frameSize); int setVFlip(int direction); int setHFlip(int direction); From 2887baabee20a45a7a2d503b0d2e294492fbc288 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 13:23:37 +0100 Subject: [PATCH 070/153] update - Begin removing commented/unneeded code --- .../network/api/utilities/apiUtilities.cpp | 76 +++---------------- .../network/api/utilities/apiUtilities.hpp | 7 -- 2 files changed, 9 insertions(+), 74 deletions(-) diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index 4f2fd54..7b1930c 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -10,24 +10,20 @@ const char *API_Utilities::MIMETYPE_HTML{"text/html"}; // const char *BaseAPI::MIMETYPE_ICO{"image/x-icon"}; const char *API_Utilities::MIMETYPE_JSON{"application/json"}; -bool API_Utilities::ssid_write = false; -bool API_Utilities::pass_write = false; -bool API_Utilities::channel_write = false; - //********************************************************************************************* //! API Utilities //********************************************************************************************* API_Utilities::API_Utilities(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - const std::string &api_url) : server(new AsyncWebServer(CONTROL_PORT)), - stateManager(stateManager), - network(network), - camera(camera), - api_url(api_url) {} - + WiFiHandler *network, + CameraHandler *camera, + StateManager *stateManager, + const std::string &api_url) : server(new AsyncWebServer(CONTROL_PORT)), + stateManager(stateManager), + network(network), + camera(camera), + api_url(api_url) {} + API_Utilities::~API_Utilities() {} std::string API_Utilities::shaEncoder(std::string data) @@ -137,57 +133,3 @@ void API_Utilities::printASCII() Serial.println(F(" ")); Serial.println(F(" <============================================================================================================================> ")); } - -/* bool API_Utilities::initSPIFFS() -{ - if (!SPIFFS.begin(false)) - { - log_e("An error has occurred while mounting SPIFFS"); - return false; - } - log_i("SPIFFS mounted successfully"); - return true; -} */ - -// Read File from SPIFFS -/* std::string API_Utilities::readFile(fs::FS &fs, std::string path) -{ - log_i("Reading file: %s\r\n", path.c_str()); - - File file = fs.open(path.c_str()); - if (!file || file.isDirectory()) - { - log_e("[INFO]: Failed to open file for reading"); - return std::string(); - } - - std::string fileContent; - while (file.available()) - { - fileContent = file.readStringUntil('#').c_str(); - break; - } - return fileContent; -} */ - -// Write file to SPIFFS -/* void API_Utilities::writeFile(fs::FS &fs, std::string path, std::string message) -{ - log_i("[Writing File]: Writing file: %s\r\n", path); - Network_Utilities::my_delay(0.1L); - - File file = fs.open(path.c_str(), FILE_WRITE); - if (!file) - { - log_i("[Writing File]: failed to open file for writing"); - return; - } - if (file.print(message.c_str())) - { - log_i("[Writing File]: file written"); - } - else - { - log_i("[Writing File]: file write failed"); - } -} */ diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index bb67c7f..540b4fe 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -37,11 +37,8 @@ public: virtual ~API_Utilities(); static void printASCII(); - //static bool initSPIFFS(); protected: void notFound(AsyncWebServerRequest *request) const; - //static std::string readFile(fs::FS &fs, std::string path); - // void writeFile(fs::FS &fs, std::string path, std::string message); std::string shaEncoder(std::string data); std::unordered_map _networkMethodsMap = { {0b00000001, "GET"}, @@ -81,10 +78,6 @@ protected: protected: std::string api_url; - static bool ssid_write; - static bool pass_write; - static bool channel_write; - static const char *MIMETYPE_HTML; /* static const char *MIMETYPE_CSS; */ /* static const char *MIMETYPE_JS; */ From 7fbe2ea4464e9c152f4359c15bb9fd1bf9cada7b Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 13:32:42 +0100 Subject: [PATCH 071/153] update - misspelled successfully - lol --- ESP/lib/src/io/camera/cameraHandler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index 348db73..f119c58 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -53,7 +53,7 @@ bool CameraHandler::setupCamera() return false; } - log_d("Sucessfully initialized the camera!"); + log_d("Successfully initialized the camera!"); //! TODO add led blinking here camera_sensor = esp_camera_sensor_get(); From 7a06a8da5cf779675a63aa8935ffb4ed27a1185f Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 16:25:53 +0100 Subject: [PATCH 072/153] update - Add user-configured wifi channel to constructor --- ESP/src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 55fe156..c668f10 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -20,7 +20,7 @@ OTA ota(&deviceConfig); LEDManager ledManager(33); CameraHandler cameraHandler(&deviceConfig); // SerialManager serialManager(&deviceConfig); -WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, 1); +WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); APIServer apiServer(CONTROL_SERVER_PORT, &wifiHandler, &cameraHandler, &wifiStateManager, "/control"); MDNSHandler mdnsHandler(&mdnsStateManager, &deviceConfig); StreamServer streamServer(STREAM_SERVER_PORT); From d8f40da5a6ac9e9f6f9060196b50206768c0af0d Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 17:04:28 +0100 Subject: [PATCH 073/153] update - Fix setWiFi crashing due to incorrect cast of int to byte. - Update strings to use assign method. --- ESP/lib/src/data/config/project_config.cpp | 22 ++++++++------------- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 21 ++++++++++---------- 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 1be1fb2..3f2cabe 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -157,15 +157,12 @@ void ProjectConfig::load() void ProjectConfig::setDeviceConfig(const std::string &name, const std::string &OTAPassword, int *OTAPort, bool shouldNotify) { log_d("Updating device config"); - this->config.device = { - name, - OTAPassword, - *OTAPort, - }; + this->config.device.name.assign(name); + this->config.device.OTAPassword.assign(OTAPassword); + this->config.device.OTAPort = *OTAPort; + if (shouldNotify) - { this->notify(ObserverEvent::deviceConfigUpdated); - } } void ProjectConfig::setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify) @@ -209,15 +206,12 @@ void ProjectConfig::setWifiConfig(const std::string &networkName, const std::str void ProjectConfig::setAPWifiConfig(const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify) { - this->config.ap_network = { - ssid, - password, - *channel, - }; + this->config.ap_network.ssid.assign(ssid); + this->config.ap_network.password.assign(password); + this->config.ap_network.channel = *channel; + this->config.ap_network.adhoc = adhoc; log_d("Updating access point config"); if (shouldNotify) - { this->notify(ObserverEvent::networksConfigUpdated); - } } \ No newline at end of file diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 7e8d491..23ed138 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -43,15 +43,15 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) { case POST: { - size_t params = request->params(); + int params = request->params(); - std::string ssid = std::string(); - std::string password = std::string(); - int channel = 0; - bool adhoc = false; + std::string ssid; + std::string password; + uint8_t channel = 0; + uint8_t adhoc = 0; log_d("Number of Params: %d", params); - for (size_t i = 0; i < params; i++) + for (int i = 0; i < params; i++) { AsyncWebParameter *param = request->getParam(i); if (param->name() == "ssid") @@ -64,22 +64,23 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) } else if (param->name() == "channel") { - channel = atoi(param->value().c_str()); + channel = (uint8_t)atoi(param->value().c_str()); } else if (param->name() == "adhoc") { - adhoc = atoi(param->value().c_str()); + adhoc = (uint8_t)atoi(param->value().c_str()); } + log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { - network->configManager->setAPWifiConfig(ssid, password, (uint8_t *)channel, adhoc, true); + network->configManager->setAPWifiConfig(ssid, password, &channel, adhoc, true); } else { - network->configManager->setWifiConfig(ssid, ssid, password, (uint8_t *)channel, adhoc, true); + network->configManager->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); } request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); From 30212835fd95cf11ea39a814fddd699662cb204b Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 17:10:50 +0100 Subject: [PATCH 074/153] update - Fixed a minor bug in the wifihandler not displaying the connected network properly --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 5526bcb..f44f003 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -81,7 +81,7 @@ void WiFiHandler::setupWifi() return; } } - log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid); + log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid.c_str()); stateManager->setState(WiFiState_e::WiFiState_Connected); } } From 9fc62b6a36181dc19d6410252fce370dacc8ae7d Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 17:11:16 +0100 Subject: [PATCH 075/153] update - Revert initConfig to use empty string syntax. Easier to read. --- ESP/lib/src/data/config/project_config.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 3f2cabe..eb4997d 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -28,14 +28,14 @@ void ProjectConfig::initConfig() false, false, false, - std::string(), - std::string(), - std::string(), + "", + "", + "", }; this->config.ap_network = { - std::string(), - std::string(), + "", + "", 0, }; } From 13d307d9640ca82ab7a65ede7aedc1625f85971e Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Wed, 31 Aug 2022 17:43:18 +0100 Subject: [PATCH 076/153] update - Fix the setWiFi method not writing to the correct config - Depreciate the to_string method in favour of append method and itoa --- ESP/lib/src/data/config/project_config.cpp | 35 ++++++++++++++------- ESP/lib/src/data/config/project_config.hpp | 1 + ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 8 +++-- 3 files changed, 30 insertions(+), 14 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index eb4997d..b968f6c 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -36,7 +36,7 @@ void ProjectConfig::initConfig() this->config.ap_network = { "", "", - 0, + 1, }; } @@ -56,12 +56,19 @@ void ProjectConfig::wifiConfigSave() /* WiFi Config */ putInt("networkCount", this->config.networks.size()); + std::string name = "name"; + std::string ssid = "ssid"; + std::string password = "pass"; + std::string channel = "channel"; for (int i = 0; i < this->config.networks.size(); i++) { - const std::string &name = std::to_string(i) + "name"; - const std::string &ssid = std::to_string(i) + "ssid"; - const std::string &password = std::to_string(i) + "pass"; - const std::string &channel = std::to_string(i) + "channel"; + char buffer[2]; + std::string iter_str = Helpers::itoa(i, buffer, 10); + + name.append(iter_str); + ssid.append(iter_str); + password.append(iter_str); + channel.append(iter_str); putString(name.c_str(), this->config.networks[i].name.c_str()); putString(ssid.c_str(), this->config.networks[i].ssid.c_str()); @@ -75,7 +82,6 @@ void ProjectConfig::wifiConfigSave() putUInt("apChannel", this->config.ap_network.channel); log_i("Project config saved and system is rebooting"); - delay(5000); ESP.restart(); } @@ -120,12 +126,19 @@ void ProjectConfig::load() /* WiFi Config */ int networkCount = getInt("networkCount", 0); + std::string name = "name"; + std::string ssid = "ssid"; + std::string password = "pass"; + std::string channel = "channel"; for (int i = 0; i < networkCount; i++) { - const std::string &name = std::to_string(i) + "name"; - const std::string &ssid = std::to_string(i) + "ssid"; - const std::string &password = std::to_string(i) + "pass"; - const std::string &channel = std::to_string(i) + "channel"; + char buffer[2]; + std::string iter_str = Helpers::itoa(i, buffer, 10); + + name.append(iter_str); + ssid.append(iter_str); + password.append(iter_str); + channel.append(iter_str); const std::string &temp_1 = getString(name.c_str()).c_str(); const std::string &temp_2 = getString(ssid.c_str()).c_str(); @@ -143,7 +156,7 @@ void ProjectConfig::load() /* AP Config */ this->config.ap_network.ssid = getString("apSSID", "easynetwork").c_str(); this->config.ap_network.password = getString("apPass", "12345678").c_str(); - this->config.ap_network.channel = getUInt("apChannel", 0); + this->config.ap_network.channel = getUInt("apChannel", 1); this->_already_loaded = true; this->notify(ObserverEvent::configLoaded); diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index e4a2500..10cdcba 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -7,6 +7,7 @@ #include #include "data/utilities/Observer.hpp" +#include "data/utilities/helpers.hpp" class ProjectConfig : public Preferences, public ISubject { diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 23ed138..d61ad58 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -74,14 +74,16 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } - if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + network->configManager->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); + + /* if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { network->configManager->setAPWifiConfig(ssid, password, &channel, adhoc, true); } else { - network->configManager->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); - } + + } */ request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); network->configManager->wifiConfigSave(); From 8bb1eccd122924de022770e4e3a6f5aa0f32504a Mon Sep 17 00:00:00 2001 From: Lorow Date: Thu, 1 Sep 2022 22:50:14 +0200 Subject: [PATCH 077/153] Add cameraReset endpoint, move logo from apiutils to separate package, fix emplace_back - missing param for adhoc Known issues: doesn't compile, linker can't seem to find a definition of setCameraConfig --- ESP/lib/src/data/config/project_config.cpp | 27 ++++---- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 10 ++- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 3 +- .../network/api/utilities/apiUtilities.cpp | 66 +------------------ .../network/api/utilities/apiUtilities.hpp | 1 - ESP/lib/src/network/api/webserverHandler.cpp | 2 +- ESP/src/main.cpp | 3 +- 7 files changed, 30 insertions(+), 82 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index b968f6c..7c0cf1f 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -147,10 +147,11 @@ void ProjectConfig::load() //! push_back creates a copy of the object, so we need to use emplace_back this->config.networks.emplace_back( - temp_1, - temp_2, - temp_3, - temp_4); + temp_1, + temp_2, + temp_3, + temp_4, + false); // TODO figure out if this should be a hardcoded false } /* AP Config */ @@ -194,10 +195,11 @@ void ProjectConfig::setWifiConfig(const std::string &networkName, const std::str if (networkToUpdate != nullptr) { this->config.networks.emplace_back( - networkName, - ssid, - password, - *channel); + networkName, + ssid, + password, + *channel, + false); // TODO figure out if this should be a hardcoded false } log_d("Updating wifi config"); } @@ -206,10 +208,11 @@ void ProjectConfig::setWifiConfig(const std::string &networkName, const std::str { //! push_back creates a copy of the object, so we need to use emplace_back this->config.networks.emplace_back( - networkName, - ssid, - password, - *channel); + networkName, + ssid, + password, + *channel, + false); // TODO figure out if this should be a hardcoded false networkToUpdate = &this->config.networks[0]; } diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index d61ad58..f360783 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -82,7 +82,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) } else { - + } */ request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); @@ -446,3 +446,11 @@ void BaseAPI::setCameraVar(AsyncWebServerRequest *request) response->addHeader("Access-Control-Allow-Origin", "*"); request->send(response); } + +void BaseAPI::restartCamera(AsyncWebServerRequest *request) +{ + int mode = atoi(request->arg("mode").c_str()); + camera->resetCamera((bool)mode); + + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera had been restarted.\"}"); +} diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index 8c5e088..ac8a765 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -41,6 +41,7 @@ protected: void getCameraStatus(AsyncWebServerRequest *request); void setCameraVar(AsyncWebServerRequest *request); void setCamera(AsyncWebServerRequest *request); + void restartCamera(AsyncWebServerRequest *request); /* Route Command types */ using route_method = void (BaseAPI::*)(AsyncWebServerRequest *); @@ -56,7 +57,7 @@ public: CameraHandler *camera, StateManager *stateManager, const std::string &api_url); - + virtual ~BaseAPI(); virtual void begin(); }; diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index 7b1930c..e17fde7 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -68,68 +68,4 @@ void API_Utilities::notFound(AsyncWebServerRequest *request) const { request->send(404, "text/plain", "Request Not found using unknown method"); } -} - -void API_Utilities::printASCII() -{ - Serial.println(F(" : === WELCOME === TO === : ")); - Serial.println(F(" <===========================================================================================================================> ")); - Serial.println(F(" ██████╗ ██████╗ ███████╗███╗ ██╗██╗██████╗ ██╗███████╗ ")); - Serial.println(F(" ██╔═══██╗██╔══██╗██╔════╝████╗ ██║██║██╔══██╗██║██╔════╝ ")); - Serial.println(F(" ██║ ██║██████╔╝█████╗ ██╔██╗ ██║██║██████╔╝██║███████╗ ")); - Serial.println(F(" ██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║██║██╔══██╗██║╚════██║ ")); - Serial.println(F(" ╚██████╔╝██║ ███████╗██║ ╚████║██║██║ ██║██║███████║ ")); - Serial.println(F(" ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝╚═╝╚═╝ ╚═╝╚═╝╚══════╝ ")); - Serial.println(F(" ")); - Serial.println(F(" ██████████████ ")); - Serial.println(F(" ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░▒▒▓▓▓▓██ ")); - Serial.println(F(" ████▓▓░░░░▒▒░░░░░░▒▒░░░░░░▒▒░░████ ")); - Serial.println(F(" ██▓▓▒▒▓▓▓▓▒▒▒▒░░░░░░▒▒░░▒▒░░░░░░▒▒░░▒▒▓▓▓▓ ")); - Serial.println(F(" ██▓▓▒▒▒▒▒▒▒▒░░▒▒░░░░░░░░░░░░▒▒░░░░▒▒░░░░▒▒░░██ ")); - Serial.println(F(" ██▓▓▓▓░░░░▒▒░░░░▒▒▒▒░░░░░░░░░░▒▒░░ ░░░░░░░░▒▒░░██ ")); - Serial.println(F(" ██▓▓▓▓▓▓▓▓▓▓░░░░░░▒▒░░░░░░░░░░░░░░ ░░░░░░░░░░░░██ ")); - Serial.println(F(" ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░░░ ░░ ▒▒▒▒██ ")); - Serial.println(F(" ██▓▓▒▒▒▒▒▒▒▒░░░░▒▒░░░░░░░░░░░░░░░░░░ ░░░░██ ")); - Serial.println(F(" ▓▓▓▓▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░░░░░░░░░▓▓▓▓▓▓▓▓▓▓ ░░ ▒▒▓▓ ")); - Serial.println(F(" ██▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓▓▓ ░░██ ")); - Serial.println(F(" ▓▓▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░ ▓▓▒▒▒▒▒▒▒▒░░░░▒▒▒▒▓▓▒▒ ░░▒▒▓▓ ")); - Serial.println(F(" ██▓▓▒▒░░░░░░▒▒▒▒▒▒░░░░░░░░░░░░░░░░▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░▒▒▓▓▓▓ ░░██ ")); - Serial.println(F(" ██▓▓▓▓▒▒▒▒▒▒▒▒░░░░▒▒░░░░░░░░░░░░ ▒▒▒▒▒▒▒▒▒▒▒▒████▓▓░░░░▒▒▓▓ ░░██ ")); - Serial.println(F(" ██▓▓▒▒▒▒▒▒▓▓▒▒▓▓░░░░░░░░░░░░░░░░░░▓▓▒▒▒▒░░▒▒▒▒████ ▒▒██░░▒▒▓▓▓▓ ░░██ ")); - Serial.println(F(" ██▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▓▓░░▒▒▒▒▒▒██████▒▒ ▓▓▓▓░░▓▓▓▓ ░░██ ")); - Serial.println(F(" ██▓▓▒▒▒▒░░▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▓▓▒▒░░▒▒░░████████▓▓ ██▓▓▒▒▓▓ ░░██ ")); - Serial.println(F(" ██▓▓▓▓▓▓▓▓▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░▒▒░░▒▒░░▒▒██████████▒▒██▒▒▒▒▓▓ ░░██ ")); - Serial.println(F(" ██▓▓▒▒▒▒▒▒░░░░░░░░▒▒▒▒░░░░░░░░░░░░▒▒▒▒░░░░▒▒██▒▒██████ ██▒▒▒▒▓▓ ░░██ ")); - Serial.println(F(" ██▒▒▒▒▒▒░░▓▓▓▓▓▓▒▒░░░░░░░░░░░░░░░░▒▒░░ ▒▒░░██ ▒▒████▒▒██▒▒▒▒▓▓ ░░██ ")); - Serial.println(F(" ██▓▓▓▓▓▓▓▓░░▒▒▒▒░░▒▒░░░░░░░░░░░░░░▒▒▒▒░░░░░░▒▒██ ██████▒▒▒▒▒▒▓▓░░░░██ ")); - Serial.println(F(" ██▓▓██▓▓▒▒▒▒▓▓░░░░▒▒░░░░░░░░░░░░░░░░░░▒▒▒▒░░▒▒░░▒▒██████▒▒▒▒▒▒▓▓ ░░██ ")); - Serial.println(F(" ██▓▓██▒▒▒▒▒▒▒▒▓▓▓▓▒▒░░░░░░░░░░░░░░░░░░▒▒░░▒▒░░▒▒░░▒▒░░▒▒▒▒▒▒▒▒▓▓░░░░██ ")); - Serial.println(F(" ██▒▒▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░▒▒░░▒▒░░░░░░▒▒▒▒▒▒▒▒▓▓ ░░░░██ ")); - Serial.println(F(" ██▒▒▒▒▓▓██▓▓▓▓▒▒▒▒▒▒▒▒░░░░░░░░▒▒░░░░░░░░░░░░▒▒▒▒▒▒░░▒▒▒▒▒▒▓▓▓▓ ░░░░██ ")); - Serial.println(F(" ▓▓▓▓▒▒▒▒▓▓██▓▓▒▒▒▒▒▒░░░░▒▒▒▒░░▒▒░░░░░░░░░░░░░░░░░░▒▒▒▒▓▓▓▓▓▓░░░░░░░░▒▒██ ")); - Serial.println(F(" ██▒▒▒▒▓▓▒▒▓▓██▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░░░██ ")); - Serial.println(F(" ██▒▒▒▒▓▓░░▒▒▒▒██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▒▒░░▒▒██ ")); - Serial.println(F(" ██▒▒▒▒▓▓▒▒░░▓▓▒▒██▓▓▒▒▒▒▒▒▒▒░░▓▓▒▒▓▓▒▒░░░░▒▒░░░░░░░░░░░░░░░░░░░░░░▓▓██ ")); - Serial.println(F(" ██▒▒▒▒▒▒░░▒▒▒▒▒▒▓▓██▓▓▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▓▓░░░░░░░░░░▒▒░░░░▒▒░░▒▒▒▒██ ")); - Serial.println(F(" ██▒▒▒▒░░▒▒░░▒▒████ ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░▓▓▒▒▒▒▒▒▓▓▒▒██ ")); - Serial.println(F(" ██▒▒▓▓░░▒▒░░▓▓ ████▓▓▒▒▓▓▒▒▒▒▒▒░░▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒██▓▓ ")); - Serial.println(F(" ██▒▒▒▒▒▒▒▒ ██ ████▓▓▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒████ ")); - Serial.println(F(" ██▒▒▒▒▒▒▒▒░░██ ██████▓▓▒▒▒▒▒▒▒▒▓▓▓▓██████ ")); - Serial.println(F(" ██▒▒▒▒▒▒▒▒░░ ████ ██████████████ ")); - Serial.println(F(" ██▒▒▒▒▒▒▒▒░░ ░░████ ")); - Serial.println(F(" ████▒▒▒▒▒▒░░░░ ░░████ ")); - Serial.println(F(" ████▒▒▒▒▒▒░░░░ ░░██ ")); - Serial.println(F(" ████▒▒▒▒▒▒░░ ░░██ ")); - Serial.println(F(" ██▓▓▒▒▒▒░░ ▒▒▓▓ ")); - Serial.println(F(" ████▒▒░░ ▒▒██ ")); - Serial.println(F(" ▓▓▒▒░░░░██ ")); - Serial.println(F(" ██░░ ██ ")); - Serial.println(F(" ▓▓██ ██░░░░██ ")); - Serial.println(F(" ██░░██ ██░░░░██ ")); - Serial.println(F(" ██░░██ ██░░▒▒██ ")); - Serial.println(F(" ██░░▒▒████░░▒▒██ ")); - Serial.println(F(" ▓▓▒▒▒▒▒▒▒▒▓▓ ")); - Serial.println(F(" ████████ ")); - Serial.println(F(" ")); - Serial.println(F(" <============================================================================================================================> ")); -} +} \ No newline at end of file diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index 540b4fe..d5dab5a 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -36,7 +36,6 @@ public: const std::string &api_url); virtual ~API_Utilities(); - static void printASCII(); protected: void notFound(AsyncWebServerRequest *request) const; std::string shaEncoder(std::string data); diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index fe441a0..6f0e77b 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -39,7 +39,7 @@ void APIServer::setupServer() routes.emplace("setJson", &APIServer::handleJson); routes.emplace("setCamera", &APIServer::setCamera); routes.emplace("deleteRoute", &APIServer::deleteRoute); - + routes.emplace("restartCamera", &APIServer::restartCamera); // Camera Routes //! reserve enough memory for all routes - must be called after adding routes and before adding routes to route_map diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index c668f10..46212f4 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include //#include // Basic Serial Manager //#include Date: Thu, 1 Sep 2022 23:45:55 +0200 Subject: [PATCH 078/153] Add missing logo.hpp --- ESP/lib/src/logo/logo.hpp | 67 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 ESP/lib/src/logo/logo.hpp diff --git a/ESP/lib/src/logo/logo.hpp b/ESP/lib/src/logo/logo.hpp new file mode 100644 index 0000000..872dd5e --- /dev/null +++ b/ESP/lib/src/logo/logo.hpp @@ -0,0 +1,67 @@ + +namespace Logo +{ + static void printASCII() + { + Serial.println(F(" : === WELCOME === TO === : ")); + Serial.println(F(" <===========================================================================================================================> ")); + Serial.println(F(" ██████╗ ██████╗ ███████╗███╗ ██╗██╗██████╗ ██╗███████╗ ")); + Serial.println(F(" ██╔═══██╗██╔══██╗██╔════╝████╗ ██║██║██╔══██╗██║██╔════╝ ")); + Serial.println(F(" ██║ ██║██████╔╝█████╗ ██╔██╗ ██║██║██████╔╝██║███████╗ ")); + Serial.println(F(" ██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║██║██╔══██╗██║╚════██║ ")); + Serial.println(F(" ╚██████╔╝██║ ███████╗██║ ╚████║██║██║ ██║██║███████║ ")); + Serial.println(F(" ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝╚═╝╚═╝ ╚═╝╚═╝╚══════╝ ")); + Serial.println(F(" ")); + Serial.println(F(" ██████████████ ")); + Serial.println(F(" ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░▒▒▓▓▓▓██ ")); + Serial.println(F(" ████▓▓░░░░▒▒░░░░░░▒▒░░░░░░▒▒░░████ ")); + Serial.println(F(" ██▓▓▒▒▓▓▓▓▒▒▒▒░░░░░░▒▒░░▒▒░░░░░░▒▒░░▒▒▓▓▓▓ ")); + Serial.println(F(" ██▓▓▒▒▒▒▒▒▒▒░░▒▒░░░░░░░░░░░░▒▒░░░░▒▒░░░░▒▒░░██ ")); + Serial.println(F(" ██▓▓▓▓░░░░▒▒░░░░▒▒▒▒░░░░░░░░░░▒▒░░ ░░░░░░░░▒▒░░██ ")); + Serial.println(F(" ██▓▓▓▓▓▓▓▓▓▓░░░░░░▒▒░░░░░░░░░░░░░░ ░░░░░░░░░░░░██ ")); + Serial.println(F(" ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░░░ ░░ ▒▒▒▒██ ")); + Serial.println(F(" ██▓▓▒▒▒▒▒▒▒▒░░░░▒▒░░░░░░░░░░░░░░░░░░ ░░░░██ ")); + Serial.println(F(" ▓▓▓▓▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░░░░░░░░░▓▓▓▓▓▓▓▓▓▓ ░░ ▒▒▓▓ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓▓▓ ░░██ ")); + Serial.println(F(" ▓▓▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░ ▓▓▒▒▒▒▒▒▒▒░░░░▒▒▒▒▓▓▒▒ ░░▒▒▓▓ ")); + Serial.println(F(" ██▓▓▒▒░░░░░░▒▒▒▒▒▒░░░░░░░░░░░░░░░░▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░▒▒▓▓▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▓▓▒▒▒▒▒▒▒▒░░░░▒▒░░░░░░░░░░░░ ▒▒▒▒▒▒▒▒▒▒▒▒████▓▓░░░░▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▒▒▒▒▒▒▓▓▒▒▓▓░░░░░░░░░░░░░░░░░░▓▓▒▒▒▒░░▒▒▒▒████ ▒▒██░░▒▒▓▓▓▓ ░░██ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▓▓░░▒▒▒▒▒▒██████▒▒ ▓▓▓▓░░▓▓▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▒▒▒▒░░▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▓▓▒▒░░▒▒░░████████▓▓ ██▓▓▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▓▓▓▓▓▓▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░▒▒░░▒▒░░▒▒██████████▒▒██▒▒▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▒▒▒▒▒▒░░░░░░░░▒▒▒▒░░░░░░░░░░░░▒▒▒▒░░░░▒▒██▒▒██████ ██▒▒▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▒▒▒▒▒▒░░▓▓▓▓▓▓▒▒░░░░░░░░░░░░░░░░▒▒░░ ▒▒░░██ ▒▒████▒▒██▒▒▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▓▓▓▓▓▓▓▓░░▒▒▒▒░░▒▒░░░░░░░░░░░░░░▒▒▒▒░░░░░░▒▒██ ██████▒▒▒▒▒▒▓▓░░░░██ ")); + Serial.println(F(" ██▓▓██▓▓▒▒▒▒▓▓░░░░▒▒░░░░░░░░░░░░░░░░░░▒▒▒▒░░▒▒░░▒▒██████▒▒▒▒▒▒▓▓ ░░██ ")); + Serial.println(F(" ██▓▓██▒▒▒▒▒▒▒▒▓▓▓▓▒▒░░░░░░░░░░░░░░░░░░▒▒░░▒▒░░▒▒░░▒▒░░▒▒▒▒▒▒▒▒▓▓░░░░██ ")); + Serial.println(F(" ██▒▒▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░▒▒░░▒▒░░░░░░▒▒▒▒▒▒▒▒▓▓ ░░░░██ ")); + Serial.println(F(" ██▒▒▒▒▓▓██▓▓▓▓▒▒▒▒▒▒▒▒░░░░░░░░▒▒░░░░░░░░░░░░▒▒▒▒▒▒░░▒▒▒▒▒▒▓▓▓▓ ░░░░██ ")); + Serial.println(F(" ▓▓▓▓▒▒▒▒▓▓██▓▓▒▒▒▒▒▒░░░░▒▒▒▒░░▒▒░░░░░░░░░░░░░░░░░░▒▒▒▒▓▓▓▓▓▓░░░░░░░░▒▒██ ")); + Serial.println(F(" ██▒▒▒▒▓▓▒▒▓▓██▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░░░██ ")); + Serial.println(F(" ██▒▒▒▒▓▓░░▒▒▒▒██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▒▒░░▒▒██ ")); + Serial.println(F(" ██▒▒▒▒▓▓▒▒░░▓▓▒▒██▓▓▒▒▒▒▒▒▒▒░░▓▓▒▒▓▓▒▒░░░░▒▒░░░░░░░░░░░░░░░░░░░░░░▓▓██ ")); + Serial.println(F(" ██▒▒▒▒▒▒░░▒▒▒▒▒▒▓▓██▓▓▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▓▓░░░░░░░░░░▒▒░░░░▒▒░░▒▒▒▒██ ")); + Serial.println(F(" ██▒▒▒▒░░▒▒░░▒▒████ ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░▓▓▒▒▒▒▒▒▓▓▒▒██ ")); + Serial.println(F(" ██▒▒▓▓░░▒▒░░▓▓ ████▓▓▒▒▓▓▒▒▒▒▒▒░░▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒██▓▓ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒ ██ ████▓▓▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒████ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒░░██ ██████▓▓▒▒▒▒▒▒▒▒▓▓▓▓██████ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒░░ ████ ██████████████ ")); + Serial.println(F(" ██▒▒▒▒▒▒▒▒░░ ░░████ ")); + Serial.println(F(" ████▒▒▒▒▒▒░░░░ ░░████ ")); + Serial.println(F(" ████▒▒▒▒▒▒░░░░ ░░██ ")); + Serial.println(F(" ████▒▒▒▒▒▒░░ ░░██ ")); + Serial.println(F(" ██▓▓▒▒▒▒░░ ▒▒▓▓ ")); + Serial.println(F(" ████▒▒░░ ▒▒██ ")); + Serial.println(F(" ▓▓▒▒░░░░██ ")); + Serial.println(F(" ██░░ ██ ")); + Serial.println(F(" ▓▓██ ██░░░░██ ")); + Serial.println(F(" ██░░██ ██░░░░██ ")); + Serial.println(F(" ██░░██ ██░░▒▒██ ")); + Serial.println(F(" ██░░▒▒████░░▒▒██ ")); + Serial.println(F(" ▓▓▒▒▒▒▒▒▒▒▓▓ ")); + Serial.println(F(" ████████ ")); + Serial.println(F(" ")); + Serial.println(F(" <============================================================================================================================> ")); + } +}; \ No newline at end of file From d965ac466b0a77451e212bd702655ee4837354cb Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 1 Sep 2022 23:00:02 +0100 Subject: [PATCH 079/153] update - Fix the casting issue with setCamera - Fix the linker undefined error with setCameraConfig --- ESP/lib/src/data/config/project_config.cpp | 13 +++++++++++++ ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 20 +++++++++----------- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 7c0cf1f..11c261e 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -179,6 +179,19 @@ void ProjectConfig::setDeviceConfig(const std::string &name, const std::string & this->notify(ObserverEvent::deviceConfigUpdated); } +void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, bool shouldNotify) +{ + log_d("Updating camera config"); + this->config.camera.vflip = *vflip; + this->config.camera.framesize = *framesize; + this->config.camera.href = *href; + this->config.camera.quality = *quality; + + log_d("Updating Camera config"); + if (shouldNotify) + this->notify(ObserverEvent::networksConfigUpdated); +} + void ProjectConfig::setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify) { WiFiConfig_t *networkToUpdate = nullptr; diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index f360783..9550e5c 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -262,10 +262,10 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) case GET: { // create temporary variables to store the values - int temp_camera_framesize = 0; - int temp_camera_vflip = 0; - int temp_camera_hflip = 0; - int temp_camera_quality = 0; + uint8_t temp_camera_framesize = 0; + uint8_t temp_camera_vflip = 0; + uint8_t temp_camera_hflip = 0; + uint8_t temp_camera_quality = 0; int params = request->params(); for (int i = 0; i < params; i++) @@ -273,19 +273,19 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) AsyncWebParameter *param = request->getParam(i); if (param->name() == "framesize") { - temp_camera_framesize = param->value().toInt(); + temp_camera_framesize = (uint8_t)param->value().toInt(); } else if (param->name() == "vflip") { - temp_camera_vflip = param->value().toInt(); + temp_camera_vflip = (uint8_t)param->value().toInt(); } else if (param->name() == "hflip") { - temp_camera_hflip = param->value().toInt(); + temp_camera_hflip = (uint8_t)param->value().toInt(); } else if (param->name() == "quality") { - temp_camera_quality = param->value().toInt(); + temp_camera_quality = (uint8_t)param->value().toInt(); } } @@ -295,11 +295,9 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) camera->setHFlip(temp_camera_hflip); //! TODO: Need to add -> camera->setQuality(temp_camera_quality); - network->configManager->setCameraConfig((uint8_t *)temp_camera_vflip, (uint8_t *)temp_camera_framesize, (uint8_t *)temp_camera_hflip, (uint8_t *)temp_camera_quality, true); + network->configManager->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, true); network->configManager->cameraConfigSave(); - - request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera Settings have been set.\"}"); break; } From 36162d5d86cab659e99da13919b37af6c1cd0dc6 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 1 Sep 2022 23:01:30 +0100 Subject: [PATCH 080/153] update - make Logo printASCII function inline --- ESP/lib/src/logo/logo.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ESP/lib/src/logo/logo.hpp b/ESP/lib/src/logo/logo.hpp index 872dd5e..2512ddd 100644 --- a/ESP/lib/src/logo/logo.hpp +++ b/ESP/lib/src/logo/logo.hpp @@ -1,7 +1,7 @@ namespace Logo { - static void printASCII() + inline static void printASCII() { Serial.println(F(" : === WELCOME === TO === : ")); Serial.println(F(" <===========================================================================================================================> ")); From 622ea32fd815fd11ffcea61c3fd5b88e013736e0 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Fri, 2 Sep 2022 01:05:08 +0100 Subject: [PATCH 081/153] update - disable turning off the brownout-detector. Was added for personal debugging no longer needed --- ESP/lib/src/network/stream/streamServer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ESP/lib/src/network/stream/streamServer.cpp b/ESP/lib/src/network/stream/streamServer.cpp index aa58a0f..253fc60 100644 --- a/ESP/lib/src/network/stream/streamServer.cpp +++ b/ESP/lib/src/network/stream/streamServer.cpp @@ -83,7 +83,7 @@ esp_err_t StreamHelpers::stream(httpd_req_t *req) int StreamServer::startStreamServer() { - WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //! Turn-off the 'brownout detector' + //WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //! Turn-off the 'brownout detector' httpd_config_t config = HTTPD_DEFAULT_CONFIG(); config.stack_size = 20480; config.max_uri_handlers = 1; From 4987144a96cb747a5e17fa41ebd9877755a92749 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Fri, 2 Sep 2022 01:08:24 +0100 Subject: [PATCH 082/153] update - fix minor formatting --- ESP/lib/src/network/stream/streamServer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ESP/lib/src/network/stream/streamServer.cpp b/ESP/lib/src/network/stream/streamServer.cpp index 253fc60..96d08ef 100644 --- a/ESP/lib/src/network/stream/streamServer.cpp +++ b/ESP/lib/src/network/stream/streamServer.cpp @@ -85,7 +85,7 @@ int StreamServer::startStreamServer() { //WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //! Turn-off the 'brownout detector' httpd_config_t config = HTTPD_DEFAULT_CONFIG(); - config.stack_size = 20480; + config.stack_size = 20480; config.max_uri_handlers = 1; config.server_port = this->STREAM_SERVER_PORT; config.ctrl_port = this->STREAM_SERVER_PORT; From e4dc25a2a6357c4e3b5488019f590d4ee7421012 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 5 Sep 2022 12:30:36 +0100 Subject: [PATCH 083/153] update - remove delay() method and change with my_delay - my_delay is a for loop that counts down --- ESP/lib/src/io/camera/cameraHandler.cpp | 8 ++++---- ESP/lib/src/io/camera/cameraHandler.hpp | 1 + ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 1 - 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index f119c58..654106f 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -125,20 +125,20 @@ int CameraHandler::setHFlip(int direction) // TODO: Add to API void CameraHandler::resetCamera(bool type) { - if (type == 1) + if (type) { // power cycle the camera module (handy if camera stops responding) digitalWrite(PWDN_GPIO_NUM, HIGH); // turn power off to camera module - delay(300); + Network_Utilities::my_delay(0.3L); // a for loop with a delay of 300ms digitalWrite(PWDN_GPIO_NUM, LOW); - delay(300); + Network_Utilities::my_delay(0.3L); setupCamera(); } else { // reset via software (handy if you wish to change resolution or image type etc. - see test procedure) esp_camera_deinit(); - delay(50); + Network_Utilities::my_delay(0.05L); setupCamera(); } } \ No newline at end of file diff --git a/ESP/lib/src/io/camera/cameraHandler.hpp b/ESP/lib/src/io/camera/cameraHandler.hpp index 2e93b05..458cf02 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -2,6 +2,7 @@ #include #include #include "data/utilities/Observer.hpp" +#include "data/utilities/network_utilities.hpp" #include "data/config/project_config.hpp" class CameraHandler : IObserver diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 9550e5c..9d05d6f 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -178,7 +178,6 @@ void BaseAPI::rebootDevice(AsyncWebServerRequest *request) { case GET: { - delay(20000); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Rebooting Device\"}"); ESP.restart(); } From 6217195248a0537092dc2f52a851819dd1ed0796 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 5 Sep 2022 12:37:57 +0100 Subject: [PATCH 084/153] update - Added debug-mode support - to disable DebugOutput change debug_mode to 0 --- ESP/platformio.ini | 5 +++++ ESP/src/main.cpp | 5 ++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 7a603a5..1e4c350 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -11,6 +11,9 @@ [platformio] default_envs = esp32Cam ; do not change this value +[debug_mode] +debug_mode = 1 ; 0 = off, 1 = on + ; The below options are available for all environments ; The ssid and password are requried for the trackers to connect to your network!!! [wifi] @@ -85,6 +88,8 @@ build_flags = -DADHOC_CHANNEL=${wifi.adhocChannel} ; -DWIFI_CHANNEL=${wifi.channel} ; + + -DDEBUG_MODE=${debug_mode.debug_mode} ; Set the debug mode '-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 diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 46212f4..1e4b23e 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -8,8 +8,7 @@ #include #include #include -//#include // Basic Serial Manager -//#include // Serial Manager #include @@ -29,7 +28,7 @@ StreamServer streamServer(STREAM_SERVER_PORT); void setup() { Serial.begin(115200); - Serial.setDebugOutput(true); + Serial.setDebugOutput(DEBUG_MODE); Serial.println("\n"); Logo::printASCII(); From f23c477315430ef2988282ddd3ba3c8d213955d4 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 5 Sep 2022 12:43:22 +0100 Subject: [PATCH 085/153] update - Remove debug_mode option in favour of setting it in the proper environment. - Now, the user does nothing but pick the environment --- ESP/platformio.ini | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 1e4c350..66cbc4c 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -11,9 +11,6 @@ [platformio] default_envs = esp32Cam ; do not change this value -[debug_mode] -debug_mode = 1 ; 0 = off, 1 = on - ; The below options are available for all environments ; The ssid and password are requried for the trackers to connect to your network!!! [wifi] @@ -88,8 +85,6 @@ build_flags = -DADHOC_CHANNEL=${wifi.adhocChannel} ; -DWIFI_CHANNEL=${wifi.channel} ; - - -DDEBUG_MODE=${debug_mode.debug_mode} ; Set the debug mode '-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 @@ -157,6 +152,8 @@ build_flags = ${common.build_flags} -DHREF_GPIO_NUM=${pinoutsESPCAM.HREF_GPIO_NUM} ; Set the HREF pin -DPCLK_GPIO_NUM=${pinoutsESPCAM.PCLK_GPIO_NUM} ; Set the PCLK pin + -DDEBUG_MODE=1 ; Set the debug mode + build_unflags = ${common.build_unflags} board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} @@ -173,6 +170,7 @@ monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} build_flags = ${common.build_flags} + -DDEBUG_MODE=0 ; Set the debug mode -DCORE_DEBUG_LEVEL=1 -DVERSION=${common.release_version} build_unflags = ${common.build_unflags} @@ -189,6 +187,7 @@ board = esp32cam framework = ${common.framework} build_flags = ${common.build_flags} + -DDEBUG_MODE=0 ; Set the debug mode -DCORE_DEBUG_LEVEL=1 -DDEBUG_ESP_OTA -DVERSION=${common.release_version} @@ -218,6 +217,7 @@ monitor_filters = ${common.monitor_filters} ;monitor_dtr = ${common.monitor_dtr} build_flags = ${common.build_flags} + -DDEBUG_MODE=1 ; Set the debug mode -DVERSION=0 ; CAMERA PINOUT DEFINITIONS @@ -256,6 +256,7 @@ monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} build_flags = ${common.build_flags} + -DDEBUG_MODE=0 ; Set the debug mode -DCORE_DEBUG_LEVEL=1 -DVERSION=${common.release_version} build_unflags = ${common.build_unflags} @@ -273,6 +274,7 @@ board = esp-wrover-kit framework = ${common.framework} build_flags = ${common.build_flags} + -DDEBUG_MODE=0 ; Set the debug mode -DCORE_DEBUG_LEVEL=1 -DDEBUG_ESP_OTA -DVERSION=${common.release_version} From 4812ba5f3510fa981e3259ff2f4937bf050adae2 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 5 Sep 2022 13:11:59 +0100 Subject: [PATCH 086/153] Large Update - Clean up main - Change handling of APIServer start & StreamServer start to the WiFiHandler - Call the setupWifi in the WiFiHandler begin method - Remove WiFiHandler from APIServer and pass in ProjectConfig directly --- .../src/network/WifiHandler/WifiHandler.hpp | 10 +++- .../src/network/WifiHandler/wifiHandler.cpp | 47 ++++++++++++++++ ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 32 +++++------ ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 4 +- .../network/api/utilities/apiUtilities.cpp | 2 - .../network/api/utilities/apiUtilities.hpp | 2 - ESP/lib/src/network/api/webserverHandler.cpp | 4 +- ESP/lib/src/network/api/webserverHandler.hpp | 2 +- ESP/src/main.cpp | 54 +++---------------- 9 files changed, 84 insertions(+), 73 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 3a503c2..7cbfd0d 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -6,19 +6,27 @@ #include #include "data/StateManager/StateManager.hpp" #include "data/config/project_config.hpp" +#include "network/api/webserverHandler.hpp" +#include "network/stream/streamServer.hpp" #include "data/utilities/helpers.hpp" class WiFiHandler { public: - WiFiHandler(ProjectConfig *configManager, StateManager *stateManager, + WiFiHandler(ProjectConfig *configManager, + APIServer *apiServer, + StreamServer *streamServer, + StateManager *stateManager, const std::string &ssid, const std::string &password, uint8_t channel); virtual ~WiFiHandler(); + void begin(); void setupWifi(); ProjectConfig *configManager; + APIServer *apiServer; + StreamServer *streamServer; StateManager *stateManager; bool _enable_adhoc; diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index f44f003..8680a25 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -2,10 +2,14 @@ #include WiFiHandler::WiFiHandler(ProjectConfig *configManager, + APIServer *apiServer, + StreamServer *streamServer, StateManager *stateManager, const std::string &ssid, const std::string &password, uint8_t channel) : configManager(configManager), + apiServer(apiServer), + streamServer(streamServer), stateManager(stateManager), ssid(ssid), password(password), @@ -14,6 +18,49 @@ WiFiHandler::WiFiHandler(ProjectConfig *configManager, WiFiHandler::~WiFiHandler() {} +void WiFiHandler::begin() +{ + this->setupWifi(); + + switch (this->stateManager->getCurrentState()) + { + case WiFiState_e::WiFiState_Disconnected: + { + //! TODO: Implement + break; + } + case WiFiState_e::WiFiState_Disconnecting: + { + //! TODO: Implement + break; + } + case WiFiState_e::WiFiState_ADHOC: + { + streamServer->startStreamServer(); + apiServer->begin(); + log_d("[SETUP]: Starting Stream Server"); + break; + } + case WiFiState_e::WiFiState_Connected: + { + streamServer->startStreamServer(); + apiServer->begin(); + log_d("[SETUP]: Starting Stream Server"); + break; + } + case WiFiState_e::WiFiState_Connecting: + { + //! TODO: Implement + break; + } + case WiFiState_e::WiFiState_Error: + { + //! TODO: Implement + break; + } + } +} + void WiFiHandler::setupWifi() { if (this->_enable_adhoc || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 9d05d6f..b10d80c 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -1,11 +1,11 @@ #include "baseAPI.hpp" BaseAPI::BaseAPI(int CONTROL_PORT, - WiFiHandler *network, + ProjectConfig *configManager, CameraHandler *camera, StateManager *stateManager, - const std::string &api_url) : API_Utilities(CONTROL_PORT, - network, + const std::string &api_url) : configManager(configManager), + API_Utilities(CONTROL_PORT, camera, stateManager, api_url) {} @@ -74,11 +74,11 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } - network->configManager->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); + configManager->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); - /* if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + /* if (stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { - network->configManager->setAPWifiConfig(ssid, password, &channel, adhoc, true); + configManager->setAPWifiConfig(ssid, password, &channel, adhoc, true); } else { @@ -86,7 +86,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) } */ request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); - network->configManager->wifiConfigSave(); + configManager->wifiConfigSave(); break; } default: @@ -132,27 +132,27 @@ void BaseAPI::handleJson(AsyncWebServerRequest *request) { case DATA: { - network->configManager->getDeviceConfig()->data_json = true; + configManager->getDeviceConfig()->data_json = true; Network_Utilities::my_delay(1L); - std::string temp = network->configManager->getDeviceConfig()->data_json_string; + std::string temp = configManager->getDeviceConfig()->data_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); break; } case SETTINGS: { - network->configManager->getDeviceConfig()->config_json = true; + configManager->getDeviceConfig()->config_json = true; Network_Utilities::my_delay(1L); - std::string temp = network->configManager->getDeviceConfig()->config_json_string; + std::string temp = configManager->getDeviceConfig()->config_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); break; } case CONFIG: { - network->configManager->getDeviceConfig()->settings_json = true; + configManager->getDeviceConfig()->settings_json = true; Network_Utilities::my_delay(1L); - std::string temp = network->configManager->getDeviceConfig()->settings_json_string; + std::string temp = configManager->getDeviceConfig()->settings_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); break; @@ -196,7 +196,7 @@ void BaseAPI::factoryReset(AsyncWebServerRequest *request) case GET: { log_d("Factory Reset"); - network->configManager->reset(); + configManager->reset(); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Factory Reset\"}"); } default: @@ -294,8 +294,8 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) camera->setHFlip(temp_camera_hflip); //! TODO: Need to add -> camera->setQuality(temp_camera_quality); - network->configManager->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, true); - network->configManager->cameraConfigSave(); + configManager->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, true); + configManager->cameraConfigSave(); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera Settings have been set.\"}"); break; diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index ac8a765..2ca8a68 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -7,7 +7,7 @@ class BaseAPI : public API_Utilities { protected: - + ProjectConfig *configManager; enum JSON_TYPES { CONFIG, @@ -53,7 +53,7 @@ protected: public: BaseAPI(int CONTROL_PORT, - WiFiHandler *network, + ProjectConfig *configManager, CameraHandler *camera, StateManager *stateManager, const std::string &api_url); diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index e17fde7..d61c41f 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -15,12 +15,10 @@ const char *API_Utilities::MIMETYPE_JSON{"application/json"}; //********************************************************************************************* API_Utilities::API_Utilities(int CONTROL_PORT, - WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, const std::string &api_url) : server(new AsyncWebServer(CONTROL_PORT)), stateManager(stateManager), - network(network), camera(camera), api_url(api_url) {} diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index d5dab5a..6f7f02b 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -30,7 +30,6 @@ class API_Utilities { public: API_Utilities(int CONTROL_PORT, - WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, const std::string &api_url); @@ -69,7 +68,6 @@ protected: protected: AsyncWebServer *server; - WiFiHandler *network; CameraHandler *camera; StateManager *stateManager; typedef std::unordered_map networkMethodsMap_t; diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 6f0e77b..ea01237 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -5,11 +5,11 @@ //********************************************************************************************* APIServer::APIServer(int CONTROL_PORT, - WiFiHandler *network, + ProjectConfig *configManager, CameraHandler *camera, StateManager *stateManager, const std::string &api_url) : BaseAPI(CONTROL_PORT, - network, + configManager, camera, stateManager, api_url) {} diff --git a/ESP/lib/src/network/api/webserverHandler.hpp b/ESP/lib/src/network/api/webserverHandler.hpp index ddbdc43..3fbb257 100644 --- a/ESP/lib/src/network/api/webserverHandler.hpp +++ b/ESP/lib/src/network/api/webserverHandler.hpp @@ -8,7 +8,7 @@ class APIServer : public BaseAPI { public: APIServer(int CONTROL_PORT, - WiFiHandler *network, + ProjectConfig *configManager, CameraHandler *camera, StateManager *stateManager, const std::string &api_url); diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 1e4b23e..5b98f80 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -12,18 +12,17 @@ #include -int STREAM_SERVER_PORT = 80; -int CONTROL_SERVER_PORT = 81; - ProjectConfig deviceConfig; OTA ota(&deviceConfig); LEDManager ledManager(33); CameraHandler cameraHandler(&deviceConfig); // SerialManager serialManager(&deviceConfig); -WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); -APIServer apiServer(CONTROL_SERVER_PORT, &wifiHandler, &cameraHandler, &wifiStateManager, "/control"); + +APIServer apiServer(81, &deviceConfig, &cameraHandler, &wifiStateManager, "/control"); +StreamServer streamServer(80); + +WiFiHandler wifiHandler(&deviceConfig, &apiServer, &streamServer, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); MDNSHandler mdnsHandler(&mdnsStateManager, &deviceConfig); -StreamServer streamServer(STREAM_SERVER_PORT); void setup() { @@ -37,48 +36,9 @@ void setup() deviceConfig.load(); cameraHandler.setupCamera(); - wifiHandler._enable_adhoc = ENABLE_ADHOC; - - wifiHandler.setupWifi(); + wifiHandler._enable_adhoc = ENABLE_ADHOC; // force ADHOC mode at compile time. + wifiHandler.begin(); // start wifi, apiserver, and streamserver mdnsHandler.startMDNS(); - - switch (wifiStateManager.getCurrentState()) - { - case WiFiState_e::WiFiState_Disconnected: - { - //! TODO: Implement - break; - } - case WiFiState_e::WiFiState_Disconnecting: - { - //! TODO: Implement - break; - } - case WiFiState_e::WiFiState_ADHOC: - { - streamServer.startStreamServer(); - apiServer.begin(); - log_d("[SETUP]: Starting Stream Server"); - break; - } - case WiFiState_e::WiFiState_Connected: - { - streamServer.startStreamServer(); - apiServer.begin(); - log_d("[SETUP]: Starting Stream Server"); - break; - } - case WiFiState_e::WiFiState_Connecting: - { - //! TODO: Implement - break; - } - case WiFiState_e::WiFiState_Error: - { - //! TODO: Implement - break; - } - } ota.SetupOTA(); } From 27ece435cd9aa0ca28316222815855780c0943a5 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 5 Sep 2022 13:46:42 +0100 Subject: [PATCH 087/153] Revert "Large Update" This reverts commit 4812ba5f3510fa981e3259ff2f4937bf050adae2. --- .../src/network/WifiHandler/WifiHandler.hpp | 10 +--- .../src/network/WifiHandler/wifiHandler.cpp | 47 ---------------- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 32 +++++------ ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 4 +- .../network/api/utilities/apiUtilities.cpp | 2 + .../network/api/utilities/apiUtilities.hpp | 2 + ESP/lib/src/network/api/webserverHandler.cpp | 4 +- ESP/lib/src/network/api/webserverHandler.hpp | 2 +- ESP/src/main.cpp | 54 ++++++++++++++++--- 9 files changed, 73 insertions(+), 84 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 7cbfd0d..3a503c2 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -6,27 +6,19 @@ #include #include "data/StateManager/StateManager.hpp" #include "data/config/project_config.hpp" -#include "network/api/webserverHandler.hpp" -#include "network/stream/streamServer.hpp" #include "data/utilities/helpers.hpp" class WiFiHandler { public: - WiFiHandler(ProjectConfig *configManager, - APIServer *apiServer, - StreamServer *streamServer, - StateManager *stateManager, + WiFiHandler(ProjectConfig *configManager, StateManager *stateManager, const std::string &ssid, const std::string &password, uint8_t channel); virtual ~WiFiHandler(); - void begin(); void setupWifi(); ProjectConfig *configManager; - APIServer *apiServer; - StreamServer *streamServer; StateManager *stateManager; bool _enable_adhoc; diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 8680a25..f44f003 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -2,14 +2,10 @@ #include WiFiHandler::WiFiHandler(ProjectConfig *configManager, - APIServer *apiServer, - StreamServer *streamServer, StateManager *stateManager, const std::string &ssid, const std::string &password, uint8_t channel) : configManager(configManager), - apiServer(apiServer), - streamServer(streamServer), stateManager(stateManager), ssid(ssid), password(password), @@ -18,49 +14,6 @@ WiFiHandler::WiFiHandler(ProjectConfig *configManager, WiFiHandler::~WiFiHandler() {} -void WiFiHandler::begin() -{ - this->setupWifi(); - - switch (this->stateManager->getCurrentState()) - { - case WiFiState_e::WiFiState_Disconnected: - { - //! TODO: Implement - break; - } - case WiFiState_e::WiFiState_Disconnecting: - { - //! TODO: Implement - break; - } - case WiFiState_e::WiFiState_ADHOC: - { - streamServer->startStreamServer(); - apiServer->begin(); - log_d("[SETUP]: Starting Stream Server"); - break; - } - case WiFiState_e::WiFiState_Connected: - { - streamServer->startStreamServer(); - apiServer->begin(); - log_d("[SETUP]: Starting Stream Server"); - break; - } - case WiFiState_e::WiFiState_Connecting: - { - //! TODO: Implement - break; - } - case WiFiState_e::WiFiState_Error: - { - //! TODO: Implement - break; - } - } -} - void WiFiHandler::setupWifi() { if (this->_enable_adhoc || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index b10d80c..9d05d6f 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -1,11 +1,11 @@ #include "baseAPI.hpp" BaseAPI::BaseAPI(int CONTROL_PORT, - ProjectConfig *configManager, + WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, - const std::string &api_url) : configManager(configManager), - API_Utilities(CONTROL_PORT, + const std::string &api_url) : API_Utilities(CONTROL_PORT, + network, camera, stateManager, api_url) {} @@ -74,11 +74,11 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } - configManager->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); + network->configManager->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); - /* if (stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + /* if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { - configManager->setAPWifiConfig(ssid, password, &channel, adhoc, true); + network->configManager->setAPWifiConfig(ssid, password, &channel, adhoc, true); } else { @@ -86,7 +86,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) } */ request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); - configManager->wifiConfigSave(); + network->configManager->wifiConfigSave(); break; } default: @@ -132,27 +132,27 @@ void BaseAPI::handleJson(AsyncWebServerRequest *request) { case DATA: { - configManager->getDeviceConfig()->data_json = true; + network->configManager->getDeviceConfig()->data_json = true; Network_Utilities::my_delay(1L); - std::string temp = configManager->getDeviceConfig()->data_json_string; + std::string temp = network->configManager->getDeviceConfig()->data_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); break; } case SETTINGS: { - configManager->getDeviceConfig()->config_json = true; + network->configManager->getDeviceConfig()->config_json = true; Network_Utilities::my_delay(1L); - std::string temp = configManager->getDeviceConfig()->config_json_string; + std::string temp = network->configManager->getDeviceConfig()->config_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); break; } case CONFIG: { - configManager->getDeviceConfig()->settings_json = true; + network->configManager->getDeviceConfig()->settings_json = true; Network_Utilities::my_delay(1L); - std::string temp = configManager->getDeviceConfig()->settings_json_string; + std::string temp = network->configManager->getDeviceConfig()->settings_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); break; @@ -196,7 +196,7 @@ void BaseAPI::factoryReset(AsyncWebServerRequest *request) case GET: { log_d("Factory Reset"); - configManager->reset(); + network->configManager->reset(); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Factory Reset\"}"); } default: @@ -294,8 +294,8 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) camera->setHFlip(temp_camera_hflip); //! TODO: Need to add -> camera->setQuality(temp_camera_quality); - configManager->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, true); - configManager->cameraConfigSave(); + network->configManager->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, true); + network->configManager->cameraConfigSave(); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera Settings have been set.\"}"); break; diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index 2ca8a68..ac8a765 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -7,7 +7,7 @@ class BaseAPI : public API_Utilities { protected: - ProjectConfig *configManager; + enum JSON_TYPES { CONFIG, @@ -53,7 +53,7 @@ protected: public: BaseAPI(int CONTROL_PORT, - ProjectConfig *configManager, + WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, const std::string &api_url); diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index d61c41f..e17fde7 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -15,10 +15,12 @@ const char *API_Utilities::MIMETYPE_JSON{"application/json"}; //********************************************************************************************* API_Utilities::API_Utilities(int CONTROL_PORT, + WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, const std::string &api_url) : server(new AsyncWebServer(CONTROL_PORT)), stateManager(stateManager), + network(network), camera(camera), api_url(api_url) {} diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index 6f7f02b..d5dab5a 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -30,6 +30,7 @@ class API_Utilities { public: API_Utilities(int CONTROL_PORT, + WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, const std::string &api_url); @@ -68,6 +69,7 @@ protected: protected: AsyncWebServer *server; + WiFiHandler *network; CameraHandler *camera; StateManager *stateManager; typedef std::unordered_map networkMethodsMap_t; diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index ea01237..6f0e77b 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -5,11 +5,11 @@ //********************************************************************************************* APIServer::APIServer(int CONTROL_PORT, - ProjectConfig *configManager, + WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, const std::string &api_url) : BaseAPI(CONTROL_PORT, - configManager, + network, camera, stateManager, api_url) {} diff --git a/ESP/lib/src/network/api/webserverHandler.hpp b/ESP/lib/src/network/api/webserverHandler.hpp index 3fbb257..ddbdc43 100644 --- a/ESP/lib/src/network/api/webserverHandler.hpp +++ b/ESP/lib/src/network/api/webserverHandler.hpp @@ -8,7 +8,7 @@ class APIServer : public BaseAPI { public: APIServer(int CONTROL_PORT, - ProjectConfig *configManager, + WiFiHandler *network, CameraHandler *camera, StateManager *stateManager, const std::string &api_url); diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 5b98f80..1e4b23e 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -12,17 +12,18 @@ #include +int STREAM_SERVER_PORT = 80; +int CONTROL_SERVER_PORT = 81; + ProjectConfig deviceConfig; OTA ota(&deviceConfig); LEDManager ledManager(33); CameraHandler cameraHandler(&deviceConfig); // SerialManager serialManager(&deviceConfig); - -APIServer apiServer(81, &deviceConfig, &cameraHandler, &wifiStateManager, "/control"); -StreamServer streamServer(80); - -WiFiHandler wifiHandler(&deviceConfig, &apiServer, &streamServer, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); +WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); +APIServer apiServer(CONTROL_SERVER_PORT, &wifiHandler, &cameraHandler, &wifiStateManager, "/control"); MDNSHandler mdnsHandler(&mdnsStateManager, &deviceConfig); +StreamServer streamServer(STREAM_SERVER_PORT); void setup() { @@ -36,9 +37,48 @@ void setup() deviceConfig.load(); cameraHandler.setupCamera(); - wifiHandler._enable_adhoc = ENABLE_ADHOC; // force ADHOC mode at compile time. - wifiHandler.begin(); // start wifi, apiserver, and streamserver + wifiHandler._enable_adhoc = ENABLE_ADHOC; + + wifiHandler.setupWifi(); mdnsHandler.startMDNS(); + + switch (wifiStateManager.getCurrentState()) + { + case WiFiState_e::WiFiState_Disconnected: + { + //! TODO: Implement + break; + } + case WiFiState_e::WiFiState_Disconnecting: + { + //! TODO: Implement + break; + } + case WiFiState_e::WiFiState_ADHOC: + { + streamServer.startStreamServer(); + apiServer.begin(); + log_d("[SETUP]: Starting Stream Server"); + break; + } + case WiFiState_e::WiFiState_Connected: + { + streamServer.startStreamServer(); + apiServer.begin(); + log_d("[SETUP]: Starting Stream Server"); + break; + } + case WiFiState_e::WiFiState_Connecting: + { + //! TODO: Implement + break; + } + case WiFiState_e::WiFiState_Error: + { + //! TODO: Implement + break; + } + } ota.SetupOTA(); } From dd5c6454a63250eeecee8290cbd6fcc15afa27c1 Mon Sep 17 00:00:00 2001 From: Lorow Date: Mon, 5 Sep 2022 23:37:48 +0200 Subject: [PATCH 088/153] Update comments with explanation as to why we're setting false to loaded networks add printing of the stream address --- ESP/lib/src/data/config/project_config.cpp | 15 ++++++++------- ESP/lib/src/network/api/webserverHandler.cpp | 2 +- ESP/lib/src/network/stream/streamServer.cpp | 7 +++++-- ESP/lib/src/network/stream/streamServer.hpp | 1 + ESP/src/main.cpp | 6 ++++-- 5 files changed, 19 insertions(+), 12 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 11c261e..17f1b70 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -147,11 +147,11 @@ void ProjectConfig::load() //! push_back creates a copy of the object, so we need to use emplace_back this->config.networks.emplace_back( - temp_1, - temp_2, - temp_3, - temp_4, - false); // TODO figure out if this should be a hardcoded false + temp_1, + temp_2, + temp_3, + temp_4, + false); // false because the networks we store in the config are the ones we want the esp to connect to, rather than host as AP } /* AP Config */ @@ -196,6 +196,7 @@ void ProjectConfig::setWifiConfig(const std::string &networkName, const std::str { WiFiConfig_t *networkToUpdate = nullptr; + // we store the ADHOC flag as false because the networks we store in the config are the ones we want the esp to connect to, rather than host as AP, and here we're just updating them size_t size = this->config.networks.size(); if (size > 0) { @@ -212,7 +213,7 @@ void ProjectConfig::setWifiConfig(const std::string &networkName, const std::str ssid, password, *channel, - false); // TODO figure out if this should be a hardcoded false + false); } log_d("Updating wifi config"); } @@ -225,7 +226,7 @@ void ProjectConfig::setWifiConfig(const std::string &networkName, const std::str ssid, password, *channel, - false); // TODO figure out if this should be a hardcoded false + false); networkToUpdate = &this->config.networks[0]; } diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 6f0e77b..72f3c0a 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -18,7 +18,7 @@ APIServer::~APIServer() {} void APIServer::begin() { - log_d("Initializing REST API"); + log_d("Initializing REST API Server"); this->setupServer(); BaseAPI::begin(); diff --git a/ESP/lib/src/network/stream/streamServer.cpp b/ESP/lib/src/network/stream/streamServer.cpp index 96d08ef..bb98b48 100644 --- a/ESP/lib/src/network/stream/streamServer.cpp +++ b/ESP/lib/src/network/stream/streamServer.cpp @@ -83,7 +83,7 @@ esp_err_t StreamHelpers::stream(httpd_req_t *req) int StreamServer::startStreamServer() { - //WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //! Turn-off the 'brownout detector' + // WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //! Turn-off the 'brownout detector' httpd_config_t config = HTTPD_DEFAULT_CONFIG(); config.stack_size = 20480; config.max_uri_handlers = 1; @@ -104,7 +104,10 @@ int StreamServer::startStreamServer() else { httpd_register_uri_handler(camera_stream, &stream_page); - log_d("Stream server initialized"); + Serial.println("Stream server initialized"); + Serial.print("\n\rThe stream is under: http://"); + Serial.print(WiFi.localIP()); + Serial.printf(":%i\n\r", this->STREAM_SERVER_PORT); return 0; } } diff --git a/ESP/lib/src/network/stream/streamServer.hpp b/ESP/lib/src/network/stream/streamServer.hpp index 68a3727..b226590 100644 --- a/ESP/lib/src/network/stream/streamServer.hpp +++ b/ESP/lib/src/network/stream/streamServer.hpp @@ -3,6 +3,7 @@ #define STREAM_SERVER_HPP #define PART_BOUNDARY "123456789000000000000987654321" #include +#include // Used to disable brownout detection #include "soc/soc.h" #include "soc/rtc_cntl_reg.h" diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 1e4b23e..174ca8c 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -57,15 +57,17 @@ void setup() case WiFiState_e::WiFiState_ADHOC: { streamServer.startStreamServer(); - apiServer.begin(); log_d("[SETUP]: Starting Stream Server"); + apiServer.begin(); + log_d("[SETUP]: Starting API Server"); break; } case WiFiState_e::WiFiState_Connected: { streamServer.startStreamServer(); - apiServer.begin(); log_d("[SETUP]: Starting Stream Server"); + apiServer.begin(); + log_d("[SETUP]: Starting API Server"); break; } case WiFiState_e::WiFiState_Connecting: From c040f10b1b799e6e20f29e31d0e31f9daf8ce07e Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 5 Sep 2022 22:56:56 +0100 Subject: [PATCH 089/153] minor update - formatting --- ESP/lib/src/network/WifiHandler/WifiHandler.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 3a503c2..c9f38d2 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -11,7 +11,8 @@ class WiFiHandler { public: - WiFiHandler(ProjectConfig *configManager, StateManager *stateManager, + WiFiHandler(ProjectConfig *configManager, + StateManager *stateManager, const std::string &ssid, const std::string &password, uint8_t channel); From 4eac69a986be871bb5edd29fc2ce4096fe3cc6c9 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 5 Sep 2022 23:04:20 +0100 Subject: [PATCH 090/153] minor update - Fix long long issue with my_delay Timer was taking longer than anticipated. --- ESP/lib/src/data/utilities/network_utilities.cpp | 6 +++--- ESP/lib/src/io/camera/cameraHandler.cpp | 6 +++--- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/ESP/lib/src/data/utilities/network_utilities.cpp b/ESP/lib/src/data/utilities/network_utilities.cpp index 06d08fc..2a9804b 100644 --- a/ESP/lib/src/data/utilities/network_utilities.cpp +++ b/ESP/lib/src/data/utilities/network_utilities.cpp @@ -5,7 +5,7 @@ void Network_Utilities::SetupWifiScan() // Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); WiFi.disconnect(); // Disconnect from the access point if connected before - delay(100); + my_delay(0.1); Serial.println("Setup done"); } @@ -21,7 +21,7 @@ bool Network_Utilities::LoopWifiScan() // Print SSID and RSSI for each network found //! TODO: Add method here to interface with the API and forward the scanned networks to the API log_i("%d: %s (%d) %s\n", i - 1, WiFi.SSID(i), WiFi.RSSI(i), (WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*"); - my_delay(0.02L); // delay 20ms + my_delay(0.02); // delay 20ms } return (networks > 0); } @@ -33,7 +33,7 @@ int Network_Utilities::getStrength(int points) // TODO: add to JSON doc for (int i = 0; i < points; i++) { rssi += WiFi.RSSI(); - delay(20); + my_delay(0.02); } averageRSSI = rssi / points; return averageRSSI; diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index 654106f..aa6d90d 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -129,16 +129,16 @@ void CameraHandler::resetCamera(bool type) { // power cycle the camera module (handy if camera stops responding) digitalWrite(PWDN_GPIO_NUM, HIGH); // turn power off to camera module - Network_Utilities::my_delay(0.3L); // a for loop with a delay of 300ms + Network_Utilities::my_delay(0.3); // a for loop with a delay of 300ms digitalWrite(PWDN_GPIO_NUM, LOW); - Network_Utilities::my_delay(0.3L); + Network_Utilities::my_delay(0.3); setupCamera(); } else { // reset via software (handy if you wish to change resolution or image type etc. - see test procedure) esp_camera_deinit(); - Network_Utilities::my_delay(0.05L); + Network_Utilities::my_delay(0.05); setupCamera(); } } \ No newline at end of file diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 9d05d6f..255d29b 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -133,7 +133,7 @@ void BaseAPI::handleJson(AsyncWebServerRequest *request) case DATA: { network->configManager->getDeviceConfig()->data_json = true; - Network_Utilities::my_delay(1L); + Network_Utilities::my_delay(1); std::string temp = network->configManager->getDeviceConfig()->data_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); @@ -142,7 +142,7 @@ void BaseAPI::handleJson(AsyncWebServerRequest *request) case SETTINGS: { network->configManager->getDeviceConfig()->config_json = true; - Network_Utilities::my_delay(1L); + Network_Utilities::my_delay(1); std::string temp = network->configManager->getDeviceConfig()->config_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); @@ -151,7 +151,7 @@ void BaseAPI::handleJson(AsyncWebServerRequest *request) case CONFIG: { network->configManager->getDeviceConfig()->settings_json = true; - Network_Utilities::my_delay(1L); + Network_Utilities::my_delay(1); std::string temp = network->configManager->getDeviceConfig()->settings_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); From 6a33cb450d8be5f32874c0b363dbc7c3e679c353 Mon Sep 17 00:00:00 2001 From: Lorow Date: Thu, 8 Sep 2022 00:35:52 +0200 Subject: [PATCH 091/153] Simplify baseAPI - replace calls to projectManager through hardware managers with a pointer to said manager Fix a bug - saving camera settings was triggering networksConfigUpdated event Hookup camera update TODO: - simplify APi utilities - consider replacing inheritance with composition - Add brightness control setting to API --- ESP/lib/src/data/config/project_config.cpp | 2 +- ESP/lib/src/data/config/project_config.hpp | 16 +++---- ESP/lib/src/io/camera/cameraHandler.hpp | 2 +- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 48 ++++++++----------- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 8 ++-- .../network/api/utilities/apiUtilities.cpp | 16 +++---- .../network/api/utilities/apiUtilities.hpp | 13 ++--- ESP/lib/src/network/api/webserverHandler.cpp | 16 +++---- ESP/lib/src/network/api/webserverHandler.hpp | 8 ++-- ESP/src/main.cpp | 6 ++- 10 files changed, 67 insertions(+), 68 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 17f1b70..55e5ebd 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -189,7 +189,7 @@ void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t log_d("Updating Camera config"); if (shouldNotify) - this->notify(ObserverEvent::networksConfigUpdated); + this->notify(ObserverEvent::cameraConfigUpdated); } void ProjectConfig::setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify) diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 10cdcba..e783a41 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -47,14 +47,14 @@ public: { //! Constructor for WiFiConfig_t - allows us to use emplace_back WiFiConfig_t(const std::string &name, - const std::string &ssid, - const std::string &password, - uint8_t channel, - bool adhoc) : name(std::move(name)), - ssid(std::move(ssid)), - password(std::move(password)), - channel(channel), - adhoc(adhoc) {} + const std::string &ssid, + const std::string &password, + uint8_t channel, + bool adhoc) : name(std::move(name)), + ssid(std::move(ssid)), + password(std::move(password)), + channel(channel), + adhoc(adhoc) {} std::string name; std::string ssid; std::string password; diff --git a/ESP/lib/src/io/camera/cameraHandler.hpp b/ESP/lib/src/io/camera/cameraHandler.hpp index 458cf02..3f4de3f 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -5,7 +5,7 @@ #include "data/utilities/network_utilities.hpp" #include "data/config/project_config.hpp" -class CameraHandler : IObserver +class CameraHandler : public IObserver { private: sensor_t *camera_sensor; diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 255d29b..ec431ae 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -1,14 +1,14 @@ #include "baseAPI.hpp" BaseAPI::BaseAPI(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - const std::string &api_url) : API_Utilities(CONTROL_PORT, - network, - camera, - stateManager, - api_url) {} + ProjectConfig *projectConfig, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url) : API_Utilities(CONTROL_PORT, + projectConfig, + camera, + WiFiStateManager, + api_url) {} BaseAPI::~BaseAPI() {} @@ -74,11 +74,11 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } - network->configManager->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); + projectConfig->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); - /* if (network->stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + /* if (WiFitateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { - network->configManager->setAPWifiConfig(ssid, password, &channel, adhoc, true); + projectConfig->setAPWifiConfig(ssid, password, &channel, adhoc, true); } else { @@ -86,7 +86,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) } */ request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); - network->configManager->wifiConfigSave(); + projectConfig->wifiConfigSave(); break; } default: @@ -132,27 +132,27 @@ void BaseAPI::handleJson(AsyncWebServerRequest *request) { case DATA: { - network->configManager->getDeviceConfig()->data_json = true; + projectConfig->getDeviceConfig()->data_json = true; Network_Utilities::my_delay(1); - std::string temp = network->configManager->getDeviceConfig()->data_json_string; + std::string temp = projectConfig->getDeviceConfig()->data_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); break; } case SETTINGS: { - network->configManager->getDeviceConfig()->config_json = true; + projectConfig->getDeviceConfig()->config_json = true; Network_Utilities::my_delay(1); - std::string temp = network->configManager->getDeviceConfig()->config_json_string; + std::string temp = projectConfig->getDeviceConfig()->config_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); break; } case CONFIG: { - network->configManager->getDeviceConfig()->settings_json = true; + projectConfig->getDeviceConfig()->settings_json = true; Network_Utilities::my_delay(1); - std::string temp = network->configManager->getDeviceConfig()->settings_json_string; + std::string temp = projectConfig->getDeviceConfig()->settings_json_string; request->send(200, MIMETYPE_JSON, temp.c_str()); temp = std::string(); break; @@ -196,7 +196,7 @@ void BaseAPI::factoryReset(AsyncWebServerRequest *request) case GET: { log_d("Factory Reset"); - network->configManager->reset(); + projectConfig->reset(); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Factory Reset\"}"); } default: @@ -288,14 +288,8 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) } } - // set the values for this instance - camera->setCameraResolution((framesize_t)temp_camera_framesize); - camera->setVFlip(temp_camera_vflip); - camera->setHFlip(temp_camera_hflip); - //! TODO: Need to add -> camera->setQuality(temp_camera_quality); - - network->configManager->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, true); - network->configManager->cameraConfigSave(); + projectConfig->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, true); + projectConfig->cameraConfigSave(); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera Settings have been set.\"}"); break; diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index ac8a765..21c3824 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -53,10 +53,10 @@ protected: public: BaseAPI(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - const std::string &api_url); + ProjectConfig *projectConfig, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url); virtual ~BaseAPI(); virtual void begin(); diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index e17fde7..43be408 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -15,14 +15,14 @@ const char *API_Utilities::MIMETYPE_JSON{"application/json"}; //********************************************************************************************* API_Utilities::API_Utilities(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - const std::string &api_url) : server(new AsyncWebServer(CONTROL_PORT)), - stateManager(stateManager), - network(network), - camera(camera), - api_url(api_url) {} + ProjectConfig *projectConfig, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url) : server(new AsyncWebServer(CONTROL_PORT)), + projectConfig(projectConfig), + WiFiStateManager(WiFiStateManager), + camera(camera), + api_url(api_url) {} API_Utilities::~API_Utilities() {} diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index d5dab5a..13cfc29 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -22,6 +22,7 @@ #include //#include #include "mbedtls/md.h" +#include "data/config/project_config.hpp" #include "network/wifihandler/WifiHandler.hpp" #include "data/StateManager/StateManager.hpp" #include "io/camera/cameraHandler.hpp" @@ -30,10 +31,10 @@ class API_Utilities { public: API_Utilities(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - const std::string &api_url); + ProjectConfig *projectConfig, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url); virtual ~API_Utilities(); protected: @@ -68,10 +69,10 @@ protected: }; protected: + ProjectConfig *projectConfig; AsyncWebServer *server; - WiFiHandler *network; CameraHandler *camera; - StateManager *stateManager; + StateManager *WiFiStateManager; typedef std::unordered_map networkMethodsMap_t; protected: diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 72f3c0a..f878e7d 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -5,14 +5,14 @@ //********************************************************************************************* APIServer::APIServer(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - const std::string &api_url) : BaseAPI(CONTROL_PORT, - network, - camera, - stateManager, - api_url) {} + ProjectConfig *projectConfig, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url) : BaseAPI(CONTROL_PORT, + projectConfig, + camera, + WiFiStateManager, + api_url){} APIServer::~APIServer() {} diff --git a/ESP/lib/src/network/api/webserverHandler.hpp b/ESP/lib/src/network/api/webserverHandler.hpp index ddbdc43..adb0b03 100644 --- a/ESP/lib/src/network/api/webserverHandler.hpp +++ b/ESP/lib/src/network/api/webserverHandler.hpp @@ -8,10 +8,10 @@ class APIServer : public BaseAPI { public: APIServer(int CONTROL_PORT, - WiFiHandler *network, - CameraHandler *camera, - StateManager *stateManager, - const std::string &api_url); + ProjectConfig *projectConfig, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url); virtual ~APIServer(); void begin(); diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 174ca8c..4b318e1 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -21,7 +21,7 @@ LEDManager ledManager(33); CameraHandler cameraHandler(&deviceConfig); // SerialManager serialManager(&deviceConfig); WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); -APIServer apiServer(CONTROL_SERVER_PORT, &wifiHandler, &cameraHandler, &wifiStateManager, "/control"); +APIServer apiServer(CONTROL_SERVER_PORT, &deviceConfig, &cameraHandler, &wifiStateManager, "/control"); MDNSHandler mdnsHandler(&mdnsStateManager, &deviceConfig); StreamServer streamServer(STREAM_SERVER_PORT); @@ -33,6 +33,10 @@ void setup() Logo::printASCII(); ledManager.begin(); + + deviceConfig.attach(&cameraHandler); + deviceConfig.attach(&mdnsHandler); + deviceConfig.initConfig(); deviceConfig.load(); cameraHandler.setupCamera(); From 9a8ff6659a14741c419f235c7379faefcbcbe905 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 8 Sep 2022 13:54:08 +0100 Subject: [PATCH 092/153] update - Remove CMake files --- ESP/CMakeLists.txt | 33 -------- ESP/CMakeListsPrivate.txt | 155 -------------------------------------- 2 files changed, 188 deletions(-) delete mode 100644 ESP/CMakeLists.txt delete mode 100644 ESP/CMakeListsPrivate.txt diff --git a/ESP/CMakeLists.txt b/ESP/CMakeLists.txt deleted file mode 100644 index 84a020a..0000000 --- a/ESP/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -# !!! WARNING !!! AUTO-GENERATED FILE, PLEASE DO NOT MODIFY IT AND USE -# https://docs.platformio.org/page/projectconf/section_env_build.html#build-flags -# -# If you need to override existing CMake configuration or add extra, -# please create `CMakeListsUser.txt` in the root of project. -# The `CMakeListsUser.txt` will not be overwritten by PlatformIO. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_SYSTEM_NAME Generic) -set(CMAKE_C_COMPILER_WORKS 1) -set(CMAKE_CXX_COMPILER_WORKS 1) - -project("ESP" C CXX) - -include(CMakeListsPrivate.txt) - -if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/CMakeListsUser.txt) -include(CMakeListsUser.txt) -endif() - -add_custom_target( - Production ALL - COMMAND platformio -c clion run "$<$>:-e${CMAKE_BUILD_TYPE}>" - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} -) - -add_custom_target( - Debug ALL - COMMAND platformio -c clion debug "$<$>:-e${CMAKE_BUILD_TYPE}>" - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} -) - -add_executable(Z_DUMMY_TARGET ${SRC_LIST}) diff --git a/ESP/CMakeListsPrivate.txt b/ESP/CMakeListsPrivate.txt deleted file mode 100644 index f59fa0e..0000000 --- a/ESP/CMakeListsPrivate.txt +++ /dev/null @@ -1,155 +0,0 @@ -# !!! WARNING !!! AUTO-GENERATED FILE, PLEASE DO NOT MODIFY IT AND USE -# https://docs.platformio.org/page/projectconf/section_env_build.html#build-flags -# -# If you need to override existing CMake configuration or add extra, -# please create `CMakeListsUser.txt` in the root of project. -# The `CMakeListsUser.txt` will not be overwritten by PlatformIO. - - - -set(CMAKE_CONFIGURATION_TYPES "esp32cam" CACHE STRING "Build Types reflect PlatformIO Environments" FORCE) - -# Convert "Home Directory" that may contain unescaped backslashes on Windows -file(TO_CMAKE_PATH $ENV{HOMEDRIVE}$ENV{HOMEPATH} ENV_HOME_PATH) - - -SET(CMAKE_C_COMPILER "${ENV_HOME_PATH}/.platformio/packages/toolchain-xtensa32/bin/xtensa-esp32-elf-gcc.exe") -SET(CMAKE_CXX_COMPILER "${ENV_HOME_PATH}/.platformio/packages/toolchain-xtensa32/bin/xtensa-esp32-elf-g++.exe") -SET(CMAKE_CXX_FLAGS "-fno-rtti -fno-exceptions -std=gnu++11 -mfix-esp32-psram-cache-issue -mfix-esp32-psram-cache-issue -g3 -Wall -nostdlib -Wpointer-arith -Wno-error=unused-but-set-variable -Wno-error=unused-variable -mlongcalls -ffunction-sections -fdata-sections -fstrict-volatile-bitfields -Wno-error=deprecated-declarations -Wno-error=unused-function -Wno-unused-parameter -Wno-sign-compare -fstack-protector -fexceptions -Werror=reorder") -SET(CMAKE_C_FLAGS "-std=gnu99 -Wno-old-style-declaration -mfix-esp32-psram-cache-issue -mfix-esp32-psram-cache-issue -g3 -Wall -nostdlib -Wpointer-arith -Wno-error=unused-but-set-variable -Wno-error=unused-variable -mlongcalls -ffunction-sections -fdata-sections -fstrict-volatile-bitfields -Wno-error=deprecated-declarations -Wno-error=unused-function -Wno-unused-parameter -Wno-sign-compare -fstack-protector -fexceptions -Werror=reorder") - -SET(CMAKE_C_STANDARD 99) -set(CMAKE_CXX_STANDARD 11) - -if (CMAKE_BUILD_TYPE MATCHES "esp32cam") - add_definitions(-DPLATFORMIO=50205) - add_definitions(-DARDUINO_ESP32_DEV) - add_definitions(-DBOARD_HAS_PSRAM) - add_definitions(-DDEBUG_ESP_PORT=Serial) - add_definitions(-DDEBUG_ESP_OTA) - add_definitions(-DBOARD_HAS_PSRAM) - add_definitions(-DESP32) - add_definitions(-DESP_PLATFORM) - add_definitions(-DF_CPU=240000000L) - add_definitions(-DHAVE_CONFIG_H) - add_definitions(-DMBEDTLS_CONFIG_FILE=\"mbedtls/esp_config.h\") - add_definitions(-DARDUINO=10805) - add_definitions(-DARDUINO_ARCH_ESP32) - add_definitions(-DARDUINO_VARIANT=\"esp32\") - add_definitions(-DARDUINO_BOARD=\"AI\ Thinker\ ESP32-CAM\") - - include_directories("${CMAKE_CURRENT_LIST_DIR}/include") - include_directories("${CMAKE_CURRENT_LIST_DIR}/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/ArduinoOTA/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/Update/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/ESPmDNS/src") - include_directories("${CMAKE_CURRENT_LIST_DIR}/.pio/libdeps/esp32cam/ESP Async WebServer/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/WiFi/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/FS/src") - include_directories("${CMAKE_CURRENT_LIST_DIR}/.pio/libdeps/esp32cam/AsyncTCP/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/config") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/app_trace") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/app_update") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/asio") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/bootloader_support") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/bt") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/coap") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/console") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/driver") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/efuse") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp-tls") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp32") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp_adc_cal") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp_event") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp_http_client") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp_http_server") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp_https_ota") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp_https_server") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp_ringbuf") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp_websocket_client") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/espcoredump") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/ethernet") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/expat") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/fatfs") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/freemodbus") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/freertos") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/heap") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/idf_test") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/jsmn") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/json") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/libsodium") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/log") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/lwip") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/mbedtls") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/mdns") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/micro-ecc") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/mqtt") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/newlib") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/nghttp") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/nvs_flash") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/openssl") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/protobuf-c") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/protocomm") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/pthread") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/sdmmc") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/smartconfig_ack") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/soc") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/spi_flash") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/spiffs") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/tcp_transport") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/tcpip_adapter") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/ulp") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/unity") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/vfs") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/wear_levelling") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/wifi_provisioning") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/wpa_supplicant") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/xtensa-debug-module") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp-face") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/esp32-camera") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/tools/sdk/include/fb_gfx") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/cores/esp32") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/variants/esp32") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/AsyncUDP/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/AzureIoT/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/BLE/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/BluetoothSerial/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/DNSServer/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/EEPROM/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/ESP32/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/FFat/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/HTTPClient/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/HTTPUpdate/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/HTTPUpdateServer/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/NetBIOS/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/Preferences/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/SD/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/SD_MMC/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/SPI/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/SPIFFS/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/SimpleBLE/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/Ticker/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/WebServer/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/WiFiClientSecure/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/WiFiProv/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/framework-arduinoespressif32/libraries/Wire/src") - include_directories("${ENV_HOME_PATH}/.platformio/packages/toolchain-xtensa32/xtensa-esp32-elf/include/c++/5.2.0") - include_directories("${ENV_HOME_PATH}/.platformio/packages/toolchain-xtensa32/xtensa-esp32-elf/include/c++/5.2.0/xtensa-esp32-elf") - include_directories("${ENV_HOME_PATH}/.platformio/packages/toolchain-xtensa32/lib/gcc/xtensa-esp32-elf/5.2.0/include") - include_directories("${ENV_HOME_PATH}/.platformio/packages/toolchain-xtensa32/lib/gcc/xtensa-esp32-elf/5.2.0/include-fixed") - include_directories("${ENV_HOME_PATH}/.platformio/packages/toolchain-xtensa32/xtensa-esp32-elf/include") - include_directories("${ENV_HOME_PATH}/.platformio/packages/tool-unity") - - FILE(GLOB_RECURSE EXTRA_LIB_SOURCES - ${CMAKE_CURRENT_LIST_DIR}/.pio/libdeps/esp32cam/*.* - ) -endif() - - -FILE(GLOB_RECURSE SRC_LIST - ${CMAKE_CURRENT_LIST_DIR}/src/*.* - ${CMAKE_CURRENT_LIST_DIR}/lib/*.* - ${CMAKE_CURRENT_LIST_DIR}/test/*.* -) - -list(APPEND SRC_LIST ${EXTRA_LIB_SOURCES}) From 35f61436ab0ad68b16da6217c22ffd9f6c627b21 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 8 Sep 2022 16:01:52 +0100 Subject: [PATCH 093/153] Major Update - Remove unneeded `data` folder at root of project - Deprecate API_Utilities class (kept only for the shaEncoder function) - Begin migration to better organization --- ESP/data/ascii.txt | 60 -------------- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 45 ++++++++--- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 75 ++++++++++++++++- .../network/api/utilities/apiUtilities.cpp | 35 +------- .../network/api/utilities/apiUtilities.hpp | 80 ++----------------- ESP/lib/src/network/api/webserverHandler.cpp | 4 +- 6 files changed, 115 insertions(+), 184 deletions(-) delete mode 100644 ESP/data/ascii.txt diff --git a/ESP/data/ascii.txt b/ESP/data/ascii.txt deleted file mode 100644 index c515e2a..0000000 --- a/ESP/data/ascii.txt +++ /dev/null @@ -1,60 +0,0 @@ - : === WELCOME === TO === : - =========================================================================================================================== - ██████╗ ██████╗ ███████╗███╗ ██╗██╗██████╗ ██╗███████╗ - ██╔═══██╗██╔══██╗██╔════╝████╗ ██║██║██╔══██╗██║██╔════╝ - ██║ ██║██████╔╝█████╗ ██╔██╗ ██║██║██████╔╝██║███████╗ - ██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║██║██╔══██╗██║╚════██║ - ╚██████╔╝██║ ███████╗██║ ╚████║██║██║ ██║██║███████║ - ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝╚═╝╚═╝ ╚═╝╚═╝╚══════╝ - - ██████████████ - ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░▒▒▓▓▓▓██ - ████▓▓░░░░▒▒░░░░░░▒▒░░░░░░▒▒░░████ - ██▓▓▒▒▓▓▓▓▒▒▒▒░░░░░░▒▒░░▒▒░░░░░░▒▒░░▒▒▓▓▓▓ - ██▓▓▒▒▒▒▒▒▒▒░░▒▒░░░░░░░░░░░░▒▒░░░░▒▒░░░░▒▒░░██ - ██▓▓▓▓░░░░▒▒░░░░▒▒▒▒░░░░░░░░░░▒▒░░ ░░░░░░░░▒▒░░██ - ██▓▓▓▓▓▓▓▓▓▓░░░░░░▒▒░░░░░░░░░░░░░░ ░░░░░░░░░░░░██ - ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░░░ ░░ ▒▒▒▒██ - ██▓▓▒▒▒▒▒▒▒▒░░░░▒▒░░░░░░░░░░░░░░░░░░ ░░░░██ - ▓▓▓▓▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░░░░░░░░░▓▓▓▓▓▓▓▓▓▓ ░░ ▒▒▓▓ - ██▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓▓▓ ░░██ - ▓▓▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░ ▓▓▒▒▒▒▒▒▒▒░░░░▒▒▒▒▓▓▒▒ ░░▒▒▓▓ - ██▓▓▒▒░░░░░░▒▒▒▒▒▒░░░░░░░░░░░░░░░░▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░▒▒▓▓▓▓ ░░██ - ██▓▓▓▓▒▒▒▒▒▒▒▒░░░░▒▒░░░░░░░░░░░░ ▒▒▒▒▒▒▒▒▒▒▒▒████▓▓░░░░▒▒▓▓ ░░██ - ██▓▓▒▒▒▒▒▒▓▓▒▒▓▓░░░░░░░░░░░░░░░░░░▓▓▒▒▒▒░░▒▒▒▒████ ▒▒██░░▒▒▓▓▓▓ ░░██ - ██▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▓▓░░▒▒▒▒▒▒██████▒▒ ▓▓▓▓░░▓▓▓▓ ░░██ - ██▓▓▒▒▒▒░░▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▓▓▒▒░░▒▒░░████████▓▓ ██▓▓▒▒▓▓ ░░██ - ██▓▓▓▓▓▓▓▓▒▒▒▒▒▒░░░░░░▒▒░░░░░░░░░░▒▒░░▒▒░░▒▒██████████▒▒██▒▒▒▒▓▓ ░░██ - ██▓▓▒▒▒▒▒▒░░░░░░░░▒▒▒▒░░░░░░░░░░░░▒▒▒▒░░░░▒▒██▒▒██████ ██▒▒▒▒▓▓ ░░██ - ██▒▒▒▒▒▒░░▓▓▓▓▓▓▒▒░░░░░░░░░░░░░░░░▒▒░░ ▒▒░░██ ▒▒████▒▒██▒▒▒▒▓▓ ░░██ - ██▓▓▓▓▓▓▓▓░░▒▒▒▒░░▒▒░░░░░░░░░░░░░░▒▒▒▒░░░░░░▒▒██ ██████▒▒▒▒▒▒▓▓░░░░██ - ██▓▓██▓▓▒▒▒▒▓▓░░░░▒▒░░░░░░░░░░░░░░░░░░▒▒▒▒░░▒▒░░▒▒██████▒▒▒▒▒▒▓▓ ░░██ - ██▓▓██▒▒▒▒▒▒▒▒▓▓▓▓▒▒░░░░░░░░░░░░░░░░░░▒▒░░▒▒░░▒▒░░▒▒░░▒▒▒▒▒▒▒▒▓▓░░░░██ - ██▒▒▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░▒▒░░▒▒░░░░░░▒▒▒▒▒▒▒▒▓▓ ░░░░██ - ██▒▒▒▒▓▓██▓▓▓▓▒▒▒▒▒▒▒▒░░░░░░░░▒▒░░░░░░░░░░░░▒▒▒▒▒▒░░▒▒▒▒▒▒▓▓▓▓ ░░░░██ - ▓▓▓▓▒▒▒▒▓▓██▓▓▒▒▒▒▒▒░░░░▒▒▒▒░░▒▒░░░░░░░░░░░░░░░░░░▒▒▒▒▓▓▓▓▓▓░░░░░░░░▒▒██ - ██▒▒▒▒▓▓▒▒▓▓██▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░░░██ - ██▒▒▒▒▓▓░░▒▒▒▒██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▒▒░░▒▒██ - ██▒▒▒▒▓▓▒▒░░▓▓▒▒██▓▓▒▒▒▒▒▒▒▒░░▓▓▒▒▓▓▒▒░░░░▒▒░░░░░░░░░░░░░░░░░░░░░░▓▓██ - ██▒▒▒▒▒▒░░▒▒▒▒▒▒▓▓██▓▓▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▓▓░░░░░░░░░░▒▒░░░░▒▒░░▒▒▒▒██ - ██▒▒▒▒░░▒▒░░▒▒████ ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░▓▓▒▒▒▒▒▒▓▓▒▒██ - ██▒▒▓▓░░▒▒░░▓▓ ████▓▓▒▒▓▓▒▒▒▒▒▒░░▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒██▓▓ - ██▒▒▒▒▒▒▒▒ ██ ████▓▓▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒████ - ██▒▒▒▒▒▒▒▒░░██ ██████▓▓▒▒▒▒▒▒▒▒▓▓▓▓██████ - ██▒▒▒▒▒▒▒▒░░ ████ ██████████████ - ██▒▒▒▒▒▒▒▒░░ ░░████ - ████▒▒▒▒▒▒░░░░ ░░████ - ████▒▒▒▒▒▒░░░░ ░░██ - ████▒▒▒▒▒▒░░ ░░██ - ██▓▓▒▒▒▒░░ ▒▒▓▓ - ████▒▒░░ ▒▒██ - ▓▓▒▒░░░░██ - ██░░ ██ - ▓▓██ ██░░░░██ - ██░░██ ██░░░░██ - ██░░██ ██░░▒▒██ - ██░░▒▒████░░▒▒██ - ▓▓▒▒▒▒▒▒▒▒▓▓ - ████████ - - ============================================================================================================================ \ No newline at end of file diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index ec431ae..e3d03e1 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -1,14 +1,24 @@ #include "baseAPI.hpp" +//! These have to be called before the constructor of the class because they are static +//! C++ 11 does not have inline variables, sadly. So we have to do this. +//const char *BaseAPI::MIMETYPE_HTML{"text/html"}; +// const char *BaseAPI::MIMETYPE_CSS{"text/css"}; +// const char *BaseAPI::MIMETYPE_JS{"application/javascript"}; +// const char *BaseAPI::MIMETYPE_PNG{"image/png"}; +// const char *BaseAPI::MIMETYPE_JPG{"image/jpeg"}; +// const char *BaseAPI::MIMETYPE_ICO{"image/x-icon"}; +const char *BaseAPI::MIMETYPE_JSON{"application/json"}; + BaseAPI::BaseAPI(int CONTROL_PORT, - ProjectConfig *projectConfig, - CameraHandler *camera, - StateManager *WiFiStateManager, - const std::string &api_url) : API_Utilities(CONTROL_PORT, - projectConfig, - camera, - WiFiStateManager, - api_url) {} + ProjectConfig *projectConfig, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url) : server(new AsyncWebServer(CONTROL_PORT)), + projectConfig(projectConfig), + camera(camera), + WiFiStateManager(WiFiStateManager), + api_url(api_url) {} BaseAPI::~BaseAPI() {} @@ -29,11 +39,26 @@ void BaseAPI::begin() DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); - // std::bind(&BaseAPI::API_Utilities::notFound, &api_utilities, std::placeholders::_1); + // std::bind(&BaseAPI::notFound, &std::placeholders::_1); server->onNotFound([&](AsyncWebServerRequest *request) { notFound(request); }); } +void BaseAPI::notFound(AsyncWebServerRequest *request) const +{ + if (_networkMethodsMap.find(request->method()) != _networkMethodsMap.end()) + { + log_i("%s: http://%s%s/\n", _networkMethodsMap.at(request->method()).c_str(), request->host().c_str(), request->url().c_str()); + char buffer[100]; + snprintf(buffer, sizeof(buffer), "Request %s Not found: %s", _networkMethodsMap.at(request->method()).c_str(), request->url().c_str()); + request->send(404, "text/plain", buffer); + } + else + { + request->send(404, "text/plain", "Request Not found using unknown method"); + } +} + //********************************************************************************************* //! Command Functions //********************************************************************************************* @@ -76,7 +101,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) projectConfig->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); - /* if (WiFitateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + /* if (WiFiStateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { projectConfig->setAPWifiConfig(ssid, password, &channel, adhoc, true); } diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index 21c3824..706f833 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -1,12 +1,37 @@ #ifndef BASEAPI_HPP #define BASEAPI_HPP -#include "network/wifihandler/wifiHandler.hpp" -#include "network/api/utilities/apiUtilities.hpp" + +#include +#include + +#define WEBSERVER_H + +/* #define XHTTP_GET 0b00000001; +#define XHTTP_POST 0b00000010; +#define XHTTP_DELETE 0b00000100; +#define XHTTP_PUT 0b00001000; +#define XHTTP_PATCH 0b00010000; +#define XHTTP_HEAD 0b00100000; +#define XHTTP_OPTIONS 0b01000000; +#define XHTTP_ANY 0b01111111; */ + +#define HTTP_ANY 0b01111111 +#define HTTP_GET 0b00000001 + +#include +#include + +//#include "network/api/utilities/apiUtilities.hpp" //! Only needed for the shaEncoder function (for now) #include "data/utilities/network_utilities.hpp" -class BaseAPI : public API_Utilities +#include "data/config/project_config.hpp" +#include "data/StateManager/StateManager.hpp" +#include "io/camera/cameraHandler.hpp" + +class BaseAPI { protected: + std::string api_url; enum JSON_TYPES { @@ -29,6 +54,14 @@ protected: {"wifiap", WIFIAP}, }; + static const char *MIMETYPE_HTML; + /* static const char *MIMETYPE_CSS; */ + /* static const char *MIMETYPE_JS; */ + /* static const char *MIMETYPE_PNG; */ + /* static const char *MIMETYPE_JPG; */ + /* static const char *MIMETYPE_ICO; */ + static const char *MIMETYPE_JSON; + protected: /* Commands */ void setWiFi(AsyncWebServerRequest *request); @@ -51,6 +84,41 @@ protected: route_t routes; route_map_t route_map; + std::unordered_map _networkMethodsMap = { + {0b00000001, "GET"}, + {0b00000010, "POST"}, + {0b00001000, "PUT"}, + {0b00000100, "DELETE"}, + {0b00010000, "PATCH"}, + {0b01000000, "OPTIONS"}, + }; + + enum RequestMethods + { + GET, + POST, + PUT, + DELETE, + PATCH, + OPTIONS, + }; + + std::unordered_map _networkMethodsMap_enum = { + {0b00000001, GET}, + {0b00000010, POST}, + {0b00001000, PUT}, + {0b00000100, DELETE}, + {0b00010000, PATCH}, + {0b01000000, OPTIONS}, + }; + + typedef std::unordered_map networkMethodsMap_t; + + ProjectConfig *projectConfig; + AsyncWebServer *server; + CameraHandler *camera; + StateManager *WiFiStateManager; + public: BaseAPI(int CONTROL_PORT, ProjectConfig *projectConfig, @@ -60,6 +128,7 @@ public: virtual ~BaseAPI(); virtual void begin(); + void notFound(AsyncWebServerRequest *request) const; }; #endif // BASEAPI_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp index 43be408..0be0dff 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.cpp @@ -1,28 +1,10 @@ #include "apiUtilities.hpp" -//! These have to be called before the constructor of the class because they are static -//! C++ 11 does not have inline variables, sadly. So we have to do this. -const char *API_Utilities::MIMETYPE_HTML{"text/html"}; -// const char *BaseAPI::MIMETYPE_CSS{"text/css"}; -// const char *BaseAPI::MIMETYPE_JS{"application/javascript"}; -// const char *BaseAPI::MIMETYPE_PNG{"image/png"}; -// const char *BaseAPI::MIMETYPE_JPG{"image/jpeg"}; -// const char *BaseAPI::MIMETYPE_ICO{"image/x-icon"}; -const char *API_Utilities::MIMETYPE_JSON{"application/json"}; - //********************************************************************************************* //! API Utilities //********************************************************************************************* -API_Utilities::API_Utilities(int CONTROL_PORT, - ProjectConfig *projectConfig, - CameraHandler *camera, - StateManager *WiFiStateManager, - const std::string &api_url) : server(new AsyncWebServer(CONTROL_PORT)), - projectConfig(projectConfig), - WiFiStateManager(WiFiStateManager), - camera(camera), - api_url(api_url) {} +API_Utilities::API_Utilities() {}; API_Utilities::~API_Utilities() {} @@ -54,18 +36,3 @@ std::string API_Utilities::shaEncoder(std::string data) } return hash_string; } - -void API_Utilities::notFound(AsyncWebServerRequest *request) const -{ - if (_networkMethodsMap.find(request->method()) != _networkMethodsMap.end()) - { - log_i("%s: http://%s%s/\n", _networkMethodsMap.at(request->method()).c_str(), request->host().c_str(), request->url().c_str()); - char buffer[100]; - snprintf(buffer, sizeof(buffer), "Request %s Not found: %s", _networkMethodsMap.at(request->method()).c_str(), request->url().c_str()); - request->send(404, "text/plain", buffer); - } - else - { - request->send(404, "text/plain", "Request Not found using unknown method"); - } -} \ No newline at end of file diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp index 13cfc29..38df323 100644 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ b/ESP/lib/src/network/api/utilities/apiUtilities.hpp @@ -1,90 +1,20 @@ #ifndef APIUTILITIES_HPP #define APIUTILITIES_HPP -#include #include - -#define WEBSERVER_H - -/* #define XHTTP_GET 0b00000001; -#define XHTTP_POST 0b00000010; -#define XHTTP_DELETE 0b00000100; -#define XHTTP_PUT 0b00001000; -#define XHTTP_PATCH 0b00010000; -#define XHTTP_HEAD 0b00100000; -#define XHTTP_OPTIONS 0b01000000; -#define XHTTP_ANY 0b01111111; */ - -#define HTTP_ANY 0b01111111 -#define HTTP_GET 0b00000001 - -#include -#include //#include #include "mbedtls/md.h" -#include "data/config/project_config.hpp" -#include "network/wifihandler/WifiHandler.hpp" -#include "data/StateManager/StateManager.hpp" -#include "io/camera/cameraHandler.hpp" +#include "data/utilities/network_utilities.hpp" class API_Utilities { public: - API_Utilities(int CONTROL_PORT, - ProjectConfig *projectConfig, - CameraHandler *camera, - StateManager *WiFiStateManager, - const std::string &api_url); + API_Utilities(); virtual ~API_Utilities(); + static std::string shaEncoder(std::string data); -protected: - void notFound(AsyncWebServerRequest *request) const; - std::string shaEncoder(std::string data); - std::unordered_map _networkMethodsMap = { - {0b00000001, "GET"}, - {0b00000010, "POST"}, - {0b00001000, "PUT"}, - {0b00000100, "DELETE"}, - {0b00010000, "PATCH"}, - {0b01000000, "OPTIONS"}, - }; - - enum RequestMethods - { - GET, - POST, - PUT, - DELETE, - PATCH, - OPTIONS, - }; - - std::unordered_map _networkMethodsMap_enum = { - {0b00000001, GET}, - {0b00000010, POST}, - {0b00001000, PUT}, - {0b00000100, DELETE}, - {0b00010000, PATCH}, - {0b01000000, OPTIONS}, - }; - -protected: - ProjectConfig *projectConfig; - AsyncWebServer *server; - CameraHandler *camera; - StateManager *WiFiStateManager; - typedef std::unordered_map networkMethodsMap_t; - -protected: - std::string api_url; - - static const char *MIMETYPE_HTML; - /* static const char *MIMETYPE_CSS; */ - /* static const char *MIMETYPE_JS; */ - /* static const char *MIMETYPE_PNG; */ - /* static const char *MIMETYPE_JPG; */ - /* static const char *MIMETYPE_ICO; */ - static const char *MIMETYPE_JSON; +public: + }; #endif // APIUTILITIES_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index f878e7d..788445d 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -37,10 +37,10 @@ void APIServer::setupServer() routes.emplace("resetConfig", &APIServer::factoryReset); routes.emplace("rebootDevice", &APIServer::rebootDevice); routes.emplace("setJson", &APIServer::handleJson); - routes.emplace("setCamera", &APIServer::setCamera); routes.emplace("deleteRoute", &APIServer::deleteRoute); - routes.emplace("restartCamera", &APIServer::restartCamera); // Camera Routes + routes.emplace("setCamera", &APIServer::setCamera); + routes.emplace("restartCamera", &APIServer::restartCamera); //! reserve enough memory for all routes - must be called after adding routes and before adding routes to route_map indexes.reserve(routes.size()); // this is done to avoid reallocation of memory and copying of data From 30067f7648be5b73f3722400433c3dadfbae7333 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Fri, 9 Sep 2022 11:41:10 +0100 Subject: [PATCH 094/153] update - Fully deprecate API_Utilities - Move shaEncoder method to Network_Utilities namespace - Delete API_Utilities --- .../src/data/utilities/network_utilities.cpp | 29 ++++++++++++++ .../src/data/utilities/network_utilities.hpp | 2 + ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 2 +- .../network/api/utilities/apiUtilities.cpp | 38 ------------------- .../network/api/utilities/apiUtilities.hpp | 20 ---------- 5 files changed, 32 insertions(+), 59 deletions(-) delete mode 100644 ESP/lib/src/network/api/utilities/apiUtilities.cpp delete mode 100644 ESP/lib/src/network/api/utilities/apiUtilities.hpp diff --git a/ESP/lib/src/data/utilities/network_utilities.cpp b/ESP/lib/src/data/utilities/network_utilities.cpp index 2a9804b..270ca66 100644 --- a/ESP/lib/src/data/utilities/network_utilities.cpp +++ b/ESP/lib/src/data/utilities/network_utilities.cpp @@ -44,4 +44,33 @@ void Network_Utilities::my_delay(volatile long delay_time) delay_time = delay_time * 1e6L; for (volatile long count = delay_time; count > 0L; count--) ; +} + +std::string shaEncoder(const std::string &data) +{ + const char *data_c = data.c_str(); + int size = 64; + uint8_t hash[size]; + mbedtls_md_context_t ctx; + mbedtls_md_type_t md_type = MBEDTLS_MD_SHA512; + + const size_t len = strlen(data_c); + mbedtls_md_init(&ctx); + mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); + mbedtls_md_starts(&ctx); + mbedtls_md_update(&ctx, (const unsigned char *)data_c, len); + mbedtls_md_finish(&ctx, hash); + mbedtls_md_free(&ctx); + + std::string hash_string = ""; + for (uint16_t i = 0; i < size; i++) + { + std::string hex = String(hash[i], HEX).c_str(); + if (hex.length() < 2) + { + hex = "0" + hex; + } + hash_string += hex; + } + return hash_string; } \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/network_utilities.hpp b/ESP/lib/src/data/utilities/network_utilities.hpp index 972f25c..a26db42 100644 --- a/ESP/lib/src/data/utilities/network_utilities.hpp +++ b/ESP/lib/src/data/utilities/network_utilities.hpp @@ -4,6 +4,7 @@ #include #include #include +#include "mbedtls/md.h" namespace Network_Utilities { bool LoopWifiScan(); @@ -11,5 +12,6 @@ namespace Network_Utilities void my_delay(volatile long delay_time); int CheckWifiState(); int getStrength(int points); + static std::string shaEncoder(const std::string &data); } #endif // !UTILITIES_hpp \ No newline at end of file diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index e3d03e1..cf32259 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -2,7 +2,7 @@ //! These have to be called before the constructor of the class because they are static //! C++ 11 does not have inline variables, sadly. So we have to do this. -//const char *BaseAPI::MIMETYPE_HTML{"text/html"}; +// const char *BaseAPI::MIMETYPE_HTML{"text/html"}; // const char *BaseAPI::MIMETYPE_CSS{"text/css"}; // const char *BaseAPI::MIMETYPE_JS{"application/javascript"}; // const char *BaseAPI::MIMETYPE_PNG{"image/png"}; diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.cpp b/ESP/lib/src/network/api/utilities/apiUtilities.cpp deleted file mode 100644 index 0be0dff..0000000 --- a/ESP/lib/src/network/api/utilities/apiUtilities.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "apiUtilities.hpp" - -//********************************************************************************************* -//! API Utilities -//********************************************************************************************* - -API_Utilities::API_Utilities() {}; - -API_Utilities::~API_Utilities() {} - -std::string API_Utilities::shaEncoder(std::string data) -{ - const char *data_c = data.c_str(); - int size = 64; - uint8_t hash[size]; - mbedtls_md_context_t ctx; - mbedtls_md_type_t md_type = MBEDTLS_MD_SHA512; - - const size_t len = strlen(data_c); - mbedtls_md_init(&ctx); - mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); - mbedtls_md_starts(&ctx); - mbedtls_md_update(&ctx, (const unsigned char *)data_c, len); - mbedtls_md_finish(&ctx, hash); - mbedtls_md_free(&ctx); - - std::string hash_string = ""; - for (uint16_t i = 0; i < size; i++) - { - std::string hex = String(hash[i], HEX).c_str(); - if (hex.length() < 2) - { - hex = "0" + hex; - } - hash_string += hex; - } - return hash_string; -} diff --git a/ESP/lib/src/network/api/utilities/apiUtilities.hpp b/ESP/lib/src/network/api/utilities/apiUtilities.hpp deleted file mode 100644 index 38df323..0000000 --- a/ESP/lib/src/network/api/utilities/apiUtilities.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef APIUTILITIES_HPP -#define APIUTILITIES_HPP - -#include -//#include -#include "mbedtls/md.h" -#include "data/utilities/network_utilities.hpp" - -class API_Utilities -{ -public: - API_Utilities(); - virtual ~API_Utilities(); - static std::string shaEncoder(std::string data); - -public: - -}; - -#endif // APIUTILITIES_HPP \ No newline at end of file From dcaefbccac3d469e57bdac5a8b1825d00f2cb2aa Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Fri, 9 Sep 2022 22:49:11 +0100 Subject: [PATCH 095/153] Major Update - Added proper Automated naming scheme for firmware files. Looks awesome now :) - changed "easynetwork" to "openiris" in project_config.cpp --- ESP/lib/src/data/config/project_config.cpp | 4 +-- ESP/platformio.ini | 29 ++++++++++++++-------- ESP/tools/customname.py | 23 +++++++++++++++++ ESP/tools/git_rev.py | 25 +++++++++++++++++++ 4 files changed, 68 insertions(+), 13 deletions(-) create mode 100644 ESP/tools/customname.py create mode 100644 ESP/tools/git_rev.py diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 55e5ebd..0d38d6c 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -119,7 +119,7 @@ void ProjectConfig::load() } /* Device Config */ - this->config.device.name = getString("deviceName", "easynetwork").c_str(); + this->config.device.name = getString("deviceName", "openiris").c_str(); this->config.device.OTAPassword = getString("OTAPassword", "12345678").c_str(); this->config.device.OTAPort = getInt("OTAPort", 3232); //! No need to load the JSON strings or bools, they are generated and used on the fly @@ -155,7 +155,7 @@ void ProjectConfig::load() } /* AP Config */ - this->config.ap_network.ssid = getString("apSSID", "easynetwork").c_str(); + this->config.ap_network.ssid = getString("apSSID", "openiris").c_str(); this->config.ap_network.password = getString("apPass", "12345678").c_str(); this->config.ap_network.channel = getUInt("apChannel", 1); diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 66cbc4c..86ad2e5 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -75,6 +75,8 @@ monitor_filters = time default esp32_exception_decoder + +release_version = 0.0.1 ; increase this value every release build build_flags = @@ -102,18 +104,20 @@ build_flags = -DCORE_DEBUG_LEVEL=4 + !python tools\git_rev.py ; add git revision to build as preprocessor defines + -DBOARD_HAS_PSRAM - - -DASYNCWEBSERVER_REGEX ; add regex support to AsyncWebServer + + -DASYNCWEBSERVER_REGEX -mfix-esp32-psram-cache-issue + build_unflags = -Os ; board_build.partitions = min_spiffs.csv board_build.partitions = huge_app.csv lib_ldf_mode = deep+ upload_speed = 921600 -release_version = 0.0.1 ; increase this value every release build lib_deps = esp32-camera leftcoast/LC_baseTools@^1.5 @@ -123,6 +127,7 @@ lib_deps = https://github.com/bblanchon/ArduinoJson.git build_type = debug +extra_scripts = pre:tools/customname.py [env:esp32Cam] platform = ${common.platform} @@ -153,6 +158,7 @@ build_flags = ${common.build_flags} -DPCLK_GPIO_NUM=${pinoutsESPCAM.PCLK_GPIO_NUM} ; Set the PCLK pin -DDEBUG_MODE=1 ; Set the debug mode + -DVERSION=0 build_unflags = ${common.build_unflags} board_build.partitions = ${common.board_build.partitions} @@ -160,6 +166,7 @@ lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} build_type = ${common.build_type} +extra_scripts = ${common.extra_scripts} [env:esp32Cam_release] platform = ${common.platform} @@ -179,6 +186,7 @@ lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} build_type = release +extra_scripts = ${common.extra_scripts} ; Experimental OTA Environment - do not select unless you know what you are doing [env:esp32Cam_OTA] @@ -191,13 +199,11 @@ build_flags = -DCORE_DEBUG_LEVEL=1 -DDEBUG_ESP_OTA -DVERSION=${common.release_version} -lib_deps = - ${common.lib_deps} +lib_deps = ${common.lib_deps} upload_speed = ${common.upload_speed} monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} -; extra_scripts = ${common.extra_scripts} board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_port = 192.168.1.38 @@ -206,6 +212,7 @@ upload_flags = --port=3232 --auth=12345678 build_type = release +extra_scripts = ${common.extra_scripts} [env:wrover] platform = ${common.platform} @@ -242,10 +249,10 @@ build_unflags = ${common.build_unflags} board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} -lib_deps = - ${common.lib_deps} +lib_deps = ${common.lib_deps} ;upload_port = COM6 build_type = ${common.build_type} +extra_scripts = ${common.extra_scripts} [env:wrover_release] platform = ${common.platform} @@ -266,6 +273,7 @@ upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} upload_port = COM6 build_type = release +extra_scripts = ${common.extra_scripts} ; Experimental OTA Environment - do not select unless you know what you are doing [env:wrover_OTA] @@ -278,13 +286,11 @@ build_flags = -DCORE_DEBUG_LEVEL=1 -DDEBUG_ESP_OTA -DVERSION=${common.release_version} -lib_deps = - ${common.lib_deps} +lib_deps = ${common.lib_deps} upload_speed = ${common.upload_speed} monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} -; extra_scripts = ${common.extra_scripts} board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_port = 192.168.1.38 @@ -293,3 +299,4 @@ upload_flags = --port=3232 --auth=12345678 build_type = release +extra_scripts = ${common.extra_scripts} \ No newline at end of file diff --git a/ESP/tools/customname.py b/ESP/tools/customname.py new file mode 100644 index 0000000..9d465e7 --- /dev/null +++ b/ESP/tools/customname.py @@ -0,0 +1,23 @@ +# Description: Custom name for firmware + +Import("env") + +my_flags = env.ParseFlags(env['BUILD_FLAGS']) +defines = dict() +for x in my_flags.get("CPPDEFINES"): + if type(x) is tuple: + (k,v) = x + defines[k] = v + elif type(x) is list: + k = x[0] + v = x[1] + defines[k] = v + else: + defines[x] = "" # empty value +# defines.get("PIO_SRC_TAG") - tag name +# strip quotes needed for shell escaping +s = lambda x: x.replace('"', "") +env.Replace( + PROGNAME="%s-%s-%s-%s-%s" % + (s(defines.get("PIO_SRC_NAM")), s(defines.get("VERSION")), str(env["BOARD"]), + s(defines.get("PIO_SRC_REV")), s(defines.get("PIO_SRC_BRH")))) diff --git a/ESP/tools/git_rev.py b/ESP/tools/git_rev.py new file mode 100644 index 0000000..90dc59a --- /dev/null +++ b/ESP/tools/git_rev.py @@ -0,0 +1,25 @@ +import subprocess + +# Get Git project name +projcmd = "git rev-parse --show-toplevel" +project = subprocess.check_output(projcmd, shell=True).decode().strip() +project = project.split("/") +project = project[len(project)-1] + +# Get 0.0.0 version from latest Git tag +# tagcmd = "git describe --tags --abbrev=0" +# version = subprocess.check_output(tagcmd, shell=True).decode().strip() + +# Get latest commit short from Git +revcmd = "git log --pretty=format:'%h' -n 1" +commit = subprocess.check_output(revcmd, shell=True).decode().strip() + +# Get branch name from Git +branchcmd = "git rev-parse --abbrev-ref HEAD" +branch = subprocess.check_output(branchcmd, shell=True).decode().strip() + +# Make all available for use in the macros +print("-DPIO_SRC_NAM={0}".format(project)) +# print("-DPIO_SRC_TAG={0}".format(version)) +print("-DPIO_SRC_REV={0}".format(commit)) +print("-DPIO_SRC_BRH={0}".format(branch)) \ No newline at end of file From daf44c7e7127ca0fc465290c936dc95e5def9577 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 10 Sep 2022 15:05:32 +0100 Subject: [PATCH 096/153] update - Disabled build_partitions by default to allow for out-of-box OTA support - Added -O2 build flag to optimize for speed - added comments on build flags to explain what they do --- ESP/platformio.ini | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 86ad2e5..0d0cb70 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -80,6 +80,8 @@ release_version = 0.0.1 ; increase this value every release build build_flags = + !python tools\git_rev.py ; add git revision to build as preprocessor defines + -DOTA_SERVER_PORT=${wifi.OTAServerPort} ; Set the OTA server -DENABLE_ADHOC=${wifi.enableADHOC} ; @@ -100,22 +102,22 @@ build_flags = '-DWIFI_AP_PASSWORD=${wifi.ap_password}' ; Set the users wifi network password - -DDEBUG_ESP_PORT=Serial + -DDEBUG_ESP_PORT=Serial ; set the debug port - -DCORE_DEBUG_LEVEL=4 + -DCORE_DEBUG_LEVEL=4 ; set the debug level - !python tools\git_rev.py ; add git revision to build as preprocessor defines + -O2 ; optimize for speed - -DBOARD_HAS_PSRAM + -DBOARD_HAS_PSRAM ; enable psram - -DASYNCWEBSERVER_REGEX + -DASYNCWEBSERVER_REGEX ; enable regex in asyncwebserver - -mfix-esp32-psram-cache-issue + -mfix-esp32-psram-cache-issue ; fix for psram -build_unflags = -Os -; board_build.partitions = min_spiffs.csv -board_build.partitions = huge_app.csv +build_unflags = -Os ; disable optimization for size +; board_build.partitions = min_spiffs.csv ; uncomment this to use the min_spiffs partition table, great for using OTA and SPIFFS +; board_build.partitions = huge_app.csv ; uncomment this to use the huge_app partition table, does not support OTA and only 1MB of SPIFFS lib_ldf_mode = deep+ upload_speed = 921600 lib_deps = From 1b90d77f73f9d4e7e4c1fb37a58b6d92442439a0 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 10 Sep 2022 15:29:34 +0100 Subject: [PATCH 097/153] minor update - comment out build_unflags to allow optimization for size by default - fix last commit build error - format ini file to be more readable --- ESP/platformio.ini | 122 +++++++++++++++++++++------------------------ 1 file changed, 57 insertions(+), 65 deletions(-) diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 0d0cb70..3854a3e 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -79,50 +79,33 @@ monitor_filters = release_version = 0.0.1 ; increase this value every release build build_flags = - !python tools\git_rev.py ; add git revision to build as preprocessor defines - -DOTA_SERVER_PORT=${wifi.OTAServerPort} ; Set the OTA server - -DENABLE_ADHOC=${wifi.enableADHOC} ; - -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 - '-DOTA_PASSWORD=${wifi.OTAPassword}' ; Set the OTA password - '-DWIFI_SSID=${wifi.ssid}' ; Set the users wifi network name - '-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 ; set the debug port - -DCORE_DEBUG_LEVEL=4 ; set the debug level - -O2 ; optimize for speed - -DBOARD_HAS_PSRAM ; enable psram - -DASYNCWEBSERVER_REGEX ; enable regex in asyncwebserver - -mfix-esp32-psram-cache-issue ; fix for psram - -build_unflags = -Os ; disable optimization for size -; board_build.partitions = min_spiffs.csv ; uncomment this to use the min_spiffs partition table, great for using OTA and SPIFFS -; board_build.partitions = huge_app.csv ; uncomment this to use the huge_app partition table, does not support OTA and only 1MB of SPIFFS +;build_unflags = -Os ; disable optimization for size +;board_build.partitions = min_spiffs.csv ; uncomment this to use the min_spiffs partition table, great for using OTA and SPIFFS +;board_build.partitions = huge_app.csv ; uncomment this to use the huge_app partition table, does not support OTA and only 1MB of SPIFFS lib_ldf_mode = deep+ upload_speed = 921600 lib_deps = esp32-camera leftcoast/LC_baseTools@^1.5 + ; geeksville/Micro-RTSP @ ^0.1.6 ; Micro-RTSP library for streaming video over RTSP - will be implemented soon https://github.com/ZanzyTHEbar/EasyPreferencesLibrary.git https://github.com/me-no-dev/ESPAsyncWebServer.git https://github.com/me-no-dev/AsyncTCP.git @@ -139,6 +122,13 @@ monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} monitor_filters = ${common.monitor_filters} +;build_unflags = ${common.build_unflags} +;board_build.partitions = ${common.board_build.partitions} +lib_ldf_mode = ${common.lib_ldf_mode} +upload_speed = ${common.upload_speed} +lib_deps = ${common.lib_deps} +build_type = ${common.build_type} +extra_scripts = ${common.extra_scripts} build_flags = ${common.build_flags} ; CAMERA PINOUT DEFINITIONS @@ -162,14 +152,6 @@ build_flags = ${common.build_flags} -DDEBUG_MODE=1 ; Set the debug mode -DVERSION=0 -build_unflags = ${common.build_unflags} -board_build.partitions = ${common.board_build.partitions} -lib_ldf_mode = ${common.lib_ldf_mode} -upload_speed = ${common.upload_speed} -lib_deps = ${common.lib_deps} -build_type = ${common.build_type} -extra_scripts = ${common.extra_scripts} - [env:esp32Cam_release] platform = ${common.platform} board = esp32cam @@ -177,18 +159,18 @@ framework = ${common.framework} monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} -build_flags = - ${common.build_flags} - -DDEBUG_MODE=0 ; Set the debug mode - -DCORE_DEBUG_LEVEL=1 - -DVERSION=${common.release_version} -build_unflags = ${common.build_unflags} -board_build.partitions = ${common.board_build.partitions} +;build_unflags = ${common.build_unflags} +;board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} build_type = release extra_scripts = ${common.extra_scripts} +build_flags = + ${common.build_flags} + -DDEBUG_MODE=0 ; Set the debug mode + -DCORE_DEBUG_LEVEL=1 + -DVERSION=${common.release_version} ; Experimental OTA Environment - do not select unless you know what you are doing [env:esp32Cam_OTA] @@ -206,7 +188,8 @@ upload_speed = ${common.upload_speed} monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} -board_build.partitions = ${common.board_build.partitions} +;build_unflags = ${common.build_unflags} +;board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_port = 192.168.1.38 upload_protocol = espota @@ -220,8 +203,18 @@ extra_scripts = ${common.extra_scripts} platform = ${common.platform} board = esp-wrover-kit framework = ${common.framework} +board_build.f_flash = 80000000L +board_build.flash_mode = qio monitor_speed = ${common.monitor_speed} monitor_filters = ${common.monitor_filters} +;build_unflags = ${common.build_unflags} +;board_build.partitions = ${common.board_build.partitions} +lib_ldf_mode = ${common.lib_ldf_mode} +upload_speed = ${common.upload_speed} +lib_deps = ${common.lib_deps} +;upload_port = COM6 +build_type = ${common.build_type} +extra_scripts = ${common.extra_scripts} ;monitor_rts = ${common.monitor_rts} ;monitor_dtr = ${common.monitor_dtr} build_flags = @@ -247,58 +240,57 @@ build_flags = -DHREF_GPIO_NUM=${pinoutsESPWROVER.HREF_GPIO_NUM} ; Set the HREF pin -DPCLK_GPIO_NUM=${pinoutsESPWROVER.PCLK_GPIO_NUM} ; Set the PCLK pin -build_unflags = ${common.build_unflags} -board_build.partitions = ${common.board_build.partitions} +[env:wrover_release] +platform = ${common.platform} +board = esp-wrover-kit +framework = ${common.framework} +board_build.f_flash = 80000000L +board_build.flash_mode = qio +monitor_speed = ${common.monitor_speed} +monitor_filters = ${common.monitor_filters} +;build_unflags = ${common.build_unflags} +;board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} ;upload_port = COM6 build_type = ${common.build_type} extra_scripts = ${common.extra_scripts} - -[env:wrover_release] -platform = ${common.platform} -board = esp-wrover-kit -framework = ${common.framework} -monitor_speed = ${common.monitor_speed} -monitor_rts = ${common.monitor_rts} -monitor_dtr = ${common.monitor_dtr} +;monitor_rts = ${common.monitor_rts} +;monitor_dtr = ${common.monitor_dtr} build_flags = ${common.build_flags} -DDEBUG_MODE=0 ; Set the debug mode -DCORE_DEBUG_LEVEL=1 -DVERSION=${common.release_version} -build_unflags = ${common.build_unflags} -board_build.partitions = ${common.board_build.partitions} -lib_ldf_mode = ${common.lib_ldf_mode} -upload_speed = ${common.upload_speed} -lib_deps = ${common.lib_deps} -upload_port = COM6 -build_type = release -extra_scripts = ${common.extra_scripts} ; Experimental OTA Environment - do not select unless you know what you are doing [env:wrover_OTA] platform = ${common.platform} board = esp-wrover-kit framework = ${common.framework} +board_build.f_flash = 80000000L +board_build.flash_mode = qio +monitor_speed = ${common.monitor_speed} +monitor_filters = ${common.monitor_filters} +;build_unflags = ${common.build_unflags} +;board_build.partitions = ${common.board_build.partitions} +lib_ldf_mode = ${common.lib_ldf_mode} +upload_speed = ${common.upload_speed} +lib_deps = ${common.lib_deps} +build_type = release +extra_scripts = ${common.extra_scripts} +;monitor_rts = ${common.monitor_rts} +;monitor_dtr = ${common.monitor_dtr} + build_flags = ${common.build_flags} -DDEBUG_MODE=0 ; Set the debug mode -DCORE_DEBUG_LEVEL=1 -DDEBUG_ESP_OTA -DVERSION=${common.release_version} -lib_deps = ${common.lib_deps} -upload_speed = ${common.upload_speed} -monitor_speed = ${common.monitor_speed} -monitor_rts = ${common.monitor_rts} -monitor_dtr = ${common.monitor_dtr} -board_build.partitions = ${common.board_build.partitions} -lib_ldf_mode = ${common.lib_ldf_mode} upload_port = 192.168.1.38 upload_protocol = espota upload_flags = --port=3232 - --auth=12345678 -build_type = release -extra_scripts = ${common.extra_scripts} \ No newline at end of file + --auth=12345678 \ No newline at end of file From 3f0c0dfee5f26872e94b70dfe0c97d58e2f103a2 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 10 Sep 2022 15:33:46 +0100 Subject: [PATCH 098/153] update - Add min_spiffs.csv as default partition table --- ESP/platformio.ini | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 3854a3e..6f5ce86 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -98,7 +98,7 @@ build_flags = -mfix-esp32-psram-cache-issue ; fix for psram ;build_unflags = -Os ; disable optimization for size -;board_build.partitions = min_spiffs.csv ; uncomment this to use the min_spiffs partition table, great for using OTA and SPIFFS +board_build.partitions = min_spiffs.csv ; uncomment this to use the min_spiffs partition table, great for using OTA ;board_build.partitions = huge_app.csv ; uncomment this to use the huge_app partition table, does not support OTA and only 1MB of SPIFFS lib_ldf_mode = deep+ upload_speed = 921600 @@ -123,7 +123,7 @@ monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} monitor_filters = ${common.monitor_filters} ;build_unflags = ${common.build_unflags} -;board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} @@ -160,7 +160,7 @@ monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} ;build_unflags = ${common.build_unflags} -;board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} @@ -189,7 +189,7 @@ monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} ;build_unflags = ${common.build_unflags} -;board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_port = 192.168.1.38 upload_protocol = espota @@ -208,7 +208,7 @@ board_build.flash_mode = qio monitor_speed = ${common.monitor_speed} monitor_filters = ${common.monitor_filters} ;build_unflags = ${common.build_unflags} -;board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} @@ -249,7 +249,7 @@ board_build.flash_mode = qio monitor_speed = ${common.monitor_speed} monitor_filters = ${common.monitor_filters} ;build_unflags = ${common.build_unflags} -;board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} @@ -274,7 +274,7 @@ board_build.flash_mode = qio monitor_speed = ${common.monitor_speed} monitor_filters = ${common.monitor_filters} ;build_unflags = ${common.build_unflags} -;board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} From 711905a1f47984c471434dfd06115ec4eaf05019 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 10 Sep 2022 17:25:29 +0100 Subject: [PATCH 099/153] large update - Added auto-versioning system to firmware name - Formatted ini file - setup OTA enabled state to be controllable by the user --- ESP/platformio.ini | 100 ++++++++++++++++-------------------- ESP/src/main.cpp | 16 ++++-- ESP/tools/autoversioning.py | 14 +++++ ESP/tools/versioning | 1 + 4 files changed, 73 insertions(+), 58 deletions(-) create mode 100644 ESP/tools/autoversioning.py create mode 100644 ESP/tools/versioning diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 6f5ce86..8d8b49c 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -23,6 +23,7 @@ OTAPassword="" ; if empty, no password will be required OTAServerPort=3232 enableADHOC=0 ; 0 = disable, 1 = enable adhocChannel=1 ; channel to use for adhoc network +enableOTA=1 ; 0 = disable, 1 = enable ; DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING [pinoutsESPCAM] @@ -76,14 +77,17 @@ monitor_filters = default esp32_exception_decoder -release_version = 0.0.1 ; increase this value every release build - +;board_build.partitions = ${common.board_build.partitions} ; uncomment this to use the huge_app partition table, does not support OTA and only 1MB of SPIFFS +board_build.partitions = min_spiffs.csv ; uncomment this to use the min_spiffs partition table, supports OTA and 1MB of SPIFFS + build_flags = + !python tools\autoversioning.py ; add build version to build as preprocessor defines !python tools\git_rev.py ; add git revision to build as preprocessor defines -DOTA_SERVER_PORT=${wifi.OTAServerPort} ; Set the OTA server -DENABLE_ADHOC=${wifi.enableADHOC} ; -DADHOC_CHANNEL=${wifi.adhocChannel} ; -DWIFI_CHANNEL=${wifi.channel} ; + -DENABLE_OTA=${wifi.enableOTA} ; '-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 '-DOTA_PASSWORD=${wifi.OTAPassword}' ; Set the OTA password '-DWIFI_SSID=${wifi.ssid}' ; Set the users wifi network name @@ -98,8 +102,6 @@ build_flags = -mfix-esp32-psram-cache-issue ; fix for psram ;build_unflags = -Os ; disable optimization for size -board_build.partitions = min_spiffs.csv ; uncomment this to use the min_spiffs partition table, great for using OTA -;board_build.partitions = huge_app.csv ; uncomment this to use the huge_app partition table, does not support OTA and only 1MB of SPIFFS lib_ldf_mode = deep+ upload_speed = 921600 lib_deps = @@ -123,7 +125,7 @@ monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} monitor_filters = ${common.monitor_filters} ;build_unflags = ${common.build_unflags} -board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} ; lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} @@ -150,7 +152,6 @@ build_flags = ${common.build_flags} -DPCLK_GPIO_NUM=${pinoutsESPCAM.PCLK_GPIO_NUM} ; Set the PCLK pin -DDEBUG_MODE=1 ; Set the debug mode - -DVERSION=0 [env:esp32Cam_release] platform = ${common.platform} @@ -160,36 +161,32 @@ monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} ;build_unflags = ${common.build_unflags} -board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} ; lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} build_type = release extra_scripts = ${common.extra_scripts} -build_flags = - ${common.build_flags} - -DDEBUG_MODE=0 ; Set the debug mode - -DCORE_DEBUG_LEVEL=1 - -DVERSION=${common.release_version} +build_flags = ${common.build_flags} + -DDEBUG_MODE=0 ; Set the debug mode + -DCORE_DEBUG_LEVEL=1 ; Experimental OTA Environment - do not select unless you know what you are doing [env:esp32Cam_OTA] platform = ${common.platform} board = esp32cam framework = ${common.framework} -build_flags = - ${common.build_flags} - -DDEBUG_MODE=0 ; Set the debug mode - -DCORE_DEBUG_LEVEL=1 - -DDEBUG_ESP_OTA - -DVERSION=${common.release_version} +build_flags = ${common.build_flags} + -DDEBUG_MODE=0 ; Set the debug mode + -DCORE_DEBUG_LEVEL=1 + -DDEBUG_ESP_OTA lib_deps = ${common.lib_deps} upload_speed = ${common.upload_speed} monitor_speed = ${common.monitor_speed} monitor_rts = ${common.monitor_rts} monitor_dtr = ${common.monitor_dtr} ;build_unflags = ${common.build_unflags} -board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} ; uncomment this to use the min_spiffs partition table, great for using OTA lib_ldf_mode = ${common.lib_ldf_mode} upload_port = 192.168.1.38 upload_protocol = espota @@ -208,7 +205,7 @@ board_build.flash_mode = qio monitor_speed = ${common.monitor_speed} monitor_filters = ${common.monitor_filters} ;build_unflags = ${common.build_unflags} -board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} ; uncomment this to use the huge_app partition table, does not support OTA and only 1MB of SPIFFS lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} @@ -217,28 +214,25 @@ build_type = ${common.build_type} extra_scripts = ${common.extra_scripts} ;monitor_rts = ${common.monitor_rts} ;monitor_dtr = ${common.monitor_dtr} -build_flags = - ${common.build_flags} - -DDEBUG_MODE=1 ; Set the debug mode - -DVERSION=0 - - ; CAMERA PINOUT DEFINITIONS - -DPWDN_GPIO_NUM=${pinoutsESPWROVER.PWDN_GPIO_NUM} ; Set the PWDN pin - -DRESET_GPIO_NUM=${pinoutsESPWROVER.RESET_GPIO_NUM} ; Set the RESET pin - -DXCLK_GPIO_NUM=${pinoutsESPWROVER.XCLK_GPIO_NUM} ; Set the XCLK pin - -DSIOD_GPIO_NUM=${pinoutsESPWROVER.SIOD_GPIO_NUM} ; Set the SIOD pin - -DSIOC_GPIO_NUM=${pinoutsESPWROVER.SIOC_GPIO_NUM} ; Set the SIOC pin - -DY9_GPIO_NUM=${pinoutsESPWROVER.Y9_GPIO_NUM} ; Set the Y9 pin - -DY8_GPIO_NUM=${pinoutsESPWROVER.Y8_GPIO_NUM} ; Set the Y8 pin - -DY7_GPIO_NUM=${pinoutsESPWROVER.Y7_GPIO_NUM} ; Set the Y7 pin - -DY6_GPIO_NUM=${pinoutsESPWROVER.Y6_GPIO_NUM} ; Set the Y6 pin - -DY5_GPIO_NUM=${pinoutsESPWROVER.Y5_GPIO_NUM} ; Set the Y5 pin - -DY4_GPIO_NUM=${pinoutsESPWROVER.Y4_GPIO_NUM} ; Set the Y4 pin - -DY3_GPIO_NUM=${pinoutsESPWROVER.Y3_GPIO_NUM} ; Set the Y3 pin - -DY2_GPIO_NUM=${pinoutsESPWROVER.Y2_GPIO_NUM} ; Set the Y2 pin - -DVSYNC_GPIO_NUM=${pinoutsESPWROVER.VSYNC_GPIO_NUM} ; Set the VSYNC pin - -DHREF_GPIO_NUM=${pinoutsESPWROVER.HREF_GPIO_NUM} ; Set the HREF pin - -DPCLK_GPIO_NUM=${pinoutsESPWROVER.PCLK_GPIO_NUM} ; Set the PCLK pin +build_flags = ${common.build_flags} + -DDEBUG_MODE=1 ; Set the debug mode + ; CAMERA PINOUT DEFINITIONS + -DPWDN_GPIO_NUM=${pinoutsESPWROVER.PWDN_GPIO_NUM} ; Set the PWDN pin + -DRESET_GPIO_NUM=${pinoutsESPWROVER.RESET_GPIO_NUM} ; Set the RESET pin + -DXCLK_GPIO_NUM=${pinoutsESPWROVER.XCLK_GPIO_NUM} ; Set the XCLK pin + -DSIOD_GPIO_NUM=${pinoutsESPWROVER.SIOD_GPIO_NUM} ; Set the SIOD pin + -DSIOC_GPIO_NUM=${pinoutsESPWROVER.SIOC_GPIO_NUM} ; Set the SIOC pin + -DY9_GPIO_NUM=${pinoutsESPWROVER.Y9_GPIO_NUM} ; Set the Y9 pin + -DY8_GPIO_NUM=${pinoutsESPWROVER.Y8_GPIO_NUM} ; Set the Y8 pin + -DY7_GPIO_NUM=${pinoutsESPWROVER.Y7_GPIO_NUM} ; Set the Y7 pin + -DY6_GPIO_NUM=${pinoutsESPWROVER.Y6_GPIO_NUM} ; Set the Y6 pin + -DY5_GPIO_NUM=${pinoutsESPWROVER.Y5_GPIO_NUM} ; Set the Y5 pin + -DY4_GPIO_NUM=${pinoutsESPWROVER.Y4_GPIO_NUM} ; Set the Y4 pin + -DY3_GPIO_NUM=${pinoutsESPWROVER.Y3_GPIO_NUM} ; Set the Y3 pin + -DY2_GPIO_NUM=${pinoutsESPWROVER.Y2_GPIO_NUM} ; Set the Y2 pin + -DVSYNC_GPIO_NUM=${pinoutsESPWROVER.VSYNC_GPIO_NUM} ; Set the VSYNC pin + -DHREF_GPIO_NUM=${pinoutsESPWROVER.HREF_GPIO_NUM} ; Set the HREF pin + -DPCLK_GPIO_NUM=${pinoutsESPWROVER.PCLK_GPIO_NUM} ; Set the PCLK pin [env:wrover_release] platform = ${common.platform} @@ -249,7 +243,7 @@ board_build.flash_mode = qio monitor_speed = ${common.monitor_speed} monitor_filters = ${common.monitor_filters} ;build_unflags = ${common.build_unflags} -board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} ; uncomment this to use the huge_app partition table, does not support OTA and only 1MB of SPIFFS lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} @@ -258,11 +252,9 @@ build_type = ${common.build_type} extra_scripts = ${common.extra_scripts} ;monitor_rts = ${common.monitor_rts} ;monitor_dtr = ${common.monitor_dtr} -build_flags = - ${common.build_flags} - -DDEBUG_MODE=0 ; Set the debug mode - -DCORE_DEBUG_LEVEL=1 - -DVERSION=${common.release_version} +build_flags = ${common.build_flags} + -DDEBUG_MODE=0 ; Set the debug mode + -DCORE_DEBUG_LEVEL=1 ; Experimental OTA Environment - do not select unless you know what you are doing [env:wrover_OTA] @@ -274,7 +266,7 @@ board_build.flash_mode = qio monitor_speed = ${common.monitor_speed} monitor_filters = ${common.monitor_filters} ;build_unflags = ${common.build_unflags} -board_build.partitions = ${common.board_build.partitions} +board_build.partitions = ${common.board_build.partitions} ; uncomment this to use the min_spiffs partition table, great for using OTA lib_ldf_mode = ${common.lib_ldf_mode} upload_speed = ${common.upload_speed} lib_deps = ${common.lib_deps} @@ -283,12 +275,10 @@ extra_scripts = ${common.extra_scripts} ;monitor_rts = ${common.monitor_rts} ;monitor_dtr = ${common.monitor_dtr} -build_flags = - ${common.build_flags} - -DDEBUG_MODE=0 ; Set the debug mode - -DCORE_DEBUG_LEVEL=1 - -DDEBUG_ESP_OTA - -DVERSION=${common.release_version} +build_flags = ${common.build_flags} + -DDEBUG_MODE=0 ; Set the debug mode + -DCORE_DEBUG_LEVEL=1 + -DDEBUG_ESP_OTA upload_port = 192.168.1.38 upload_protocol = espota upload_flags = diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 4b318e1..cbcdafe 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -1,22 +1,27 @@ #include -#include #include #include #include #include #include #include +//! TODO: Setup OTA enabled state to be controllable by API if enabled at compile time +#if ENABLE_OTA +#include +#endif // ENABLE_OTA #include #include -//#include // Serial Manager -#include +//#include +//#include // Serial Manager int STREAM_SERVER_PORT = 80; int CONTROL_SERVER_PORT = 81; ProjectConfig deviceConfig; +#if ENABLE_OTA OTA ota(&deviceConfig); +#endif // ENABLE_OTA LEDManager ledManager(33); CameraHandler cameraHandler(&deviceConfig); // SerialManager serialManager(&deviceConfig); @@ -27,6 +32,7 @@ StreamServer streamServer(STREAM_SERVER_PORT); void setup() { + Serial.begin(115200); Serial.setDebugOutput(DEBUG_MODE); Serial.println("\n"); @@ -85,12 +91,16 @@ void setup() break; } } +#if ENABLE_OTA ota.SetupOTA(); +#endif // ENABLE_OTA } void loop() { +#if ENABLE_OTA ota.HandleOTAUpdate(); +#endif // ENABLE_OTA ledManager.displayStatus(); // serialManager.handleSerial(); } \ No newline at end of file diff --git a/ESP/tools/autoversioning.py b/ESP/tools/autoversioning.py new file mode 100644 index 0000000..b6833e5 --- /dev/null +++ b/ESP/tools/autoversioning.py @@ -0,0 +1,14 @@ +FILENAME_BUILDNO = 'tools/versioning' +version = 'v0.1.' +build_no = 0 + +try: + with open(FILENAME_BUILDNO) as f: + build_no = int(f.readline()) + 1 +except: + build_no = 1 +with open(FILENAME_BUILDNO, 'w+') as f: + f.write(str(build_no)) + +#print("-DVERSION=\"%s\"" % version+str(build_no)) +print("-DVERSION={0}".format(version+str(build_no))) diff --git a/ESP/tools/versioning b/ESP/tools/versioning new file mode 100644 index 0000000..bf0d87a --- /dev/null +++ b/ESP/tools/versioning @@ -0,0 +1 @@ +4 \ No newline at end of file From 35d615e96c4316c47e394c4d8498578b8f8de020 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 10 Sep 2022 18:06:38 +0100 Subject: [PATCH 100/153] update - add support or Git tags in the firmware name --- ESP/tools/customname.py | 4 ++-- ESP/tools/git_rev.py | 6 +++--- ESP/tools/versioning | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ESP/tools/customname.py b/ESP/tools/customname.py index 9d465e7..73b7f8a 100644 --- a/ESP/tools/customname.py +++ b/ESP/tools/customname.py @@ -18,6 +18,6 @@ for x in my_flags.get("CPPDEFINES"): # strip quotes needed for shell escaping s = lambda x: x.replace('"', "") env.Replace( - PROGNAME="%s-%s-%s-%s-%s" % - (s(defines.get("PIO_SRC_NAM")), s(defines.get("VERSION")), str(env["BOARD"]), + PROGNAME="%s-%s-%s-%s-%s-%s" % + (s(defines.get("PIO_SRC_NAM")), s(defines.get("VERSION")), s(defines.get("PIO_SRC_TAG")), str(env["BOARD"]), s(defines.get("PIO_SRC_REV")), s(defines.get("PIO_SRC_BRH")))) diff --git a/ESP/tools/git_rev.py b/ESP/tools/git_rev.py index 90dc59a..bbdc837 100644 --- a/ESP/tools/git_rev.py +++ b/ESP/tools/git_rev.py @@ -7,8 +7,8 @@ project = project.split("/") project = project[len(project)-1] # Get 0.0.0 version from latest Git tag -# tagcmd = "git describe --tags --abbrev=0" -# version = subprocess.check_output(tagcmd, shell=True).decode().strip() +tagcmd = "git describe --tags --abbrev=0" +version = subprocess.check_output(tagcmd, shell=True).decode().strip() # Get latest commit short from Git revcmd = "git log --pretty=format:'%h' -n 1" @@ -20,6 +20,6 @@ branch = subprocess.check_output(branchcmd, shell=True).decode().strip() # Make all available for use in the macros print("-DPIO_SRC_NAM={0}".format(project)) -# print("-DPIO_SRC_TAG={0}".format(version)) +print("-DPIO_SRC_TAG={0}".format(version)) print("-DPIO_SRC_REV={0}".format(commit)) print("-DPIO_SRC_BRH={0}".format(branch)) \ No newline at end of file diff --git a/ESP/tools/versioning b/ESP/tools/versioning index bf0d87a..301160a 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -4 \ No newline at end of file +8 \ No newline at end of file From 9b965c224b70ea61d43dce771340f7338191b266 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 13 Sep 2022 17:13:29 +0100 Subject: [PATCH 101/153] update - Re-write bool cast for restartCamera method - Removed preferencesapi library - no longer needed --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 4 ++-- ESP/platformio.ini | 1 - ESP/tools/versioning | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index cf32259..98dbae3 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -465,8 +465,8 @@ void BaseAPI::setCameraVar(AsyncWebServerRequest *request) void BaseAPI::restartCamera(AsyncWebServerRequest *request) { - int mode = atoi(request->arg("mode").c_str()); - camera->resetCamera((bool)mode); + bool mode = (bool)atoi(request->arg("mode").c_str()); + camera->resetCamera(mode); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera had been restarted.\"}"); } diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 8d8b49c..4ee0cea 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -108,7 +108,6 @@ lib_deps = esp32-camera leftcoast/LC_baseTools@^1.5 ; geeksville/Micro-RTSP @ ^0.1.6 ; Micro-RTSP library for streaming video over RTSP - will be implemented soon - https://github.com/ZanzyTHEbar/EasyPreferencesLibrary.git https://github.com/me-no-dev/ESPAsyncWebServer.git https://github.com/me-no-dev/AsyncTCP.git https://github.com/bblanchon/ArduinoJson.git diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 301160a..3cacc0b 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -8 \ No newline at end of file +12 \ No newline at end of file From 3c1f3312e7f38ee92b0500358e5c76a136a235ff Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 13 Sep 2022 17:24:56 +0100 Subject: [PATCH 102/153] update - Fix potential bug in config read and write after 10 iterations through the for loop --- ESP/lib/src/data/config/project_config.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 0d38d6c..162819b 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -74,6 +74,11 @@ void ProjectConfig::wifiConfigSave() putString(ssid.c_str(), this->config.networks[i].ssid.c_str()); putString(password.c_str(), this->config.networks[i].password.c_str()); putInt(channel.c_str(), this->config.networks[i].channel); + + name = "name"; + ssid = "ssid"; + password = "pass"; + channel = "channel"; } /* AP Config */ @@ -145,6 +150,11 @@ void ProjectConfig::load() const std::string &temp_3 = getString(password.c_str()).c_str(); uint8_t temp_4 = getUInt(channel.c_str()); + name = "name"; + ssid = "ssid"; + password = "pass"; + channel = "channel"; + //! push_back creates a copy of the object, so we need to use emplace_back this->config.networks.emplace_back( temp_1, From 490b1ea6c2e68560f7e8bbc1237d3b9e2416f99a Mon Sep 17 00:00:00 2001 From: Lorow Date: Fri, 16 Sep 2022 22:20:47 +0200 Subject: [PATCH 103/153] Fix subject calling the base update() method instead of the derived one on notify --- ESP/lib/src/data/utilities/Observer.hpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/ESP/lib/src/data/utilities/Observer.hpp b/ESP/lib/src/data/utilities/Observer.hpp index a3a0c99..1d4c38a 100644 --- a/ESP/lib/src/data/utilities/Observer.hpp +++ b/ESP/lib/src/data/utilities/Observer.hpp @@ -17,7 +17,7 @@ namespace ObserverEvent class IObserver { public: - void update(ObserverEvent::Event event){}; + virtual void update(ObserverEvent::Event event) = 0; }; class ISubject @@ -38,12 +38,9 @@ public: void notify(ObserverEvent::Event event) { - std::set::iterator iterator = observers.begin(); - - while (iterator != observers.end()) + for (auto observer : this->observers) { - (*iterator)->update(event); - ++iterator; + observer->update(event); } } }; From 01f04fee86664eec77416e1337c86f935bbbefea Mon Sep 17 00:00:00 2001 From: Lorow Date: Mon, 19 Sep 2022 23:49:37 +0200 Subject: [PATCH 104/153] Refactor camera to that it's initialization is signal based, depending on config loading successfully --- ESP/lib/src/data/config/project_config.cpp | 1 + ESP/lib/src/io/camera/cameraHandler.cpp | 79 ++++++++++++++-------- ESP/lib/src/io/camera/cameraHandler.hpp | 8 ++- ESP/src/main.cpp | 2 - 4 files changed, 58 insertions(+), 32 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 162819b..d73d567 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -38,6 +38,7 @@ void ProjectConfig::initConfig() "", 1, }; + // TODO camera config is missing, add it } void ProjectConfig::save() diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index aa6d90d..8599bea 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -1,9 +1,7 @@ #include "cameraHandler.hpp" -bool CameraHandler::setupCamera() +void CameraHandler::setupCameraPinout() { - log_d("Setting up camera \r\n"); - config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.grab_mode = CAMERA_GRAB_LATEST; @@ -26,36 +24,29 @@ bool CameraHandler::setupCamera() config.xclk_freq_hz = 16500000; // 10000000 stable, // 16500000 optimal, // 20000000 max fps - config.pixel_format = PIXFORMAT_JPEG; +} +void CameraHandler::setupBasicResolution() +{ + config.pixel_format = PIXFORMAT_JPEG; + config.frame_size = FRAMESIZE_240X240; if (psramFound()) { - log_d("Found psram, setting the 240x240 image quality"); - config.frame_size = FRAMESIZE_240X240; + log_d("Found psram, setting the higher image quality"); + config.jpeg_quality = 7; // 0-63 lower number = higher quality, more latency and less fps 7 for most fps, 5 for best quality config.fb_count = 3; } else { - log_e("Did not find psram, setting svga quality"); - config.frame_size = FRAMESIZE_SVGA; + log_e("Did not find psram, setting lower image quality"); config.jpeg_quality = 1; config.fb_count = 1; } +} - esp_err_t err = esp_camera_init(&config); - - if (err != ESP_OK) - { - log_e("Camera initialization failed with error: 0x%x \r\n", err); - log_e("Camera most likely not seated properly in the socket. Please fix the camera and reboot the device.\r\n"); - //! TODO add led blinking here - return false; - } - - log_d("Successfully initialized the camera!"); - //! TODO add led blinking here - +void CameraHandler::setupCameraSensor() +{ camera_sensor = esp_camera_sensor_get(); // fixes corrupted jpegs, https://github.com/espressif/esp32-camera/issues/203 camera_sensor->set_reg(camera_sensor, 0xff, 0xff, 0x00); // banksel @@ -78,19 +69,50 @@ bool CameraHandler::setupCamera() camera_sensor->set_dcw(camera_sensor, 0); // 0 = disable , 1 = enable camera_sensor->set_colorbar(camera_sensor, 0); // 0 = disable , 1 = enable camera_sensor->set_special_effect(camera_sensor, 2); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 4 - Green Tint, 5 - Blue Tint, 6 - Sepia) +} - return true; +bool CameraHandler::setupCamera() +{ + this->setupCameraPinout(); + this->setupBasicResolution(); + esp_err_t hasCameraBeenInitialized = esp_camera_init(&config); + + if (hasCameraBeenInitialized != ESP_OK) + { + log_e("Camera initialization failed with error: 0x%x \r\n", hasCameraBeenInitialized); + log_e("Camera most likely not seated properly in the socket. Please fix the camera and reboot the device.\r\n"); + //! TODO add led blinking here + return false; + } + else + { + this->setupCameraSensor(); + return true; + } +} + +void CameraHandler::loadConfigData() +{ + ProjectConfig::CameraConfig_t *cameraConfig = configManager->getCameraConfig(); + this->setHFlip(cameraConfig->href); + this->setVFlip(cameraConfig->vflip); + this->setCameraResolution((framesize_t)cameraConfig->framesize); + camera_sensor->set_quality(camera_sensor, cameraConfig->quality); } void CameraHandler::update(ObserverEvent::Event event) { - if (event == ObserverEvent::cameraConfigUpdated) + switch (event) { - ProjectConfig::CameraConfig_t *cameraConfig = configManager->getCameraConfig(); - this->setHFlip(cameraConfig->href); - this->setVFlip(cameraConfig->vflip); - this->setCameraResolution((framesize_t)cameraConfig->framesize); - camera_sensor->set_quality(camera_sensor, cameraConfig->quality); + case ObserverEvent::Event::configLoaded: + this->setupCamera(); + this->loadConfigData(); + break; + case ObserverEvent::Event::cameraConfigUpdated: + this->loadConfigData(); + break; + default: + break; } } @@ -122,7 +144,6 @@ int CameraHandler::setHFlip(int direction) } //! either hardware(1) or software(0) -// TODO: Add to API void CameraHandler::resetCamera(bool type) { if (type) diff --git a/ESP/lib/src/io/camera/cameraHandler.hpp b/ESP/lib/src/io/camera/cameraHandler.hpp index 3f4de3f..02bc892 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -14,11 +14,17 @@ private: public: CameraHandler(ProjectConfig *configManager) : configManager(configManager) {} - bool setupCamera(); int setCameraResolution(framesize_t frameSize); int setVFlip(int direction); int setHFlip(int direction); int setVieWindow(int offsetX, int offsetY, int outputX, int outputY); void update(ObserverEvent::Event event); void resetCamera(bool type = 0); + +private: + void loadConfigData(); + bool setupCamera(); + void setupCameraPinout(); + void setupBasicResolution(); + void setupCameraSensor(); }; diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index cbcdafe..b8cbf94 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -45,12 +45,10 @@ void setup() deviceConfig.initConfig(); deviceConfig.load(); - cameraHandler.setupCamera(); wifiHandler._enable_adhoc = ENABLE_ADHOC; wifiHandler.setupWifi(); - mdnsHandler.startMDNS(); switch (wifiStateManager.getCurrentState()) { From 2b745a3d1dba30d8a0ec63ebcf6dc0cbee95c781 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 20 Sep 2022 10:24:40 +0100 Subject: [PATCH 105/153] update - return optimize the cameraHandler.cpp methods to remove needless if-else checking --- ESP/lib/src/io/camera/cameraHandler.cpp | 24 ++++++++++-------------- ESP/tools/versioning | 2 +- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index 8599bea..c193be2 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -30,19 +30,17 @@ void CameraHandler::setupBasicResolution() { config.pixel_format = PIXFORMAT_JPEG; config.frame_size = FRAMESIZE_240X240; - if (psramFound()) - { - log_d("Found psram, setting the higher image quality"); - - config.jpeg_quality = 7; // 0-63 lower number = higher quality, more latency and less fps 7 for most fps, 5 for best quality - config.fb_count = 3; - } - else + if (!psramFound()) { log_e("Did not find psram, setting lower image quality"); config.jpeg_quality = 1; config.fb_count = 1; + return; } + + log_d("Found psram, setting the higher image quality"); + config.jpeg_quality = 7; // 0-63 lower number = higher quality, more latency and less fps 7 for most fps, 5 for best quality + config.fb_count = 3; } void CameraHandler::setupCameraSensor() @@ -84,11 +82,9 @@ bool CameraHandler::setupCamera() //! TODO add led blinking here return false; } - else - { - this->setupCameraSensor(); - return true; - } + + this->setupCameraSensor(); + return true; } void CameraHandler::loadConfigData() @@ -150,7 +146,7 @@ void CameraHandler::resetCamera(bool type) { // power cycle the camera module (handy if camera stops responding) digitalWrite(PWDN_GPIO_NUM, HIGH); // turn power off to camera module - Network_Utilities::my_delay(0.3); // a for loop with a delay of 300ms + Network_Utilities::my_delay(0.3); // a for loop with a delay of 300ms digitalWrite(PWDN_GPIO_NUM, LOW); Network_Utilities::my_delay(0.3); setupCamera(); diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 3cacc0b..8fdd954 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -12 \ No newline at end of file +22 \ No newline at end of file From 94d5872e991e463c2f26f303d4f3c79ae9e2b3fc Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 20 Sep 2022 11:50:25 +0100 Subject: [PATCH 106/153] update - Added CameraConfig_t struct to the initStruct method - initialized with default values - Added brightness setting --- ESP/lib/src/data/config/project_config.cpp | 36 ++++++++++++++++++---- ESP/lib/src/data/config/project_config.hpp | 5 +-- ESP/lib/src/io/camera/cameraHandler.cpp | 1 + 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index d73d567..0a077b0 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -21,6 +21,12 @@ void ProjectConfig::initConfig() log_i("Config name: %s", _name.c_str()); log_i("Config loaded: %s", success ? "true" : "false"); + /* + * If the config is not loaded, + * we need to initialize the config with default data + ! Do not initialize the WiFiConfig_t struct here, + ! as it will create a blank network which breaks the WiFiManager + */ this->config.device = { _name, "12345678", @@ -37,8 +43,16 @@ void ProjectConfig::initConfig() "", "", 1, + false, + }; + + this->config.camera = { + .vflip = 0, + .href = 4, + .framesize = 0, + .quality = 7, + .brightness = 0, }; - // TODO camera config is missing, add it } void ProjectConfig::save() @@ -47,7 +61,8 @@ void ProjectConfig::save() deviceConfigSave(); cameraConfigSave(); wifiConfigSave(); - end(); + end(); // we call end() here to close the connection to the NVS partition, we only do this because we call ESP.restart() next. + ESP.restart(); } void ProjectConfig::wifiConfigSave() @@ -88,7 +103,6 @@ void ProjectConfig::wifiConfigSave() putUInt("apChannel", this->config.ap_network.channel); log_i("Project config saved and system is rebooting"); - ESP.restart(); } void ProjectConfig::deviceConfigSave() @@ -104,9 +118,10 @@ void ProjectConfig::cameraConfigSave() { /* Camera Config */ putInt("vflip", this->config.camera.vflip); - putInt("framesize", this->config.camera.framesize); putInt("href", this->config.camera.href); + putInt("framesize", this->config.camera.framesize); putInt("quality", this->config.camera.quality); + putInt("brightness", this->config.camera.brightness); } bool ProjectConfig::reset() @@ -170,6 +185,14 @@ void ProjectConfig::load() this->config.ap_network.password = getString("apPass", "12345678").c_str(); this->config.ap_network.channel = getUInt("apChannel", 1); + + /* Camera Config */ + this->config.camera.vflip = getInt("vflip", 0); + this->config.camera.href = getInt("href", 0); + this->config.camera.framesize = getInt("framesize", 4); + this->config.camera.quality = getInt("quality", 7); + this->config.camera.brightness = getInt("brightness", 0); + this->_already_loaded = true; this->notify(ObserverEvent::configLoaded); } @@ -190,13 +213,14 @@ void ProjectConfig::setDeviceConfig(const std::string &name, const std::string & this->notify(ObserverEvent::deviceConfigUpdated); } -void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, bool shouldNotify) +void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, uint8_t *brightness, bool shouldNotify) { log_d("Updating camera config"); this->config.camera.vflip = *vflip; - this->config.camera.framesize = *framesize; this->config.camera.href = *href; + this->config.camera.framesize = *framesize; this->config.camera.quality = *quality; + this->config.camera.brightness = *brightness; log_d("Updating Camera config"); if (shouldNotify) diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index e783a41..c71a251 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -38,9 +38,10 @@ public: struct CameraConfig_t { uint8_t vflip; - uint8_t framesize; uint8_t href; + uint8_t framesize; uint8_t quality; + uint8_t brightness; }; struct WiFiConfig_t @@ -84,7 +85,7 @@ public: AP_WiFiConfig_t *getAPWifiConfig() { return &this->config.ap_network; } void setDeviceConfig(const std::string &name, const std::string &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, uint8_t *brightness, bool shouldNotify); void setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify); void setAPWifiConfig(const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify); diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index c193be2..22c7dc5 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -94,6 +94,7 @@ void CameraHandler::loadConfigData() this->setVFlip(cameraConfig->vflip); this->setCameraResolution((framesize_t)cameraConfig->framesize); camera_sensor->set_quality(camera_sensor, cameraConfig->quality); + camera_sensor->set_brightness(camera_sensor, cameraConfig->brightness); } void CameraHandler::update(ObserverEvent::Event event) From f7f629240b64e54551e6b94f0b156e2c001a2786 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 20 Sep 2022 12:10:16 +0100 Subject: [PATCH 107/153] update - Add brightness to API --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 98dbae3..9896280 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -290,6 +290,7 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) uint8_t temp_camera_vflip = 0; uint8_t temp_camera_hflip = 0; uint8_t temp_camera_quality = 0; + uint8_t temp_camera_brightness = 0; int params = request->params(); for (int i = 0; i < params; i++) @@ -311,9 +312,13 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) { temp_camera_quality = (uint8_t)param->value().toInt(); } + else if (param->name() == "brightness") + { + temp_camera_brightness = (uint8_t)param->value().toInt(); + } } - projectConfig->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, true); + projectConfig->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, &temp_camera_brightness, true); projectConfig->cameraConfigSave(); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera Settings have been set.\"}"); From 4ad516eb776a057e962108a7332141c03f84046c Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 20 Sep 2022 12:12:59 +0100 Subject: [PATCH 108/153] update - Added a comment about the elseif chains --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 9896280..b62dfa3 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -293,6 +293,8 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) uint8_t temp_camera_brightness = 0; int params = request->params(); + //! Using the else if statements to ensure that the values do not need to be set in a specific order + //! This means the order of the URL params does not matter for (int i = 0; i < params; i++) { AsyncWebParameter *param = request->getParam(i); From 6f68b45704b67590803b2a45ecd3c256259e32c7 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 25 Sep 2022 10:49:38 +0100 Subject: [PATCH 109/153] Update - fix bug in my_delay function - edit LEDManager to handle blocking and non-blocking methods --- .../src/data/utilities/network_utilities.cpp | 4 +- ESP/lib/src/io/LEDManager/LEDManager.cpp | 62 ++++++++++++++----- ESP/lib/src/io/LEDManager/LEDManager.hpp | 4 +- ESP/tools/versioning | 2 +- 4 files changed, 53 insertions(+), 19 deletions(-) diff --git a/ESP/lib/src/data/utilities/network_utilities.cpp b/ESP/lib/src/data/utilities/network_utilities.cpp index 270ca66..aca862a 100644 --- a/ESP/lib/src/data/utilities/network_utilities.cpp +++ b/ESP/lib/src/data/utilities/network_utilities.cpp @@ -41,8 +41,8 @@ int Network_Utilities::getStrength(int points) // TODO: add to JSON doc void Network_Utilities::my_delay(volatile long delay_time) { - delay_time = delay_time * 1e6L; - for (volatile long count = delay_time; count > 0L; count--) + delay_time = delay_time * 1e6L; + for (volatile long count = delay_time; count > 0; count--) ; } diff --git a/ESP/lib/src/io/LEDManager/LEDManager.cpp b/ESP/lib/src/io/LEDManager/LEDManager.cpp index c3982ed..01e8aef 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.cpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.cpp @@ -8,32 +8,64 @@ void LEDManager::begin() { pinMode(_ledPin, OUTPUT); onOff(false); - - /* for (auto &led : _leds) - { - if (led > 0) - { - pinMode(led, OUTPUT); - } - } */ } -void LEDManager::onOff(bool state) const -{ - digitalWrite(_ledPin, state); -} - -void LEDManager::blink(unsigned long time) +/** + * @brief Control the LED timer + * @details This function must be called in the main loop + * + * @param time + */ +void LEDManager::handleLED(unsigned long time) { unsigned long currentMillis = millis(); if (currentMillis - _previousMillis >= time) { _previousMillis = currentMillis; _ledState = !_ledState; - onOff(_ledState); } } +/** + * @brief Turn the LED on or off + * + * @param state + */ +void LEDManager::onOff(bool state) const +{ + digitalWrite(_ledPin, state); +} + +/** + * @brief Blink the LED + * @details This function requires the handleLED function to be called in the main loop + */ +void LEDManager::blink() +{ + onOff(_ledState); +} + +/** + * @brief Blink the LED a number of times + * @details This function is blocking and does not require the handleLED function to be called in the main loop + * @param times + * @param delayTime + */ +void LEDManager::blink(int times, int delayTime) +{ + for (int i = 0; i < times; i++) + { + onOff(true); + delay(delayTime); + onOff(false); + delay(delayTime); + } +} + +/** + * @brief Display the status of the LED + * @details This function requires the handleLED function to be called in the main loop + */ void LEDManager::displayStatus() { } diff --git a/ESP/lib/src/io/LEDManager/LEDManager.hpp b/ESP/lib/src/io/LEDManager/LEDManager.hpp index 6501723..52c141e 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.hpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.hpp @@ -10,7 +10,9 @@ public: void begin(); void onOff(bool state) const; - void blink(unsigned long time); + void blink(); + void blink(int times, int delayTime); + void handleLED(unsigned long time); void displayStatus(); private: diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 8fdd954..cabf43b 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -22 \ No newline at end of file +24 \ No newline at end of file From 335abd1de85ede6bd17ff859a1cab42809344156 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 25 Sep 2022 11:54:57 +0100 Subject: [PATCH 110/153] update - Optimizing StateManager - Create LEDStates enum - Migrate entire project to StateManager --- .../src/data/StateManager/StateManager.cpp | 2 +- .../src/data/StateManager/StateManager.hpp | 161 ++++++++++-------- ESP/lib/src/io/LEDManager/LEDManager.cpp | 4 +- ESP/lib/src/io/camera/cameraHandler.cpp | 2 +- .../src/network/WifiHandler/wifiHandler.cpp | 4 +- ESP/lib/src/network/mDNS/MDNSManager.hpp | 4 +- ESP/tools/versioning | 2 +- 7 files changed, 100 insertions(+), 79 deletions(-) diff --git a/ESP/lib/src/data/StateManager/StateManager.cpp b/ESP/lib/src/data/StateManager/StateManager.cpp index ba17b52..ec64375 100644 --- a/ESP/lib/src/data/StateManager/StateManager.cpp +++ b/ESP/lib/src/data/StateManager/StateManager.cpp @@ -5,5 +5,5 @@ StateManager wifiStateManager; StateManager webServerStateManager; StateManager mdnsStateManager; StateManager cameraStateManager; -StateManager buttonStateManager; +StateManager ledStateManager; StateManager streamStateManager; \ No newline at end of file diff --git a/ESP/lib/src/data/StateManager/StateManager.hpp b/ESP/lib/src/data/StateManager/StateManager.hpp index e21128f..c99ddcb 100644 --- a/ESP/lib/src/data/StateManager/StateManager.hpp +++ b/ESP/lib/src/data/StateManager/StateManager.hpp @@ -6,75 +6,97 @@ * StateManager * All Project States are managed here */ -class ProgramStates +struct DeviceStates { -public: - struct DeviceStates + enum State_e { - enum State_e - { - Starting, - Started, - Stopping, - Stopped, - Error + Starting, + Started, + Stopping, + Stopped, + Error + }; - }; + enum LEDStates_e + { + _LEDOff, + _LEDOn, + _LEDBlink, + _SerialManager_Start, + _SerialManager_Stop, + _SerialManager_Error, + _WiFiState_None, + _WiFiState_Connecting, + _WiFiState_Connected, + _WiFiState_Disconnected, + _WiFiState_Disconnecting, + _WiFiState_ADHOC, + _WiFiState_Error, + _WebServerState_None, + _WebServerState_Starting, + _WebServerState_Started, + _WebServerState_Stopping, + _WebServerState_Stopped, + _WebServerState_Error, + _MDNSState_None, + _MDNSState_Starting, + _MDNSState_Started, + _MDNSState_Stopping, + _MDNSState_Stopped, + _MDNSState_Error, + _Camera_Success, + _Camera_Connected, + _Camera_Disconnected, + _Camera_Error, + _Stream_OFF, + _Stream_ON, + _Stream_Error, + }; - enum WiFiState_e - { - WiFiState_None, - WiFiState_Connecting, - WiFiState_Connected, - WiFiState_Disconnected, - WiFiState_Disconnecting, - WiFiState_ADHOC, - WiFiState_Error - }; + enum WiFiState_e + { + WiFiState_None, + WiFiState_Connecting, + WiFiState_Connected, + WiFiState_Disconnected, + WiFiState_Disconnecting, + WiFiState_ADHOC, + WiFiState_Error + }; - enum WebServerState_e - { - WebServerState_None, - WebServerState_Starting, - WebServerState_Started, - WebServerState_Stopping, - WebServerState_Stopped, - WebServerState_Error - }; + enum WebServerState_e + { + WebServerState_None, + WebServerState_Starting, + WebServerState_Started, + WebServerState_Stopping, + WebServerState_Stopped, + WebServerState_Error + }; - enum MDNSState_e - { - MDNSState_None, - MDNSState_Starting, - MDNSState_Started, - MDNSState_Stopping, - MDNSState_Stopped, - MDNSState_Error - }; + enum MDNSState_e + { + MDNSState_None, + MDNSState_Starting, + MDNSState_Started, + MDNSState_Stopping, + MDNSState_Stopped, + MDNSState_Error + }; - enum CameraState_e - { - Camera_Success, - Camera_Connected, - Camera_Disconnected, - Camera_Error - }; + enum CameraState_e + { + Camera_Success, + Camera_Connected, + Camera_Disconnected, + Camera_Error + }; - enum ButtonState_e - { - Buttons_OFF, - Buttons_ON, - Buttons_PLUS, - Buttons_MINUS, - Buttons_Error - }; - - enum StreamState_e - { - Stream_OFF, - Stream_ON, - Stream_Error - }; + enum StreamState_e + { + Stream_OFF, + Stream_ON, + Stream_Error }; }; @@ -108,21 +130,20 @@ private: T _current_state; }; -typedef ProgramStates::DeviceStates::State_e State_e; -typedef ProgramStates::DeviceStates::WiFiState_e WiFiState_e; -typedef ProgramStates::DeviceStates::WebServerState_e WebServerState_e; -typedef ProgramStates::DeviceStates::MDNSState_e MDNSState_e; -typedef ProgramStates::DeviceStates::CameraState_e CameraState_e; -typedef ProgramStates::DeviceStates::ButtonState_e ButtonState_e; -typedef ProgramStates::DeviceStates::StreamState_e StreamState_e; +typedef DeviceStates::State_e State_e; +typedef DeviceStates::WiFiState_e WiFiState_e; +typedef DeviceStates::WebServerState_e WebServerState_e; +typedef DeviceStates::MDNSState_e MDNSState_e; +typedef DeviceStates::CameraState_e CameraState_e; +typedef DeviceStates::LEDStates_e LEDStates_e; +typedef DeviceStates::StreamState_e StreamState_e; extern StateManager stateManager; extern StateManager wifiStateManager; extern StateManager webServerStateManager; extern StateManager mdnsStateManager; extern StateManager cameraStateManager; -extern StateManager buttonStateManager; +extern StateManager ledStateManager; extern StateManager streamStateManager; - #endif // STATEMANAGER_HPP \ No newline at end of file diff --git a/ESP/lib/src/io/LEDManager/LEDManager.cpp b/ESP/lib/src/io/LEDManager/LEDManager.cpp index 01e8aef..110b133 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.cpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.cpp @@ -48,8 +48,8 @@ void LEDManager::blink() /** * @brief Blink the LED a number of times * @details This function is blocking and does not require the handleLED function to be called in the main loop - * @param times - * @param delayTime + * @param times number of times to blink + * @param delayTime delay between each blink */ void LEDManager::blink(int times, int delayTime) { diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index 22c7dc5..b7bb2de 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -79,7 +79,7 @@ bool CameraHandler::setupCamera() { log_e("Camera initialization failed with error: 0x%x \r\n", hasCameraBeenInitialized); log_e("Camera most likely not seated properly in the socket. Please fix the camera and reboot the device.\r\n"); - //! TODO add led blinking here + //! TODO add led blinking trigger boolean here return false; } diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index f44f003..8d593bf 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -66,7 +66,7 @@ void WiFiHandler::setupWifi() while (WiFi.status() != WL_CONNECTED) { progress++; - stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting); + stateManager->setState(WiFiState_e::WiFiState_Connecting); currentMillis = millis(); Helpers::update_progress_bar(progress, 100); delay(301); @@ -154,7 +154,7 @@ void WiFiHandler::iniSTA() WiFi.begin(this->ssid.c_str(), this->password.c_str(), this->channel); while (WiFi.status() != WL_CONNECTED) { - stateManager->setState(ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting); + stateManager->setState(WiFiState_e::WiFiState_Connecting); currentMillis = millis(); Helpers::update_progress_bar(progress, 100); delay(301); diff --git a/ESP/lib/src/network/mDNS/MDNSManager.hpp b/ESP/lib/src/network/mDNS/MDNSManager.hpp index 25237f0..dc8a335 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.hpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.hpp @@ -8,11 +8,11 @@ class MDNSHandler : public IObserver { private: - StateManager *stateManager; + StateManager *stateManager; ProjectConfig *configManager; public: - MDNSHandler(StateManager *stateManager, ProjectConfig *configManager) : stateManager(stateManager), configManager(configManager) {} + MDNSHandler(StateManager *stateManager, ProjectConfig *configManager) : stateManager(stateManager), configManager(configManager) {} void startMDNS(); void update(ObserverEvent::Event event); }; \ No newline at end of file diff --git a/ESP/tools/versioning b/ESP/tools/versioning index cabf43b..1758ddd 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -24 \ No newline at end of file +32 \ No newline at end of file From 40ca34c382783cc7ee94450d57f60a83b1b77a48 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 25 Sep 2022 13:12:03 +0100 Subject: [PATCH 111/153] update - Add one new state to LEDStates enum - Added proper lookup-table based state mapping for led states - created a handleLED method to call in the loop --- .../src/data/StateManager/StateManager.hpp | 1 + ESP/lib/src/io/LEDManager/LEDManager.cpp | 96 +++++++++++++------ ESP/lib/src/io/LEDManager/LEDManager.hpp | 21 +++- ESP/src/main.cpp | 4 +- ESP/tools/versioning | 2 +- 5 files changed, 89 insertions(+), 35 deletions(-) diff --git a/ESP/lib/src/data/StateManager/StateManager.hpp b/ESP/lib/src/data/StateManager/StateManager.hpp index c99ddcb..09c8c57 100644 --- a/ESP/lib/src/data/StateManager/StateManager.hpp +++ b/ESP/lib/src/data/StateManager/StateManager.hpp @@ -22,6 +22,7 @@ struct DeviceStates _LEDOff, _LEDOn, _LEDBlink, + _LEDBlinkFast, _SerialManager_Start, _SerialManager_Stop, _SerialManager_Error, diff --git a/ESP/lib/src/io/LEDManager/LEDManager.cpp b/ESP/lib/src/io/LEDManager/LEDManager.cpp index 110b133..c7b0051 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.cpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.cpp @@ -1,6 +1,51 @@ #include "LEDManager.hpp" -LEDManager::LEDManager(byte pin) : _ledPin(pin), _previousMillis(0), _ledState(false) {} +/** + *! @brief This is declared as a static member of the class - therefor it must be initialized outside of the class. + ** @brief This is a map of the LEDStates and the BlinkPatterns. + ** @brief The LEDStates are the keys and the BlinkPatterns are the values. + ** @brief The BlinkPatterns are the number of times to blink and the delay between blinks. + */ +LEDManager::ledStateMap_t LEDManager::ledStateMap = { + {LEDStates_e::_LEDOff, {0, 0}}, + {LEDStates_e::_LEDOn, {0, 0}}, + {LEDStates_e::_LEDBlink, {1, 500}}, + {LEDStates_e::_LEDBlinkFast, {1, 250}}, + {LEDStates_e::_SerialManager_Start, {1, 500}}, + {LEDStates_e::_SerialManager_Stop, {1, 500}}, + {LEDStates_e::_SerialManager_Error, {1, 500}}, + {LEDStates_e::_WiFiState_None, {1, 500}}, + {LEDStates_e::_WiFiState_Connecting, {1, 500}}, + {LEDStates_e::_WiFiState_Connected, {1, 500}}, + {LEDStates_e::_WiFiState_Disconnected, {1, 500}}, + {LEDStates_e::_WiFiState_Disconnecting, {1, 500}}, + {LEDStates_e::_WiFiState_ADHOC, {1, 500}}, + {LEDStates_e::_WiFiState_Error, {1, 500}}, + {LEDStates_e::_WebServerState_None, {1, 500}}, + {LEDStates_e::_WebServerState_Starting, {1, 500}}, + {LEDStates_e::_WebServerState_Started, {1, 500}}, + {LEDStates_e::_WebServerState_Stopping, {1, 500}}, + {LEDStates_e::_WebServerState_Stopped, {1, 500}}, + {LEDStates_e::_WebServerState_Error, {1, 500}}, + {LEDStates_e::_MDNSState_None, {1, 500}}, + {LEDStates_e::_MDNSState_Starting, {1, 500}}, + {LEDStates_e::_MDNSState_Started, {1, 500}}, + {LEDStates_e::_MDNSState_Stopping, {1, 500}}, + {LEDStates_e::_MDNSState_Stopped, {1, 500}}, + {LEDStates_e::_MDNSState_Error, {1, 500}}, + {LEDStates_e::_Camera_Success, {1, 500}}, + {LEDStates_e::_Camera_Connected, {1, 500}}, + {LEDStates_e::_Camera_Disconnected, {1, 500}}, + {LEDStates_e::_Camera_Error, {1, 500}}, +}; + +//!TODO: Change the parameters for each LED state to be unique. + +LEDManager::LEDManager(byte pin, + StateManager *stateManager) : _ledPin(pin), + stateManager(stateManager), + _previousMillis(0), + _ledState(false) {} LEDManager::~LEDManager() {} @@ -11,40 +56,43 @@ void LEDManager::begin() } /** - * @brief Control the LED timer + * @brief Control the LED * @details This function must be called in the main loop - * - * @param time + * */ -void LEDManager::handleLED(unsigned long time) +void LEDManager::handleLED() { - unsigned long currentMillis = millis(); - if (currentMillis - _previousMillis >= time) + if (ledStateMap.find(stateManager->getCurrentState()) != ledStateMap.end()) { - _previousMillis = currentMillis; - _ledState = !_ledState; + blinkPatterns = ledStateMap[stateManager->getCurrentState()]; // Get the blink pattern for the current state + unsigned long currentMillis = millis(); // Get the current time + if (currentMillis - _previousMillis >= blinkPatterns.delayTime) // Check if the current time is greater than the previous time plus the delay time + { + _previousMillis = currentMillis; + for (int i = 0; i < blinkPatterns.times; i++) + { + _ledState = !_ledState; + onOff(_ledState); + } + } + stateManager->setState(LEDStates_e::_LEDOff); // Set the state to off + onOff(false); // Turn the LED off + return; } + + log_e("LED State not found"); } /** * @brief Turn the LED on or off - * - * @param state + * + * @param state */ void LEDManager::onOff(bool state) const { digitalWrite(_ledPin, state); } -/** - * @brief Blink the LED - * @details This function requires the handleLED function to be called in the main loop - */ -void LEDManager::blink() -{ - onOff(_ledState); -} - /** * @brief Blink the LED a number of times * @details This function is blocking and does not require the handleLED function to be called in the main loop @@ -61,11 +109,3 @@ void LEDManager::blink(int times, int delayTime) delay(delayTime); } } - -/** - * @brief Display the status of the LED - * @details This function requires the handleLED function to be called in the main loop - */ -void LEDManager::displayStatus() -{ -} diff --git a/ESP/lib/src/io/LEDManager/LEDManager.hpp b/ESP/lib/src/io/LEDManager/LEDManager.hpp index 52c141e..f2cae7b 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.hpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.hpp @@ -1,24 +1,37 @@ #ifndef LEDMANAGER_HPP #define LEDMANAGER_HPP #include +#include +#include class LEDManager { public: - LEDManager(byte pin); + LEDManager(byte pin, + StateManager *stateManager); virtual ~LEDManager(); void begin(); + void handleLED(); void onOff(bool state) const; - void blink(); void blink(int times, int delayTime); - void handleLED(unsigned long time); - void displayStatus(); private: byte _ledPin; + StateManager *stateManager; unsigned long _previousMillis; bool _ledState; + + struct BlinkPatterns + { + int times; + int delayTime; + }; + + BlinkPatterns blinkPatterns; + + typedef std::unordered_map ledStateMap_t; + static ledStateMap_t ledStateMap; }; #endif // LEDMANAGER_HPP \ No newline at end of file diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index b8cbf94..fb2d03f 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -22,7 +22,7 @@ ProjectConfig deviceConfig; #if ENABLE_OTA OTA ota(&deviceConfig); #endif // ENABLE_OTA -LEDManager ledManager(33); +LEDManager ledManager(33, &ledStateManager); CameraHandler cameraHandler(&deviceConfig); // SerialManager serialManager(&deviceConfig); WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); @@ -99,6 +99,6 @@ void loop() #if ENABLE_OTA ota.HandleOTAUpdate(); #endif // ENABLE_OTA - ledManager.displayStatus(); + ledManager.handleLED(); // serialManager.handleSerial(); } \ No newline at end of file diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 1758ddd..3e932fe 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -32 \ No newline at end of file +34 \ No newline at end of file From 803eea15c2fde74bb24945a9337475a7d00bc866 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 25 Sep 2022 13:25:48 +0100 Subject: [PATCH 112/153] update - update LEDManager blink method to use the ledStateMap - update handleLED method to turn the LED off on an incorrect state-match --- ESP/lib/src/io/LEDManager/LEDManager.cpp | 38 ++++++++++++++++-------- ESP/lib/src/io/LEDManager/LEDManager.hpp | 8 ++--- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/ESP/lib/src/io/LEDManager/LEDManager.cpp b/ESP/lib/src/io/LEDManager/LEDManager.cpp index c7b0051..1b2ee4b 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.cpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.cpp @@ -39,13 +39,11 @@ LEDManager::ledStateMap_t LEDManager::ledStateMap = { {LEDStates_e::_Camera_Error, {1, 500}}, }; -//!TODO: Change the parameters for each LED state to be unique. +//! TODO: Change the parameters for each LED state to be unique. -LEDManager::LEDManager(byte pin, - StateManager *stateManager) : _ledPin(pin), - stateManager(stateManager), - _previousMillis(0), - _ledState(false) {} +LEDManager::LEDManager(byte pin) : _ledPin(pin), + _previousMillis(0), + _ledState(false) {} LEDManager::~LEDManager() {} @@ -60,7 +58,7 @@ void LEDManager::begin() * @details This function must be called in the main loop * */ -void LEDManager::handleLED() +void LEDManager::handleLED(StateManager *stateManager) { if (ledStateMap.find(stateManager->getCurrentState()) != ledStateMap.end()) { @@ -81,6 +79,8 @@ void LEDManager::handleLED() } log_e("LED State not found"); + stateManager->setState(LEDStates_e::_LEDOff); // Set the state to off + onOff(false); } /** @@ -99,13 +99,25 @@ void LEDManager::onOff(bool state) const * @param times number of times to blink * @param delayTime delay between each blink */ -void LEDManager::blink(int times, int delayTime) +void LEDManager::blink(StateManager *stateManager) { - for (int i = 0; i < times; i++) + + if (ledStateMap.find(stateManager->getCurrentState()) != ledStateMap.end()) { - onOff(true); - delay(delayTime); - onOff(false); - delay(delayTime); + blinkPatterns = ledStateMap[stateManager->getCurrentState()]; // Get the blink pattern for the current state + for (int i = 0; i < blinkPatterns.times; i++) + { + onOff(true); + delay(blinkPatterns.delayTime); + onOff(false); + delay(blinkPatterns.delayTime); + } + stateManager->setState(LEDStates_e::_LEDOff); // Set the state to off + onOff(false); // Turn the LED off + return; } + + log_e("LED State not found"); + stateManager->setState(LEDStates_e::_LEDOff); // Set the state to off + onOff(false); } diff --git a/ESP/lib/src/io/LEDManager/LEDManager.hpp b/ESP/lib/src/io/LEDManager/LEDManager.hpp index f2cae7b..08497c5 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.hpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.hpp @@ -7,18 +7,16 @@ class LEDManager { public: - LEDManager(byte pin, - StateManager *stateManager); + LEDManager(byte pin); virtual ~LEDManager(); void begin(); - void handleLED(); + void handleLED(StateManager *stateManager); void onOff(bool state) const; - void blink(int times, int delayTime); + void blink(StateManager *stateManager); private: byte _ledPin; - StateManager *stateManager; unsigned long _previousMillis; bool _ledState; From e3de6584f18a6e90b098b75ea3e4fad27762f37c Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 25 Sep 2022 13:27:57 +0100 Subject: [PATCH 113/153] update - add the last remaining states to the map --- ESP/lib/src/io/LEDManager/LEDManager.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ESP/lib/src/io/LEDManager/LEDManager.cpp b/ESP/lib/src/io/LEDManager/LEDManager.cpp index 1b2ee4b..fff0d5f 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.cpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.cpp @@ -37,6 +37,9 @@ LEDManager::ledStateMap_t LEDManager::ledStateMap = { {LEDStates_e::_Camera_Connected, {1, 500}}, {LEDStates_e::_Camera_Disconnected, {1, 500}}, {LEDStates_e::_Camera_Error, {1, 500}}, + {LEDStates_e::_Stream_OFF, {1, 500}}, + {LEDStates_e::_Stream_ON, {1, 500}}, + {LEDStates_e::_Stream_Error, {1, 500}}, }; //! TODO: Change the parameters for each LED state to be unique. From 69d2666f200c707f72dabeff69d5dd72af924248 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 25 Sep 2022 13:38:03 +0100 Subject: [PATCH 114/153] Update - Added LED debugging to cameraHandler setup method --- ESP/lib/src/io/camera/cameraHandler.cpp | 9 +++++++-- ESP/lib/src/io/camera/cameraHandler.hpp | 4 +++- ESP/src/main.cpp | 6 +++--- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index b7bb2de..6fa3134 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -1,5 +1,9 @@ #include "cameraHandler.hpp" +CameraHandler::CameraHandler(ProjectConfig *configManager, + StateManager *stateManager) : configManager(configManager), + stateManager(stateManager) {} + void CameraHandler::setupCameraPinout() { config.ledc_channel = LEDC_CHANNEL_0; @@ -79,11 +83,12 @@ bool CameraHandler::setupCamera() { log_e("Camera initialization failed with error: 0x%x \r\n", hasCameraBeenInitialized); log_e("Camera most likely not seated properly in the socket. Please fix the camera and reboot the device.\r\n"); - //! TODO add led blinking trigger boolean here + stateManager->setState(LEDStates_e::_Camera_Error); return false; } - + this->setupCameraSensor(); + stateManager->setState(LEDStates_e::_Camera_Success); return true; } diff --git a/ESP/lib/src/io/camera/cameraHandler.hpp b/ESP/lib/src/io/camera/cameraHandler.hpp index 02bc892..ffd2d93 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -4,6 +4,7 @@ #include "data/utilities/Observer.hpp" #include "data/utilities/network_utilities.hpp" #include "data/config/project_config.hpp" +#include "data/StateManager/StateManager.hpp" class CameraHandler : public IObserver { @@ -11,9 +12,10 @@ private: sensor_t *camera_sensor; camera_config_t config; ProjectConfig *configManager; + StateManager *stateManager; public: - CameraHandler(ProjectConfig *configManager) : configManager(configManager) {} + CameraHandler(ProjectConfig *configManager, StateManager *stateManager); int setCameraResolution(framesize_t frameSize); int setVFlip(int direction); int setHFlip(int direction); diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index fb2d03f..6b15a82 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -22,8 +22,8 @@ ProjectConfig deviceConfig; #if ENABLE_OTA OTA ota(&deviceConfig); #endif // ENABLE_OTA -LEDManager ledManager(33, &ledStateManager); -CameraHandler cameraHandler(&deviceConfig); +LEDManager ledManager(33); +CameraHandler cameraHandler(&deviceConfig, &ledStateManager); // SerialManager serialManager(&deviceConfig); WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); APIServer apiServer(CONTROL_SERVER_PORT, &deviceConfig, &cameraHandler, &wifiStateManager, "/control"); @@ -99,6 +99,6 @@ void loop() #if ENABLE_OTA ota.HandleOTAUpdate(); #endif // ENABLE_OTA - ledManager.handleLED(); + ledManager.handleLED(&ledStateManager); // serialManager.handleSerial(); } \ No newline at end of file From 1c324fc0ac58f5a9201c57864d8b7ac3fcf09dea Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 25 Sep 2022 14:17:05 +0100 Subject: [PATCH 115/153] update - fix pattern struct assignment to be discrete per method --- ESP/lib/src/io/LEDManager/LEDManager.cpp | 4 ++-- ESP/lib/src/io/LEDManager/LEDManager.hpp | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/ESP/lib/src/io/LEDManager/LEDManager.cpp b/ESP/lib/src/io/LEDManager/LEDManager.cpp index fff0d5f..cbe6527 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.cpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.cpp @@ -65,7 +65,7 @@ void LEDManager::handleLED(StateManager *stateManager) { if (ledStateMap.find(stateManager->getCurrentState()) != ledStateMap.end()) { - blinkPatterns = ledStateMap[stateManager->getCurrentState()]; // Get the blink pattern for the current state + BlinkPatterns_t blinkPatterns = ledStateMap[stateManager->getCurrentState()]; // Get the blink pattern for the current state unsigned long currentMillis = millis(); // Get the current time if (currentMillis - _previousMillis >= blinkPatterns.delayTime) // Check if the current time is greater than the previous time plus the delay time { @@ -107,7 +107,7 @@ void LEDManager::blink(StateManager *stateManager) if (ledStateMap.find(stateManager->getCurrentState()) != ledStateMap.end()) { - blinkPatterns = ledStateMap[stateManager->getCurrentState()]; // Get the blink pattern for the current state + BlinkPatterns_t blinkPatterns = ledStateMap[stateManager->getCurrentState()]; // Get the blink pattern for the current state for (int i = 0; i < blinkPatterns.times; i++) { onOff(true); diff --git a/ESP/lib/src/io/LEDManager/LEDManager.hpp b/ESP/lib/src/io/LEDManager/LEDManager.hpp index 08497c5..2966f1a 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.hpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.hpp @@ -20,15 +20,13 @@ private: unsigned long _previousMillis; bool _ledState; - struct BlinkPatterns + struct BlinkPatterns_t { int times; int delayTime; }; - BlinkPatterns blinkPatterns; - - typedef std::unordered_map ledStateMap_t; + typedef std::unordered_map ledStateMap_t; static ledStateMap_t ledStateMap; }; From 86084ecd06eac44fa9eeda1ff9c9b4f00dc9e88b Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 26 Sep 2022 13:40:59 +0100 Subject: [PATCH 116/153] update - basic formatting --- ESP/lib/src/io/LEDManager/LEDManager.cpp | 4 ++-- ESP/tools/versioning | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ESP/lib/src/io/LEDManager/LEDManager.cpp b/ESP/lib/src/io/LEDManager/LEDManager.cpp index cbe6527..cbe7a75 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.cpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.cpp @@ -66,8 +66,8 @@ void LEDManager::handleLED(StateManager *stateManager) if (ledStateMap.find(stateManager->getCurrentState()) != ledStateMap.end()) { BlinkPatterns_t blinkPatterns = ledStateMap[stateManager->getCurrentState()]; // Get the blink pattern for the current state - unsigned long currentMillis = millis(); // Get the current time - if (currentMillis - _previousMillis >= blinkPatterns.delayTime) // Check if the current time is greater than the previous time plus the delay time + unsigned long currentMillis = millis(); // Get the current time + if (currentMillis - _previousMillis >= blinkPatterns.delayTime) // Check if the current time is greater than the previous time plus the delay time { _previousMillis = currentMillis; for (int i = 0; i < blinkPatterns.times; i++) diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 3e932fe..c24b6ae 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -34 \ No newline at end of file +38 \ No newline at end of file From ce8b27dee461d4bc21125e9e206f3eb9e07c7224 Mon Sep 17 00:00:00 2001 From: Lorow Date: Sun, 2 Oct 2022 18:49:05 +0200 Subject: [PATCH 117/153] Fix MDNS not starting properly and always having the same service name --- ESP/lib/src/network/mDNS/MDNSManager.cpp | 14 +++++++++----- ESP/src/main.cpp | 1 + ESP/tools/versioning | 2 +- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/ESP/lib/src/network/mDNS/MDNSManager.cpp b/ESP/lib/src/network/mDNS/MDNSManager.cpp index 319cdaa..1f9d61a 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.cpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.cpp @@ -3,14 +3,14 @@ void MDNSHandler::startMDNS() { ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig(); - - if (MDNS.begin(deviceConfig->name.c_str())) + // deviceConfig->name.c_str() + if (MDNS.begin("OpenIrisTracker")) { stateManager->setState(MDNSState_e::MDNSState_Starting); - MDNS.addService("openIrisTracker", "tcp", 80); + MDNS.addService(deviceConfig->name.c_str(), "tcp", 80); char port[20]; //! Add service needs leading _ on ESP32 implementation for some reason (according to the docs) - MDNS.addServiceTxt("_openIrisTracker", "_tcp", "_stream_port", (const char *)Helpers::itoa(80, port, 10)); //! convert int to const char* using a very efficient implemenation of itoa + MDNS.addServiceTxt(("_" + deviceConfig->name).c_str(), "_tcp", "_stream_port", (const char *)Helpers::itoa(80, port, 10)); //! convert int to const char* using a very efficient implemenation of itoa log_i("MDNS initialized!"); stateManager->setState(MDNSState_e::MDNSState_Started); } @@ -23,9 +23,13 @@ void MDNSHandler::startMDNS() void MDNSHandler::update(ObserverEvent::Event event) { - if (event == ObserverEvent::deviceConfigUpdated) + switch (event) { + case ObserverEvent::Event::deviceConfigUpdated: MDNS.end(); startMDNS(); + break; + default: + break; } } \ No newline at end of file diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 6b15a82..31f5455 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -76,6 +76,7 @@ void setup() log_d("[SETUP]: Starting Stream Server"); apiServer.begin(); log_d("[SETUP]: Starting API Server"); + mdnsHandler.startMDNS(); break; } case WiFiState_e::WiFiState_Connecting: diff --git a/ESP/tools/versioning b/ESP/tools/versioning index c24b6ae..0aeb548 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -38 \ No newline at end of file +74 \ No newline at end of file From adb7853c71ef495ef3d732fbb719d86b0fffce85 Mon Sep 17 00:00:00 2001 From: Lorow Date: Sun, 2 Oct 2022 21:32:45 +0200 Subject: [PATCH 118/153] Fix default values for camera config, fix brightness setting affecting brightness instead of acg_gain --- ESP/lib/src/data/config/project_config.cpp | 14 +++++++------- ESP/lib/src/io/camera/cameraHandler.cpp | 2 +- ESP/tools/versioning | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 0a077b0..a8c3efb 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -21,8 +21,8 @@ void ProjectConfig::initConfig() log_i("Config name: %s", _name.c_str()); log_i("Config loaded: %s", success ? "true" : "false"); - /* - * If the config is not loaded, + /* + * If the config is not loaded, * we need to initialize the config with default data ! Do not initialize the WiFiConfig_t struct here, ! as it will create a blank network which breaks the WiFiManager @@ -45,13 +45,13 @@ void ProjectConfig::initConfig() 1, false, }; - + this->config.camera = { .vflip = 0, - .href = 4, - .framesize = 0, + .href = 0, + .framesize = 4, .quality = 7, - .brightness = 0, + .brightness = 2, }; } @@ -191,7 +191,7 @@ void ProjectConfig::load() this->config.camera.href = getInt("href", 0); this->config.camera.framesize = getInt("framesize", 4); this->config.camera.quality = getInt("quality", 7); - this->config.camera.brightness = getInt("brightness", 0); + this->config.camera.brightness = getInt("brightness", 2); this->_already_loaded = true; this->notify(ObserverEvent::configLoaded); diff --git a/ESP/lib/src/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index 6fa3134..98b076d 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -99,7 +99,7 @@ void CameraHandler::loadConfigData() this->setVFlip(cameraConfig->vflip); this->setCameraResolution((framesize_t)cameraConfig->framesize); camera_sensor->set_quality(camera_sensor, cameraConfig->quality); - camera_sensor->set_brightness(camera_sensor, cameraConfig->brightness); + camera_sensor->set_agc_gain(camera_sensor, cameraConfig->brightness); } void CameraHandler::update(ObserverEvent::Event event) diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 0aeb548..c9c4108 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -74 \ No newline at end of file +114 \ No newline at end of file From 4baf7a89c46ca4bd56fca414c29028d79e14dedf Mon Sep 17 00:00:00 2001 From: lorow Date: Sun, 16 Oct 2022 20:07:23 +0200 Subject: [PATCH 119/153] Remove unused API methods, fix missing pinout issues, fix OTA not having a password set up correctly, fix missing default password in platformio file --- ESP/lib/src/network/OTA/OTA.cpp | 7 +- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 278 +++---------------- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 27 +- ESP/lib/src/network/api/webserverHandler.cpp | 4 +- ESP/platformio.ini | 38 ++- ESP/tools/versioning | 2 +- 6 files changed, 58 insertions(+), 298 deletions(-) diff --git a/ESP/lib/src/network/OTA/OTA.cpp b/ESP/lib/src/network/OTA/OTA.cpp index 7abd36d..7d92363 100644 --- a/ESP/lib/src/network/OTA/OTA.cpp +++ b/ESP/lib/src/network/OTA/OTA.cpp @@ -16,6 +16,7 @@ void OTA::SetupOTA() } ArduinoOTA.setPort(localConfig->OTAPort); + ArduinoOTA.setPassword(localConfig->OTAPassword.c_str()); ArduinoOTA .onStart([]() @@ -52,7 +53,7 @@ void OTA::SetupOTA() } }); log_i("Starting up basic OTA server"); - log_i("OTA will be live for 30s, after which it will be disabled until restart"); + log_i("OTA will be live for 5 minutes, after which it will be disabled until restart"); ArduinoOTA.begin(); _bootTimestamp = millis(); } @@ -61,9 +62,9 @@ void OTA::HandleOTAUpdate() { if (_isOtaEnabled) { - if (_bootTimestamp + 30000 < millis()) + if (_bootTimestamp + (60000 * 5) < millis()) { - // we're disabling ota after first 30sec so that nothing bad happens during runtime + // we're disabling ota after first 5 minutes so that nothing bad happens during runtime _isOtaEnabled = false; log_i("From now on, OTA is disabled"); return; diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index b62dfa3..fcaabbf 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -123,77 +123,39 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) } } -//! TODO: ADD JSON handlers for the POST requests -void BaseAPI::handleJson(AsyncWebServerRequest *request) +void BaseAPI::getJsonConfig(AsyncWebServerRequest *request) { - std::string type = request->pathArg(0).c_str(); - switch (_networkMethodsMap_enum[request->method()]) - { - case POST: - { - switch (json_TypesMap.at(type)) - { - case DATA: - { - break; - } - case SETTINGS: - { - break; - } - case CONFIG: - { - break; - } - default: - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } - break; - } - case GET: - { - switch (json_TypesMap.at(type)) - { - case DATA: - { - projectConfig->getDeviceConfig()->data_json = true; - Network_Utilities::my_delay(1); - std::string temp = projectConfig->getDeviceConfig()->data_json_string; - request->send(200, MIMETYPE_JSON, temp.c_str()); - temp = std::string(); - break; - } - case SETTINGS: - { - projectConfig->getDeviceConfig()->config_json = true; - Network_Utilities::my_delay(1); - std::string temp = projectConfig->getDeviceConfig()->config_json_string; - request->send(200, MIMETYPE_JSON, temp.c_str()); - temp = std::string(); - break; - } - case CONFIG: - { - projectConfig->getDeviceConfig()->settings_json = true; - Network_Utilities::my_delay(1); - std::string temp = projectConfig->getDeviceConfig()->settings_json_string; - request->send(200, MIMETYPE_JSON, temp.c_str()); - temp = std::string(); - break; - } - default: - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); +} - break; - } - default: - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } +void BaseAPI::setDeviceConfig(AsyncWebServerRequest *request){ + switch (_networkMethodsMap_enum[request->method()]){ + case GET: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + case POST: { + int params = request->params(); + + std::string device_name; + std::string ota_password; + int ota_port; + + for (int i = 0; i < params; i++){ + AsyncWebParameter *param = request->getParam(i); + if (param->name() == "device_name"){ + device_name = param->value().c_str(); + } + if (param->name() == "ota_port"){ + ota_port = atoi(param->value().c_str()); + } + if (param->name() == "ota_password"){ + ota_password = param->value().c_str(); + } + } + projectConfig->setDeviceConfig(device_name, ota_password, &ota_port, true); + } } } @@ -232,49 +194,6 @@ void BaseAPI::factoryReset(AsyncWebServerRequest *request) } } -/** - * @brief Remove a command handler from the API - * - * @param request - * @return \c void - */ -void BaseAPI::deleteRoute(AsyncWebServerRequest *request) -{ - log_i("Request: %s", request->url().c_str()); - int params = request->params(); - auto it_map = route_map.find(request->pathArg(0).c_str()); - log_i("Request: %s", request->pathArg(0).c_str()); - if (it_map != route_map.end()) - { - auto it = it_map->second.find(request->pathArg(1).c_str()); - if (it != it_map->second.end()) - { - switch (_networkMethodsMap_enum[request->method()]) - { - case DELETE: - { - route_map.erase(it_map->first); - request->send(200, MIMETYPE_JSON, "{\"msg\":\"OK - Command handler removed\"}"); - break; - } - default: - { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } - } - } - else - { - request->send(404); - } - } - else - { - request->send(404); - } -} - //********************************************************************************************* //! Camera Command Functions //********************************************************************************************* @@ -335,141 +254,6 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) } } -//! TODO: Optimize this!! -void BaseAPI::getCameraStatus(AsyncWebServerRequest *request) -{ - static char json_response[1024]; - - sensor_t *s = esp_camera_sensor_get(); - if (s == NULL) - { - request->send(501); - return; - } - char *p = json_response; - *p++ = '{'; - - p += sprintf(p, "\"framesize\":%u,", s->status.framesize); - p += sprintf(p, "\"quality\":%u,", s->status.quality); - p += sprintf(p, "\"brightness\":%d,", s->status.brightness); - p += sprintf(p, "\"contrast\":%d,", s->status.contrast); - p += sprintf(p, "\"saturation\":%d,", s->status.saturation); - p += sprintf(p, "\"sharpness\":%d,", s->status.sharpness); - p += sprintf(p, "\"special_effect\":%u,", s->status.special_effect); - p += sprintf(p, "\"wb_mode\":%u,", s->status.wb_mode); - p += sprintf(p, "\"awb\":%u,", s->status.awb); - p += sprintf(p, "\"awb_gain\":%u,", s->status.awb_gain); - p += sprintf(p, "\"aec\":%u,", s->status.aec); - p += sprintf(p, "\"aec2\":%u,", s->status.aec2); - p += sprintf(p, "\"denoise\":%u,", s->status.denoise); - p += sprintf(p, "\"ae_level\":%d,", s->status.ae_level); - p += sprintf(p, "\"aec_value\":%u,", s->status.aec_value); - p += sprintf(p, "\"agc\":%u,", s->status.agc); - p += sprintf(p, "\"agc_gain\":%u,", s->status.agc_gain); - p += sprintf(p, "\"gainceiling\":%u,", s->status.gainceiling); - p += sprintf(p, "\"bpc\":%u,", s->status.bpc); - p += sprintf(p, "\"wpc\":%u,", s->status.wpc); - p += sprintf(p, "\"raw_gma\":%u,", s->status.raw_gma); - p += sprintf(p, "\"lenc\":%u,", s->status.lenc); - p += sprintf(p, "\"hmirror\":%u,", s->status.hmirror); - p += sprintf(p, "\"vflip\":%u,", s->status.vflip); - p += sprintf(p, "\"dcw\":%u,", s->status.dcw); - p += sprintf(p, "\"colorbar\":%u", s->status.colorbar); - *p++ = '}'; - *p++ = 0; - - AsyncWebServerResponse *response = request->beginResponse(200, MIMETYPE_JSON, json_response); - response->addHeader("Access-Control-Allow-Origin", "*"); - request->send(response); -} - -//! TODO: Optimize this!! -//! Change this to a hashmap and a switch-case to remove the string comparisons and if statements -void BaseAPI::setCameraVar(AsyncWebServerRequest *request) -{ - if (!request->hasArg("var") || !request->hasArg("val")) - { - request->send(404); - return; - } - String var = request->arg("var"); - const char *variable = var.c_str(); - int val = atoi(request->arg("val").c_str()); - - sensor_t *s = esp_camera_sensor_get(); - if (s == NULL) - { - request->send(501); - return; - } - - int res = 0; - if (!strcmp(variable, "framesize")) - res = s->set_framesize(s, (framesize_t)val); - else if (!strcmp(variable, "quality")) - res = s->set_quality(s, val); - else if (!strcmp(variable, "contrast")) - res = s->set_contrast(s, val); - else if (!strcmp(variable, "brightness")) - res = s->set_brightness(s, val); - else if (!strcmp(variable, "saturation")) - res = s->set_saturation(s, val); - else if (!strcmp(variable, "sharpness")) - res = s->set_sharpness(s, val); - else if (!strcmp(variable, "gainceiling")) - res = s->set_gainceiling(s, (gainceiling_t)val); - else if (!strcmp(variable, "colorbar")) - res = s->set_colorbar(s, val); - else if (!strcmp(variable, "awb")) - res = s->set_whitebal(s, val); - else if (!strcmp(variable, "agc")) - res = s->set_gain_ctrl(s, val); - else if (!strcmp(variable, "aec")) - res = s->set_exposure_ctrl(s, val); - else if (!strcmp(variable, "hmirror")) - res = s->set_hmirror(s, val); - else if (!strcmp(variable, "vflip")) - res = s->set_vflip(s, val); - else if (!strcmp(variable, "awb_gain")) - res = s->set_awb_gain(s, val); - else if (!strcmp(variable, "agc_gain")) - res = s->set_agc_gain(s, val); - else if (!strcmp(variable, "aec_value")) - res = s->set_aec_value(s, val); - else if (!strcmp(variable, "aec2")) - res = s->set_aec2(s, val); - else if (!strcmp(variable, "denoise")) - res = s->set_denoise(s, val); - else if (!strcmp(variable, "dcw")) - res = s->set_dcw(s, val); - else if (!strcmp(variable, "bpc")) - res = s->set_bpc(s, val); - else if (!strcmp(variable, "wpc")) - res = s->set_wpc(s, val); - else if (!strcmp(variable, "raw_gma")) - res = s->set_raw_gma(s, val); - else if (!strcmp(variable, "lenc")) - res = s->set_lenc(s, val); - else if (!strcmp(variable, "special_effect")) - res = s->set_special_effect(s, val); - else if (!strcmp(variable, "wb_mode")) - res = s->set_wb_mode(s, val); - else if (!strcmp(variable, "ae_level")) - res = s->set_ae_level(s, val); - - else - { - log_e("unknown setting %s", var.c_str()); - request->send(404); - return; - } - log_d("Got setting %s with value %d. Res: %d", var.c_str(), val, res); - - AsyncWebServerResponse *response = request->beginResponse(200); - response->addHeader("Access-Control-Allow-Origin", "*"); - request->send(response); -} - void BaseAPI::restartCamera(AsyncWebServerRequest *request) { bool mode = (bool)atoi(request->arg("mode").c_str()); diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index 706f833..e6f4d96 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -33,27 +33,6 @@ class BaseAPI protected: std::string api_url; - enum JSON_TYPES - { - CONFIG, - SETTINGS, - DATA, - STATUS, - COMMANDS, - WIFI, - WIFIAP, - }; - - std::unordered_map json_TypesMap = { - {"config", CONFIG}, - {"settings", SETTINGS}, - {"data", DATA}, - {"status", STATUS}, - {"commands", COMMANDS}, - {"wifi", WIFI}, - {"wifiap", WIFIAP}, - }; - static const char *MIMETYPE_HTML; /* static const char *MIMETYPE_CSS; */ /* static const char *MIMETYPE_JS; */ @@ -65,14 +44,12 @@ protected: protected: /* Commands */ void setWiFi(AsyncWebServerRequest *request); - void handleJson(AsyncWebServerRequest *request); + void getJsonConfig(AsyncWebServerRequest *request); void factoryReset(AsyncWebServerRequest *request); + void setDeviceConfig(AsyncWebServerRequest *request); void rebootDevice(AsyncWebServerRequest *request); - void deleteRoute(AsyncWebServerRequest *request); /* Camera Handlers */ - void getCameraStatus(AsyncWebServerRequest *request); - void setCameraVar(AsyncWebServerRequest *request); void setCamera(AsyncWebServerRequest *request); void restartCamera(AsyncWebServerRequest *request); diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 788445d..9dea50f 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -35,9 +35,9 @@ void APIServer::setupServer() { routes.emplace("wifi", &APIServer::setWiFi); routes.emplace("resetConfig", &APIServer::factoryReset); + routes.emplace("setDevice", &APIServer::setDeviceConfig); routes.emplace("rebootDevice", &APIServer::rebootDevice); - routes.emplace("setJson", &APIServer::handleJson); - routes.emplace("deleteRoute", &APIServer::deleteRoute); + routes.emplace("getStoredConfig", &APIServer::getJsonConfig); // Camera Routes routes.emplace("setCamera", &APIServer::setCamera); routes.emplace("restartCamera", &APIServer::restartCamera); diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 4ee0cea..e07c133 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -19,7 +19,7 @@ password="" ; your wifi network password goes here channel=1 ; 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="12345678" OTAServerPort=3232 enableADHOC=0 ; 0 = disable, 1 = enable adhocChannel=1 ; channel to use for adhoc network @@ -100,6 +100,23 @@ build_flags = -DBOARD_HAS_PSRAM ; enable psram -DASYNCWEBSERVER_REGEX ; enable regex in asyncwebserver -mfix-esp32-psram-cache-issue ; fix for psram + ; CAMERA PINOUT DEFINITIONS + -DPWDN_GPIO_NUM=${pinoutsESPCAM.PWDN_GPIO_NUM} ; Set the PWDN pin + -DRESET_GPIO_NUM=${pinoutsESPCAM.RESET_GPIO_NUM} ; Set the RESET pin + -DXCLK_GPIO_NUM=${pinoutsESPCAM.XCLK_GPIO_NUM} ; Set the XCLK pin + -DSIOD_GPIO_NUM=${pinoutsESPCAM.SIOD_GPIO_NUM} ; Set the SIOD pin + -DSIOC_GPIO_NUM=${pinoutsESPCAM.SIOC_GPIO_NUM} ; Set the SIOC pin + -DY9_GPIO_NUM=${pinoutsESPCAM.Y9_GPIO_NUM} ; Set the Y9 pin + -DY8_GPIO_NUM=${pinoutsESPCAM.Y8_GPIO_NUM} ; Set the Y8 pin + -DY7_GPIO_NUM=${pinoutsESPCAM.Y7_GPIO_NUM} ; Set the Y7 pin + -DY6_GPIO_NUM=${pinoutsESPCAM.Y6_GPIO_NUM} ; Set the Y6 pin + -DY5_GPIO_NUM=${pinoutsESPCAM.Y5_GPIO_NUM} ; Set the Y5 pin + -DY4_GPIO_NUM=${pinoutsESPCAM.Y4_GPIO_NUM} ; Set the Y4 pin + -DY3_GPIO_NUM=${pinoutsESPCAM.Y3_GPIO_NUM} ; Set the Y3 pin + -DY2_GPIO_NUM=${pinoutsESPCAM.Y2_GPIO_NUM} ; Set the Y2 pin + -DVSYNC_GPIO_NUM=${pinoutsESPCAM.VSYNC_GPIO_NUM} ; Set the VSYNC pin + -DHREF_GPIO_NUM=${pinoutsESPCAM.HREF_GPIO_NUM} ; Set the HREF pin + -DPCLK_GPIO_NUM=${pinoutsESPCAM.PCLK_GPIO_NUM} ; Set the PCLK pin ;build_unflags = -Os ; disable optimization for size lib_ldf_mode = deep+ @@ -131,25 +148,6 @@ lib_deps = ${common.lib_deps} build_type = ${common.build_type} extra_scripts = ${common.extra_scripts} build_flags = ${common.build_flags} - - ; CAMERA PINOUT DEFINITIONS - -DPWDN_GPIO_NUM=${pinoutsESPCAM.PWDN_GPIO_NUM} ; Set the PWDN pin - -DRESET_GPIO_NUM=${pinoutsESPCAM.RESET_GPIO_NUM} ; Set the RESET pin - -DXCLK_GPIO_NUM=${pinoutsESPCAM.XCLK_GPIO_NUM} ; Set the XCLK pin - -DSIOD_GPIO_NUM=${pinoutsESPCAM.SIOD_GPIO_NUM} ; Set the SIOD pin - -DSIOC_GPIO_NUM=${pinoutsESPCAM.SIOC_GPIO_NUM} ; Set the SIOC pin - -DY9_GPIO_NUM=${pinoutsESPCAM.Y9_GPIO_NUM} ; Set the Y9 pin - -DY8_GPIO_NUM=${pinoutsESPCAM.Y8_GPIO_NUM} ; Set the Y8 pin - -DY7_GPIO_NUM=${pinoutsESPCAM.Y7_GPIO_NUM} ; Set the Y7 pin - -DY6_GPIO_NUM=${pinoutsESPCAM.Y6_GPIO_NUM} ; Set the Y6 pin - -DY5_GPIO_NUM=${pinoutsESPCAM.Y5_GPIO_NUM} ; Set the Y5 pin - -DY4_GPIO_NUM=${pinoutsESPCAM.Y4_GPIO_NUM} ; Set the Y4 pin - -DY3_GPIO_NUM=${pinoutsESPCAM.Y3_GPIO_NUM} ; Set the Y3 pin - -DY2_GPIO_NUM=${pinoutsESPCAM.Y2_GPIO_NUM} ; Set the Y2 pin - -DVSYNC_GPIO_NUM=${pinoutsESPCAM.VSYNC_GPIO_NUM} ; Set the VSYNC pin - -DHREF_GPIO_NUM=${pinoutsESPCAM.HREF_GPIO_NUM} ; Set the HREF pin - -DPCLK_GPIO_NUM=${pinoutsESPCAM.PCLK_GPIO_NUM} ; Set the PCLK pin - -DDEBUG_MODE=1 ; Set the debug mode [env:esp32Cam_release] diff --git a/ESP/tools/versioning b/ESP/tools/versioning index c9c4108..030d25b 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -114 \ No newline at end of file +248 \ No newline at end of file From b2d7abe9548a84638cfeb13384bc9d0eaac46030 Mon Sep 17 00:00:00 2001 From: lorow Date: Tue, 25 Oct 2022 00:25:58 +0200 Subject: [PATCH 120/153] Add basic toRepresentation serialization methods for config elements --- ESP/lib/src/data/config/project_config.cpp | 6 --- ESP/lib/src/data/config/project_config.hpp | 50 ++++++++++++++++++--- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 2 + ESP/tools/versioning | 2 +- 4 files changed, 47 insertions(+), 13 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index a8c3efb..56fcd4d 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -31,12 +31,6 @@ void ProjectConfig::initConfig() _name, "12345678", 3232, - false, - false, - false, - "", - "", - "", }; this->config.ap_network = { diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index c71a251..0a6fa39 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -27,12 +27,16 @@ public: std::string name; std::string OTAPassword; int OTAPort; - bool data_json; - bool config_json; - bool settings_json; - std::string data_json_string; - std::string config_json_string; - std::string settings_json_string; + + const char* toRepresentation() { + char *p = (char*)"device_config: {"; + p += sprintf(p, "\"name\":%s,", this->name); + p += sprintf(p, "\"OTAPassword\":%s,", this->OTAPassword); + p += sprintf(p, "\"OTAPort\":%u,", this->OTAPort); + p += sprintf(p, "},"); + *p++ = 0; + return p; + } }; struct CameraConfig_t @@ -42,6 +46,18 @@ public: uint8_t framesize; uint8_t quality; uint8_t brightness; + + const char* toRepresentation() { + char *p = (char*)"camera_config: {"; + p += sprintf(p, "\"vflip\":%u,", this->vflip); + p += sprintf(p, "\"href\":%u,", this->href); + p += sprintf(p, "\"framesize\":%d,", this->framesize); + p += sprintf(p, "\"quality\":%d,", this->quality); + p += sprintf(p, "\"brightness\":%d", this->brightness); + p += sprintf(p, "},"); + *p++ = 0; + return p; + } }; struct WiFiConfig_t @@ -61,6 +77,18 @@ public: std::string password; uint8_t channel; bool adhoc; + + const char* toRepresentation() { + char *p = (char*)"wifi_entry: {"; + p += sprintf(p, "\"name\":%s,", this->name); + p += sprintf(p, "\"ssid\":%s,", this->ssid); + p += sprintf(p, "\"password\":%s,", this->password); + p += sprintf(p, "\"channel\":%u,", this->channel); + p += sprintf(p, "\"adhoc\":%u", this->adhoc); + p += sprintf(p, "},"); + *p++ = 0; + return p; + } }; struct AP_WiFiConfig_t @@ -69,6 +97,16 @@ public: std::string password; uint8_t channel; bool adhoc; + const char* toRepresentation() { + char *p = (char*)"adhoc_network: {"; + p += sprintf(p, "\"ssid\":%s,", this->ssid); + p += sprintf(p, "\"password\":%s,", this->password); + p += sprintf(p, "\"channel\":%u,", this->channel); + p += sprintf(p, "\"adhoc\":%d", this->adhoc); + p += sprintf(p, "},"); + *p++ = 0; + return p; + } }; struct TrackerConfig_t diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index fcaabbf..4e91fed 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -125,6 +125,8 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) void BaseAPI::getJsonConfig(AsyncWebServerRequest *request) { + // go through the config and build the response uisng toRepresentation methods + // consider moving handling the data to fromRepresentation request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); } diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 030d25b..44dfb1d 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -248 \ No newline at end of file +264 \ No newline at end of file From 168993128efeab627e6043b35dce33de66cd02e1 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 1 Nov 2022 17:03:17 +0000 Subject: [PATCH 121/153] update - move the MDNSHandler constructor definition to cpp file This is cleaner and proper class structure - definitions never go header files unless it's a template --- ESP/lib/src/network/mDNS/MDNSManager.cpp | 6 +++++- ESP/lib/src/network/mDNS/MDNSManager.hpp | 3 ++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/network/mDNS/MDNSManager.cpp b/ESP/lib/src/network/mDNS/MDNSManager.cpp index 1f9d61a..ef01840 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.cpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.cpp @@ -1,10 +1,14 @@ #include "MDNSManager.hpp" +MDNSHandler::MDNSHandler(StateManager *stateManager, + ProjectConfig *configManager) : stateManager(stateManager), + configManager(configManager) {} + void MDNSHandler::startMDNS() { ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig(); // deviceConfig->name.c_str() - if (MDNS.begin("OpenIrisTracker")) + if (MDNS.begin("openiristracker")) // lowercase only - as this will be the url { stateManager->setState(MDNSState_e::MDNSState_Starting); MDNS.addService(deviceConfig->name.c_str(), "tcp", 80); diff --git a/ESP/lib/src/network/mDNS/MDNSManager.hpp b/ESP/lib/src/network/mDNS/MDNSManager.hpp index dc8a335..95f0cd8 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.hpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.hpp @@ -12,7 +12,8 @@ private: ProjectConfig *configManager; public: - MDNSHandler(StateManager *stateManager, ProjectConfig *configManager) : stateManager(stateManager), configManager(configManager) {} + MDNSHandler(StateManager *stateManager, + ProjectConfig *configManager); void startMDNS(); void update(ObserverEvent::Event event); }; \ No newline at end of file From ef1fa0314faf298b93b5f76e866db12059c62af7 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 1 Nov 2022 17:11:17 +0000 Subject: [PATCH 122/153] update - found bug in config manager - fixed bug --- ESP/lib/src/data/config/project_config.cpp | 2 +- ESP/tools/versioning | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 56fcd4d..023ca8e 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -134,7 +134,7 @@ void ProjectConfig::load() } /* Device Config */ - this->config.device.name = getString("deviceName", "openiris").c_str(); + this->config.device.name = getString("deviceName", "openiristracker").c_str(); this->config.device.OTAPassword = getString("OTAPassword", "12345678").c_str(); this->config.device.OTAPort = getInt("OTAPort", 3232); //! No need to load the JSON strings or bools, they are generated and used on the fly diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 44dfb1d..02225a5 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -264 \ No newline at end of file +268 \ No newline at end of file From 88f5cf29b76afed82902bb1aae71b9f4fc5fc724 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 1 Nov 2022 18:32:05 +0000 Subject: [PATCH 123/153] Major Update - fixed Hostname issue with ArduinoOTA and mDNS - fix flashing binary issue on Unix systems --- ESP/lib/src/network/OTA/OTA.cpp | 7 ++++--- ESP/lib/src/network/OTA/OTA.hpp | 8 ++++---- ESP/platformio.ini | 2 +- ESP/src/main.cpp | 2 +- ESP/tools/versioning | 2 +- 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/ESP/lib/src/network/OTA/OTA.cpp b/ESP/lib/src/network/OTA/OTA.cpp index 7d92363..a8ae3dc 100644 --- a/ESP/lib/src/network/OTA/OTA.cpp +++ b/ESP/lib/src/network/OTA/OTA.cpp @@ -1,6 +1,7 @@ #include "OTA.hpp" -OTA::OTA(ProjectConfig *_deviceConfig) : _deviceConfig(_deviceConfig) {} +OTA::OTA(ProjectConfig *_deviceConfig, const std::string &hostname) : _deviceConfig(_deviceConfig), + _hostname(std::move(hostname)) {} OTA::~OTA() {} @@ -16,7 +17,6 @@ void OTA::SetupOTA() } ArduinoOTA.setPort(localConfig->OTAPort); - ArduinoOTA.setPassword(localConfig->OTAPassword.c_str()); ArduinoOTA .onStart([]() @@ -53,7 +53,8 @@ void OTA::SetupOTA() } }); log_i("Starting up basic OTA server"); - log_i("OTA will be live for 5 minutes, after which it will be disabled until restart"); + log_i("OTA will be live for 30s, after which it will be disabled until restart"); + ArduinoOTA.setHostname(_hostname.c_str()); ArduinoOTA.begin(); _bootTimestamp = millis(); } diff --git a/ESP/lib/src/network/OTA/OTA.hpp b/ESP/lib/src/network/OTA/OTA.hpp index f4cdbbe..5f8445c 100644 --- a/ESP/lib/src/network/OTA/OTA.hpp +++ b/ESP/lib/src/network/OTA/OTA.hpp @@ -2,21 +2,21 @@ #define OTA_HPP #include #include -#include "data/Config/project_config.hpp" +#include "data/config/project_config.hpp" class OTA { public: - OTA(ProjectConfig *_deviceConfig); + OTA(ProjectConfig *_deviceConfig, + const std::string &hostname); virtual ~OTA(); - void SetupOTA(); - void HandleOTAUpdate(); private: unsigned long _bootTimestamp = 0; bool _isOtaEnabled = true; ProjectConfig *_deviceConfig; + std::string _hostname; }; #endif // OTA_HPP \ No newline at end of file diff --git a/ESP/platformio.ini b/ESP/platformio.ini index e07c133..28b4360 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -120,7 +120,7 @@ build_flags = ;build_unflags = -Os ; disable optimization for size lib_ldf_mode = deep+ -upload_speed = 921600 +upload_speed = 115200 ;115200 is used for compatability - if you are on windows and want the code to flash faster use 921600 lib_deps = esp32-camera leftcoast/LC_baseTools@^1.5 diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 31f5455..f9e2457 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -20,7 +20,7 @@ int CONTROL_SERVER_PORT = 81; ProjectConfig deviceConfig; #if ENABLE_OTA -OTA ota(&deviceConfig); +OTA ota(&deviceConfig, "openiristracker"); #endif // ENABLE_OTA LEDManager ledManager(33); CameraHandler cameraHandler(&deviceConfig, &ledStateManager); diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 02225a5..8bc94cb 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -268 \ No newline at end of file +276 \ No newline at end of file From 746a0a9f9bd01d31248f7e3177741a878955b93a Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 1 Nov 2022 20:24:50 +0000 Subject: [PATCH 124/153] Major Update - migrate toRepresentation methods out of header file - optimize toRepresentation methods - add helper for string formatting - put proper include guards in helper and MDNSManager - begin adding queryMDNS code --- ESP/lib/src/data/config/project_config.cpp | 403 +++++++++++---------- ESP/lib/src/data/config/project_config.hpp | 48 +-- ESP/lib/src/data/utilities/helpers.cpp | 2 +- ESP/lib/src/data/utilities/helpers.hpp | 27 +- ESP/lib/src/network/mDNS/MDNSManager.hpp | 6 +- ESP/lib/src/network/mDNS/queryMDNS.cpp | 0 ESP/lib/src/network/mDNS/queryMDNS.hpp | 23 ++ ESP/tools/versioning | 2 +- 8 files changed, 284 insertions(+), 227 deletions(-) create mode 100644 ESP/lib/src/network/mDNS/queryMDNS.cpp create mode 100644 ESP/lib/src/network/mDNS/queryMDNS.hpp diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 023ca8e..161fb1b 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -10,185 +10,184 @@ ProjectConfig::~ProjectConfig() {} */ void ProjectConfig::initConfig() { - if (_name.empty()) - { - log_e("Config name is null\n"); - _name = "openiris"; - } + if (_name.empty()) + { + log_e("Config name is null\n"); + _name = "openiris"; + } - bool success = begin(_name.c_str()); + bool success = begin(_name.c_str()); - log_i("Config name: %s", _name.c_str()); - log_i("Config loaded: %s", success ? "true" : "false"); + log_i("Config name: %s", _name.c_str()); + log_i("Config loaded: %s", success ? "true" : "false"); - /* - * If the config is not loaded, - * we need to initialize the config with default data - ! Do not initialize the WiFiConfig_t struct here, - ! as it will create a blank network which breaks the WiFiManager - */ - this->config.device = { - _name, - "12345678", - 3232, - }; + /* + * If the config is not loaded, + * we need to initialize the config with default data + ! Do not initialize the WiFiConfig_t struct here, + ! as it will create a blank network which breaks the WiFiManager + */ + this->config.device = { + _name, + "12345678", + 3232, + }; - this->config.ap_network = { - "", - "", - 1, - false, - }; + this->config.ap_network = { + "", + "", + 1, + false, + }; - this->config.camera = { - .vflip = 0, - .href = 0, - .framesize = 4, - .quality = 7, - .brightness = 2, - }; + this->config.camera = { + .vflip = 0, + .href = 0, + .framesize = 4, + .quality = 7, + .brightness = 2, + }; } void ProjectConfig::save() { - log_d("Saving project config"); - deviceConfigSave(); - cameraConfigSave(); - wifiConfigSave(); - end(); // we call end() here to close the connection to the NVS partition, we only do this because we call ESP.restart() next. - ESP.restart(); + log_d("Saving project config"); + deviceConfigSave(); + cameraConfigSave(); + wifiConfigSave(); + end(); // we call end() here to close the connection to the NVS partition, we only do this because we call ESP.restart() next. + ESP.restart(); } void ProjectConfig::wifiConfigSave() { - log_d("Saving wifi config"); + log_d("Saving wifi config"); - /* WiFi Config */ - putInt("networkCount", this->config.networks.size()); + /* WiFi Config */ + putInt("networkCount", this->config.networks.size()); - std::string name = "name"; - std::string ssid = "ssid"; - std::string password = "pass"; - std::string channel = "channel"; - for (int i = 0; i < this->config.networks.size(); i++) - { - char buffer[2]; - std::string iter_str = Helpers::itoa(i, buffer, 10); + std::string name = "name"; + std::string ssid = "ssid"; + std::string password = "pass"; + std::string channel = "channel"; + for (int i = 0; i < this->config.networks.size(); i++) + { + char buffer[2]; + std::string iter_str = Helpers::itoa(i, buffer, 10); - name.append(iter_str); - ssid.append(iter_str); - password.append(iter_str); - channel.append(iter_str); + name.append(iter_str); + ssid.append(iter_str); + password.append(iter_str); + channel.append(iter_str); - putString(name.c_str(), this->config.networks[i].name.c_str()); - putString(ssid.c_str(), this->config.networks[i].ssid.c_str()); - putString(password.c_str(), this->config.networks[i].password.c_str()); - putInt(channel.c_str(), this->config.networks[i].channel); + putString(name.c_str(), this->config.networks[i].name.c_str()); + putString(ssid.c_str(), this->config.networks[i].ssid.c_str()); + putString(password.c_str(), this->config.networks[i].password.c_str()); + putInt(channel.c_str(), this->config.networks[i].channel); - name = "name"; - ssid = "ssid"; - password = "pass"; - channel = "channel"; - } + name = "name"; + ssid = "ssid"; + password = "pass"; + channel = "channel"; + } - /* AP Config */ - putString("apSSID", this->config.ap_network.ssid.c_str()); - putString("apPass", this->config.ap_network.password.c_str()); - putUInt("apChannel", this->config.ap_network.channel); + /* AP Config */ + putString("apSSID", this->config.ap_network.ssid.c_str()); + putString("apPass", this->config.ap_network.password.c_str()); + putUInt("apChannel", this->config.ap_network.channel); - log_i("Project config saved and system is rebooting"); + log_i("Project config saved and system is rebooting"); } void ProjectConfig::deviceConfigSave() { - /* Device Config */ - putString("deviceName", this->config.device.name.c_str()); - putString("OTAPassword", this->config.device.OTAPassword.c_str()); - putInt("OTAPort", this->config.device.OTAPort); - //! No need to save the JSON strings or bools, they are generated and used on the fly + /* Device Config */ + putString("deviceName", this->config.device.name.c_str()); + putString("OTAPassword", this->config.device.OTAPassword.c_str()); + putInt("OTAPort", this->config.device.OTAPort); + //! No need to save the JSON strings or bools, they are generated and used on the fly } void ProjectConfig::cameraConfigSave() { - /* Camera Config */ - putInt("vflip", this->config.camera.vflip); - putInt("href", this->config.camera.href); - putInt("framesize", this->config.camera.framesize); - putInt("quality", this->config.camera.quality); - putInt("brightness", this->config.camera.brightness); + /* Camera Config */ + putInt("vflip", this->config.camera.vflip); + putInt("href", this->config.camera.href); + putInt("framesize", this->config.camera.framesize); + putInt("quality", this->config.camera.quality); + putInt("brightness", this->config.camera.brightness); } bool ProjectConfig::reset() { - log_w("Resetting project config"); - return clear(); + log_w("Resetting project config"); + return clear(); } void ProjectConfig::load() { - log_d("Loading project config"); - if (this->_already_loaded) - { - log_w("Project config already loaded"); - return; - } + log_d("Loading project config"); + if (this->_already_loaded) + { + log_w("Project config already loaded"); + return; + } - /* Device Config */ - this->config.device.name = getString("deviceName", "openiristracker").c_str(); - this->config.device.OTAPassword = getString("OTAPassword", "12345678").c_str(); - this->config.device.OTAPort = getInt("OTAPort", 3232); - //! No need to load the JSON strings or bools, they are generated and used on the fly + /* Device Config */ + this->config.device.name = getString("deviceName", "openiristracker").c_str(); + this->config.device.OTAPassword = getString("OTAPassword", "12345678").c_str(); + this->config.device.OTAPort = getInt("OTAPort", 3232); + //! No need to load the JSON strings or bools, they are generated and used on the fly - /* WiFi Config */ - int networkCount = getInt("networkCount", 0); - std::string name = "name"; - std::string ssid = "ssid"; - std::string password = "pass"; - std::string channel = "channel"; - for (int i = 0; i < networkCount; i++) - { - char buffer[2]; - std::string iter_str = Helpers::itoa(i, buffer, 10); + /* WiFi Config */ + int networkCount = getInt("networkCount", 0); + std::string name = "name"; + std::string ssid = "ssid"; + std::string password = "pass"; + std::string channel = "channel"; + for (int i = 0; i < networkCount; i++) + { + char buffer[2]; + std::string iter_str = Helpers::itoa(i, buffer, 10); - name.append(iter_str); - ssid.append(iter_str); - password.append(iter_str); - channel.append(iter_str); + name.append(iter_str); + ssid.append(iter_str); + password.append(iter_str); + channel.append(iter_str); - const std::string &temp_1 = getString(name.c_str()).c_str(); - const std::string &temp_2 = getString(ssid.c_str()).c_str(); - const std::string &temp_3 = getString(password.c_str()).c_str(); - uint8_t temp_4 = getUInt(channel.c_str()); + const std::string &temp_1 = getString(name.c_str()).c_str(); + const std::string &temp_2 = getString(ssid.c_str()).c_str(); + const std::string &temp_3 = getString(password.c_str()).c_str(); + uint8_t temp_4 = getUInt(channel.c_str()); - name = "name"; - ssid = "ssid"; - password = "pass"; - channel = "channel"; + name = "name"; + ssid = "ssid"; + password = "pass"; + channel = "channel"; - //! push_back creates a copy of the object, so we need to use emplace_back - this->config.networks.emplace_back( - temp_1, - temp_2, - temp_3, - temp_4, - false); // false because the networks we store in the config are the ones we want the esp to connect to, rather than host as AP - } + //! push_back creates a copy of the object, so we need to use emplace_back + this->config.networks.emplace_back( + temp_1, + temp_2, + temp_3, + temp_4, + false); // false because the networks we store in the config are the ones we want the esp to connect to, rather than host as AP + } - /* AP Config */ - this->config.ap_network.ssid = getString("apSSID", "openiris").c_str(); - this->config.ap_network.password = getString("apPass", "12345678").c_str(); - this->config.ap_network.channel = getUInt("apChannel", 1); + /* AP Config */ + this->config.ap_network.ssid = getString("apSSID", "openiris").c_str(); + this->config.ap_network.password = getString("apPass", "12345678").c_str(); + this->config.ap_network.channel = getUInt("apChannel", 1); + /* Camera Config */ + this->config.camera.vflip = getInt("vflip", 0); + this->config.camera.href = getInt("href", 0); + this->config.camera.framesize = getInt("framesize", 4); + this->config.camera.quality = getInt("quality", 7); + this->config.camera.brightness = getInt("brightness", 2); - /* Camera Config */ - this->config.camera.vflip = getInt("vflip", 0); - this->config.camera.href = getInt("href", 0); - this->config.camera.framesize = getInt("framesize", 4); - this->config.camera.quality = getInt("quality", 7); - this->config.camera.brightness = getInt("brightness", 2); - - this->_already_loaded = true; - this->notify(ObserverEvent::configLoaded); + this->_already_loaded = true; + this->notify(ObserverEvent::configLoaded); } //********************************************************************************************************************** @@ -198,79 +197,101 @@ void ProjectConfig::load() //********************************************************************************************************************** void ProjectConfig::setDeviceConfig(const std::string &name, const std::string &OTAPassword, int *OTAPort, bool shouldNotify) { - log_d("Updating device config"); - this->config.device.name.assign(name); - this->config.device.OTAPassword.assign(OTAPassword); - this->config.device.OTAPort = *OTAPort; + log_d("Updating device config"); + this->config.device.name.assign(name); + this->config.device.OTAPassword.assign(OTAPassword); + this->config.device.OTAPort = *OTAPort; - if (shouldNotify) - this->notify(ObserverEvent::deviceConfigUpdated); + if (shouldNotify) + this->notify(ObserverEvent::deviceConfigUpdated); } void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, uint8_t *brightness, bool shouldNotify) { - log_d("Updating camera config"); - this->config.camera.vflip = *vflip; - this->config.camera.href = *href; - this->config.camera.framesize = *framesize; - this->config.camera.quality = *quality; - this->config.camera.brightness = *brightness; + log_d("Updating camera config"); + this->config.camera.vflip = *vflip; + this->config.camera.href = *href; + this->config.camera.framesize = *framesize; + this->config.camera.quality = *quality; + this->config.camera.brightness = *brightness; - log_d("Updating Camera config"); - if (shouldNotify) - this->notify(ObserverEvent::cameraConfigUpdated); + log_d("Updating Camera config"); + if (shouldNotify) + this->notify(ObserverEvent::cameraConfigUpdated); } void ProjectConfig::setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify) { - WiFiConfig_t *networkToUpdate = nullptr; + WiFiConfig_t *networkToUpdate = nullptr; - // we store the ADHOC flag as false because the networks we store in the config are the ones we want the esp to connect to, rather than host as AP, and here we're just updating them - size_t size = this->config.networks.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - if (strcmp(this->config.networks[i].name.c_str(), networkName.c_str()) == 0) - networkToUpdate = &this->config.networks[i]; + // we store the ADHOC flag as false because the networks we store in the config are the ones we want the esp to connect to, rather than host as AP, and here we're just updating them + size_t size = this->config.networks.size(); + if (size > 0) + { + for (int i = 0; i < size; i++) + { + if (strcmp(this->config.networks[i].name.c_str(), networkName.c_str()) == 0) + networkToUpdate = &this->config.networks[i]; - //! push_back creates a copy of the object, so we need to use emplace_back - if (networkToUpdate != nullptr) - { - this->config.networks.emplace_back( - networkName, - ssid, - password, - *channel, - false); - } - log_d("Updating wifi config"); - } - } - else - { - //! push_back creates a copy of the object, so we need to use emplace_back - this->config.networks.emplace_back( - networkName, - ssid, - password, - *channel, - false); - networkToUpdate = &this->config.networks[0]; - } + //! push_back creates a copy of the object, so we need to use emplace_back + if (networkToUpdate != nullptr) + { + this->config.networks.emplace_back( + networkName, + ssid, + password, + *channel, + false); + } + log_d("Updating wifi config"); + } + } + else + { + //! push_back creates a copy of the object, so we need to use emplace_back + this->config.networks.emplace_back( + networkName, + ssid, + password, + *channel, + false); + networkToUpdate = &this->config.networks[0]; + } - if (shouldNotify) - this->notify(ObserverEvent::networksConfigUpdated); + if (shouldNotify) + this->notify(ObserverEvent::networksConfigUpdated); } void ProjectConfig::setAPWifiConfig(const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify) { - this->config.ap_network.ssid.assign(ssid); - this->config.ap_network.password.assign(password); - this->config.ap_network.channel = *channel; - this->config.ap_network.adhoc = adhoc; + this->config.ap_network.ssid.assign(ssid); + this->config.ap_network.password.assign(password); + this->config.ap_network.channel = *channel; + this->config.ap_network.adhoc = adhoc; - log_d("Updating access point config"); - if (shouldNotify) - this->notify(ObserverEvent::networksConfigUpdated); + log_d("Updating access point config"); + if (shouldNotify) + this->notify(ObserverEvent::networksConfigUpdated); +} + +std::string ProjectConfig::DeviceConfig_t::toRepresentation() +{ + std::string json = Helpers::format_string( + "device_config: {\"name\": \"%s\", \"OTAPassword\": \"%s\", \"OTAPort\": %u}", + this->name.c_str(), + this->OTAPassword.c_str(), + this->OTAPort); + + return json; +} + +std::string ProjectConfig::CameraConfig_t::toRepresentation() +{ + std::string json = Helpers::format_string("camera_config: {\"vflip\": %d,\"framesize\": %d,\"href\": %d,\"quality\": %d,\"brightness\": %d}", + this->vflip, + this->framesize, + this->href, + this->quality, + this->brightness); + return json; } \ No newline at end of file diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 0a6fa39..46d5dc9 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -28,15 +28,7 @@ public: std::string OTAPassword; int OTAPort; - const char* toRepresentation() { - char *p = (char*)"device_config: {"; - p += sprintf(p, "\"name\":%s,", this->name); - p += sprintf(p, "\"OTAPassword\":%s,", this->OTAPassword); - p += sprintf(p, "\"OTAPort\":%u,", this->OTAPort); - p += sprintf(p, "},"); - *p++ = 0; - return p; - } + std::string toRepresentation(); }; struct CameraConfig_t @@ -47,39 +39,30 @@ public: uint8_t quality; uint8_t brightness; - const char* toRepresentation() { - char *p = (char*)"camera_config: {"; - p += sprintf(p, "\"vflip\":%u,", this->vflip); - p += sprintf(p, "\"href\":%u,", this->href); - p += sprintf(p, "\"framesize\":%d,", this->framesize); - p += sprintf(p, "\"quality\":%d,", this->quality); - p += sprintf(p, "\"brightness\":%d", this->brightness); - p += sprintf(p, "},"); - *p++ = 0; - return p; - } + std::string toRepresentation(); }; struct WiFiConfig_t { //! Constructor for WiFiConfig_t - allows us to use emplace_back WiFiConfig_t(const std::string &name, - const std::string &ssid, - const std::string &password, - uint8_t channel, - bool adhoc) : name(std::move(name)), - ssid(std::move(ssid)), - password(std::move(password)), - channel(channel), - adhoc(adhoc) {} + const std::string &ssid, + const std::string &password, + uint8_t channel, + bool adhoc) : name(std::move(name)), + ssid(std::move(ssid)), + password(std::move(password)), + channel(channel), + adhoc(adhoc) {} std::string name; std::string ssid; std::string password; uint8_t channel; bool adhoc; - const char* toRepresentation() { - char *p = (char*)"wifi_entry: {"; + const char *toRepresentation() + { + char *p = (char *)"wifi_entry: {"; p += sprintf(p, "\"name\":%s,", this->name); p += sprintf(p, "\"ssid\":%s,", this->ssid); p += sprintf(p, "\"password\":%s,", this->password); @@ -97,8 +80,9 @@ public: std::string password; uint8_t channel; bool adhoc; - const char* toRepresentation() { - char *p = (char*)"adhoc_network: {"; + const char *toRepresentation() + { + char *p = (char *)"adhoc_network: {"; p += sprintf(p, "\"ssid\":%s,", this->ssid); p += sprintf(p, "\"password\":%s,", this->password); p += sprintf(p, "\"channel\":%u,", this->channel); diff --git a/ESP/lib/src/data/utilities/helpers.cpp b/ESP/lib/src/data/utilities/helpers.cpp index 0950cd2..52af448 100644 --- a/ESP/lib/src/data/utilities/helpers.cpp +++ b/ESP/lib/src/data/utilities/helpers.cpp @@ -96,4 +96,4 @@ void Helpers::update_progress_bar(int progress, int total) } std::cout << "] " << int(progress * 100.0 / total) << " %\r"; std::cout.flush(); -} +} \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/helpers.hpp b/ESP/lib/src/data/utilities/helpers.hpp index f9dc835..0f1d0a4 100644 --- a/ESP/lib/src/data/utilities/helpers.hpp +++ b/ESP/lib/src/data/utilities/helpers.hpp @@ -1,7 +1,10 @@ +#ifndef HELPERS_HPP +#define HELPERS_HPP #include #include #include #include +#include namespace Helpers { @@ -9,4 +12,26 @@ namespace Helpers void split(std::string str, std::string splitBy, std::vector &tokens); std::vector split(const std::string &s, char delimiter); void update_progress_bar(int progress, int total); -} \ No newline at end of file + + /// @brief + /// @tparam ...Args + /// @param format + /// @param ...args + /// @return + template + std::string format_string(const std::string &format, Args... args) + { + int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0' + if (size_s <= 0) + { + std::cout << "Error during formatting."; + return ""; + } + auto size = static_cast(size_s); + std::unique_ptr buf(new char[size]); + std::snprintf(buf.get(), size, format.c_str(), args...); + return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside + } +} + +#endif // HELPERS_HPP diff --git a/ESP/lib/src/network/mDNS/MDNSManager.hpp b/ESP/lib/src/network/mDNS/MDNSManager.hpp index 95f0cd8..a33be12 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.hpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.hpp @@ -1,4 +1,6 @@ #pragma once +#ifndef MDNSHANDLER_HPP +#define MDNSHANDLER_HPP #include #include "data/StateManager/StateManager.hpp" #include "data/utilities/Observer.hpp" @@ -16,4 +18,6 @@ public: ProjectConfig *configManager); void startMDNS(); void update(ObserverEvent::Event event); -}; \ No newline at end of file +}; + +#endif // MDNSHANDLER_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/mDNS/queryMDNS.cpp b/ESP/lib/src/network/mDNS/queryMDNS.cpp new file mode 100644 index 0000000..e69de29 diff --git a/ESP/lib/src/network/mDNS/queryMDNS.hpp b/ESP/lib/src/network/mDNS/queryMDNS.hpp new file mode 100644 index 0000000..db30cf7 --- /dev/null +++ b/ESP/lib/src/network/mDNS/queryMDNS.hpp @@ -0,0 +1,23 @@ +#pragma once +#ifndef QUERYMDNSSERVICE_HPP +#define QUERYMDNSSERVICE_HPP +#include +#include "data/StateManager/StateManager.hpp" +#include "data/utilities/Observer.hpp" +#include "data/utilities/helpers.hpp" +#include "data/config/project_config.hpp" + +class QueryMDNSService : public IObserver +{ +private: + StateManager *stateManager; + ProjectConfig *configManager; + +public: + QueryMDNSService(StateManager *stateManager, + ProjectConfig *configManager); + void queryMDNS(); + void update(ObserverEvent::Event event); +}; + +#endif // QUERYMDNSSERVICE_HPP \ No newline at end of file diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 8bc94cb..022e7e6 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -276 \ No newline at end of file +288 \ No newline at end of file From 326ec8e4cdcda9e4e82c9683a6f06e13c109fe5c Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Tue, 1 Nov 2022 22:12:16 +0000 Subject: [PATCH 125/153] Major Update - migrate the rest of the toRepresentation methods out of header file - optimize toRepresentation methods - add query service to set up service name and hostname --- .../src/data/StateManager/StateManager.hpp | 4 +- ESP/lib/src/data/config/project_config.cpp | 88 +++++++++++++++---- ESP/lib/src/data/config/project_config.hpp | 46 ++++------ ESP/lib/src/data/utilities/Observer.hpp | 1 + ESP/lib/src/network/OTA/OTA.cpp | 6 +- ESP/lib/src/network/OTA/OTA.hpp | 4 +- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 63 +++++++------ ESP/lib/src/network/mDNS/MDNSManager.cpp | 11 ++- ESP/lib/src/network/mDNS/queryMDNS.cpp | 65 ++++++++++++++ ESP/lib/src/network/mDNS/queryMDNS.hpp | 5 +- ESP/src/main.cpp | 17 +++- ESP/tools/versioning | 2 +- 12 files changed, 223 insertions(+), 89 deletions(-) diff --git a/ESP/lib/src/data/StateManager/StateManager.hpp b/ESP/lib/src/data/StateManager/StateManager.hpp index 09c8c57..039563e 100644 --- a/ESP/lib/src/data/StateManager/StateManager.hpp +++ b/ESP/lib/src/data/StateManager/StateManager.hpp @@ -82,7 +82,9 @@ struct DeviceStates MDNSState_Started, MDNSState_Stopping, MDNSState_Stopped, - MDNSState_Error + MDNSState_Error, + MDNSState_QueryStarted, + MDNSState_QueryComplete }; enum CameraState_e diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 161fb1b..36be6c3 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -28,11 +28,15 @@ void ProjectConfig::initConfig() ! as it will create a blank network which breaks the WiFiManager */ this->config.device = { - _name, "12345678", 3232, }; + this->config.mdns = { + "openiristracker", + "", + }; + this->config.ap_network = { "", "", @@ -53,6 +57,7 @@ void ProjectConfig::save() { log_d("Saving project config"); deviceConfigSave(); + mdnsConfigSave(); cameraConfigSave(); wifiConfigSave(); end(); // we call end() here to close the connection to the NVS partition, we only do this because we call ESP.restart() next. @@ -102,10 +107,15 @@ void ProjectConfig::wifiConfigSave() void ProjectConfig::deviceConfigSave() { /* Device Config */ - putString("deviceName", this->config.device.name.c_str()); putString("OTAPassword", this->config.device.OTAPassword.c_str()); putInt("OTAPort", this->config.device.OTAPort); - //! No need to save the JSON strings or bools, they are generated and used on the fly +} + +void ProjectConfig::mdnsConfigSave() +{ + /* Device Config */ + putString("hostname", this->config.mdns.hostname.c_str()); + putString("service", this->config.mdns.service.c_str()); } void ProjectConfig::cameraConfigSave() @@ -134,11 +144,12 @@ void ProjectConfig::load() } /* Device Config */ - this->config.device.name = getString("deviceName", "openiristracker").c_str(); this->config.device.OTAPassword = getString("OTAPassword", "12345678").c_str(); this->config.device.OTAPort = getInt("OTAPort", 3232); - //! No need to load the JSON strings or bools, they are generated and used on the fly + /* MDNS Config */ + this->config.mdns.hostname = getString("hostname").c_str(); + this->config.mdns.service = getString("service").c_str(); /* WiFi Config */ int networkCount = getInt("networkCount", 0); std::string name = "name"; @@ -195,10 +206,9 @@ void ProjectConfig::load() //! DeviceConfig //* //********************************************************************************************************************** -void ProjectConfig::setDeviceConfig(const std::string &name, const std::string &OTAPassword, int *OTAPort, bool shouldNotify) +void ProjectConfig::setDeviceConfig(const std::string &OTAPassword, int *OTAPort, bool shouldNotify) { log_d("Updating device config"); - this->config.device.name.assign(name); this->config.device.OTAPassword.assign(OTAPassword); this->config.device.OTAPort = *OTAPort; @@ -206,6 +216,16 @@ void ProjectConfig::setDeviceConfig(const std::string &name, const std::string & this->notify(ObserverEvent::deviceConfigUpdated); } +void ProjectConfig::setMDNSConfig(const std::string &hostname, const std::string &service, bool shouldNotify) +{ + log_d("Updating MDNS config"); + this->config.mdns.hostname.assign(hostname); + this->config.mdns.service.assign(service); + + if (shouldNotify) + this->notify(ObserverEvent::mdnsConfigUpdated); +} + void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, uint8_t *brightness, bool shouldNotify) { log_d("Updating camera config"); @@ -277,21 +297,55 @@ void ProjectConfig::setAPWifiConfig(const std::string &ssid, const std::string & std::string ProjectConfig::DeviceConfig_t::toRepresentation() { std::string json = Helpers::format_string( - "device_config: {\"name\": \"%s\", \"OTAPassword\": \"%s\", \"OTAPort\": %u}", - this->name.c_str(), + "device_config: {\"OTAPassword\": \"%s\", \"OTAPort\": %u}", this->OTAPassword.c_str(), this->OTAPort); - return json; } std::string ProjectConfig::CameraConfig_t::toRepresentation() { - std::string json = Helpers::format_string("camera_config: {\"vflip\": %d,\"framesize\": %d,\"href\": %d,\"quality\": %d,\"brightness\": %d}", - this->vflip, - this->framesize, - this->href, - this->quality, - this->brightness); + std::string json = Helpers::format_string( + "camera_config: {\"vflip\": %d,\"framesize\": %d,\"href\": %d,\"quality\": %d,\"brightness\": %d}", + this->vflip, + this->framesize, + this->href, + this->quality, + this->brightness); return json; -} \ No newline at end of file +} + +std::string ProjectConfig::WiFiConfig_t::toRepresentation() +{ + std::string json = Helpers::format_string( + "wifi_config: {\"name\": \"%s\", \"ssid\": \"%s\", \"password\": \"%s\", \"channel\": %u, \"adhoc\": %s}", + this->name.c_str(), + this->ssid.c_str(), + this->password.c_str(), + this->channel, + this->adhoc ? "true" : "false"); + return json; +} + +std::string ProjectConfig::AP_WiFiConfig_t::toRepresentation() +{ + std::string json = Helpers::format_string( + "ap_wifi_config: {\"ssid\": \"%s\", \"password\": \"%s\", \"channel\": %u, \"adhoc\": %s}", + this->ssid.c_str(), + this->password.c_str(), + this->channel, + this->adhoc ? "true" : "false"); + return json; +} + +//********************************************************************************************************************** +//* +//! Get Methods +//* +//********************************************************************************************************************** + +ProjectConfig::DeviceConfig_t *ProjectConfig::getDeviceConfig() { return &this->config.device; } +ProjectConfig::CameraConfig_t *ProjectConfig::getCameraConfig() { return &this->config.camera; } +std::vector *ProjectConfig::getWifiConfigs() { return &this->config.networks; } +ProjectConfig::AP_WiFiConfig_t *ProjectConfig::getAPWifiConfig() { return &this->config.ap_network; } +ProjectConfig::MDNSConfig_t *ProjectConfig::getMDNSConfig() { return &this->config.mdns; } \ No newline at end of file diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 46d5dc9..667fdd0 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -19,15 +19,21 @@ public: void wifiConfigSave(); void cameraConfigSave(); void deviceConfigSave(); + void mdnsConfigSave(); bool reset(); void initConfig(); struct DeviceConfig_t { - std::string name; std::string OTAPassword; int OTAPort; + std::string toRepresentation(); + }; + struct MDNSConfig_t + { + std::string hostname; + std::string service; std::string toRepresentation(); }; @@ -60,18 +66,7 @@ public: uint8_t channel; bool adhoc; - const char *toRepresentation() - { - char *p = (char *)"wifi_entry: {"; - p += sprintf(p, "\"name\":%s,", this->name); - p += sprintf(p, "\"ssid\":%s,", this->ssid); - p += sprintf(p, "\"password\":%s,", this->password); - p += sprintf(p, "\"channel\":%u,", this->channel); - p += sprintf(p, "\"adhoc\":%u", this->adhoc); - p += sprintf(p, "},"); - *p++ = 0; - return p; - } + std::string toRepresentation(); }; struct AP_WiFiConfig_t @@ -80,17 +75,7 @@ public: std::string password; uint8_t channel; bool adhoc; - const char *toRepresentation() - { - char *p = (char *)"adhoc_network: {"; - p += sprintf(p, "\"ssid\":%s,", this->ssid); - p += sprintf(p, "\"password\":%s,", this->password); - p += sprintf(p, "\"channel\":%u,", this->channel); - p += sprintf(p, "\"adhoc\":%d", this->adhoc); - p += sprintf(p, "},"); - *p++ = 0; - return p; - } + std::string toRepresentation(); }; struct TrackerConfig_t @@ -99,14 +84,17 @@ public: CameraConfig_t camera; std::vector networks; AP_WiFiConfig_t ap_network; + MDNSConfig_t mdns; }; - DeviceConfig_t *getDeviceConfig() { return &this->config.device; } - CameraConfig_t *getCameraConfig() { return &this->config.camera; } - std::vector *getWifiConfigs() { return &this->config.networks; } - AP_WiFiConfig_t *getAPWifiConfig() { return &this->config.ap_network; } + DeviceConfig_t *getDeviceConfig(); + CameraConfig_t *getCameraConfig(); + std::vector *getWifiConfigs(); + AP_WiFiConfig_t *getAPWifiConfig(); + MDNSConfig_t *getMDNSConfig(); - void setDeviceConfig(const std::string &name, const std::string &OTAPassword, int *OTAPort, bool shouldNotify); + void setDeviceConfig(const std::string &OTAPassword, int *OTAPort, bool shouldNotify); + void setMDNSConfig(const std::string &hostname, const std::string &service, bool shouldNotify); void setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, uint8_t *brightness, bool shouldNotify); void setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify); void setAPWifiConfig(const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify); diff --git a/ESP/lib/src/data/utilities/Observer.hpp b/ESP/lib/src/data/utilities/Observer.hpp index 1d4c38a..2be42ea 100644 --- a/ESP/lib/src/data/utilities/Observer.hpp +++ b/ESP/lib/src/data/utilities/Observer.hpp @@ -11,6 +11,7 @@ namespace ObserverEvent deviceConfigUpdated = 2, cameraConfigUpdated = 3, networksConfigUpdated = 4, + mdnsConfigUpdated = 5, }; } diff --git a/ESP/lib/src/network/OTA/OTA.cpp b/ESP/lib/src/network/OTA/OTA.cpp index a8ae3dc..9f18de7 100644 --- a/ESP/lib/src/network/OTA/OTA.cpp +++ b/ESP/lib/src/network/OTA/OTA.cpp @@ -1,7 +1,6 @@ #include "OTA.hpp" -OTA::OTA(ProjectConfig *_deviceConfig, const std::string &hostname) : _deviceConfig(_deviceConfig), - _hostname(std::move(hostname)) {} +OTA::OTA(ProjectConfig *_deviceConfig) : _deviceConfig(_deviceConfig) {} OTA::~OTA() {} @@ -54,7 +53,8 @@ void OTA::SetupOTA() log_i("Starting up basic OTA server"); log_i("OTA will be live for 30s, after which it will be disabled until restart"); - ArduinoOTA.setHostname(_hostname.c_str()); + auto mdnsConfig = _deviceConfig->getMDNSConfig(); + ArduinoOTA.setHostname(mdnsConfig->hostname.c_str()); ArduinoOTA.begin(); _bootTimestamp = millis(); } diff --git a/ESP/lib/src/network/OTA/OTA.hpp b/ESP/lib/src/network/OTA/OTA.hpp index 5f8445c..0a60e7d 100644 --- a/ESP/lib/src/network/OTA/OTA.hpp +++ b/ESP/lib/src/network/OTA/OTA.hpp @@ -7,8 +7,7 @@ class OTA { public: - OTA(ProjectConfig *_deviceConfig, - const std::string &hostname); + OTA(ProjectConfig *_deviceConfig); virtual ~OTA(); void SetupOTA(); void HandleOTAUpdate(); @@ -17,6 +16,5 @@ private: unsigned long _bootTimestamp = 0; bool _isOtaEnabled = true; ProjectConfig *_deviceConfig; - std::string _hostname; }; #endif // OTA_HPP \ No newline at end of file diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 4e91fed..24c98de 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -130,34 +130,47 @@ void BaseAPI::getJsonConfig(AsyncWebServerRequest *request) request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); } -void BaseAPI::setDeviceConfig(AsyncWebServerRequest *request){ - switch (_networkMethodsMap_enum[request->method()]){ - case GET: +void BaseAPI::setDeviceConfig(AsyncWebServerRequest *request) +{ + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + case POST: + { + int params = request->params(); + + std::string hostname; + std::string service; + std::string ota_password; + int ota_port; + + for (int i = 0; i < params; i++) { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); - break; - } - case POST: { - int params = request->params(); - - std::string device_name; - std::string ota_password; - int ota_port; - - for (int i = 0; i < params; i++){ - AsyncWebParameter *param = request->getParam(i); - if (param->name() == "device_name"){ - device_name = param->value().c_str(); - } - if (param->name() == "ota_port"){ - ota_port = atoi(param->value().c_str()); - } - if (param->name() == "ota_password"){ - ota_password = param->value().c_str(); - } + AsyncWebParameter *param = request->getParam(i); + if (param->name() == "hostname") + { + hostname = param->value().c_str(); + } + if (param->name() == "service") + { + service = param->value().c_str(); + } + if (param->name() == "ota_port") + { + ota_port = atoi(param->value().c_str()); + } + if (param->name() == "ota_password") + { + ota_password = param->value().c_str(); } - projectConfig->setDeviceConfig(device_name, ota_password, &ota_port, true); } + projectConfig->setDeviceConfig(ota_password, &ota_port, true); + projectConfig->setMDNSConfig(hostname, service, true); + } } } diff --git a/ESP/lib/src/network/mDNS/MDNSManager.cpp b/ESP/lib/src/network/mDNS/MDNSManager.cpp index ef01840..0a6340d 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.cpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.cpp @@ -6,15 +6,14 @@ MDNSHandler::MDNSHandler(StateManager *stateManager, void MDNSHandler::startMDNS() { - ProjectConfig::DeviceConfig_t *deviceConfig = configManager->getDeviceConfig(); - // deviceConfig->name.c_str() - if (MDNS.begin("openiristracker")) // lowercase only - as this will be the url + ProjectConfig::MDNSConfig_t *mdnsConfig = configManager->getMDNSConfig(); + if (MDNS.begin(mdnsConfig->hostname.c_str())) // lowercase only - as this will be the url { stateManager->setState(MDNSState_e::MDNSState_Starting); - MDNS.addService(deviceConfig->name.c_str(), "tcp", 80); + MDNS.addService(mdnsConfig->hostname.c_str(), "tcp", 80); char port[20]; //! Add service needs leading _ on ESP32 implementation for some reason (according to the docs) - MDNS.addServiceTxt(("_" + deviceConfig->name).c_str(), "_tcp", "_stream_port", (const char *)Helpers::itoa(80, port, 10)); //! convert int to const char* using a very efficient implemenation of itoa + MDNS.addServiceTxt(("_" + mdnsConfig->hostname).c_str(), "_tcp", "_stream_port", (const char *)Helpers::itoa(80, port, 10)); //! convert int to const char* using a very efficient implemenation of itoa log_i("MDNS initialized!"); stateManager->setState(MDNSState_e::MDNSState_Started); } @@ -29,7 +28,7 @@ void MDNSHandler::update(ObserverEvent::Event event) { switch (event) { - case ObserverEvent::Event::deviceConfigUpdated: + case ObserverEvent::Event::mdnsConfigUpdated: MDNS.end(); startMDNS(); break; diff --git a/ESP/lib/src/network/mDNS/queryMDNS.cpp b/ESP/lib/src/network/mDNS/queryMDNS.cpp index e69de29..cee205c 100644 --- a/ESP/lib/src/network/mDNS/queryMDNS.cpp +++ b/ESP/lib/src/network/mDNS/queryMDNS.cpp @@ -0,0 +1,65 @@ +#include "queryMDNS.hpp" + +QueryMDNSService::QueryMDNSService(StateManager *stateManager, + ProjectConfig *configManager) : stateManager(stateManager), + configManager(configManager) {} + +QueryMDNSService::~QueryMDNSService() +{ + // Finalize the MDNS library + mdns_free(); +} + +void QueryMDNSService::queryMDNS() +{ + stateManager->setState(MDNSState_e::MDNSState_QueryComplete); + ProjectConfig::MDNSConfig_t *mdnsConfig = configManager->getMDNSConfig(); + // check if we have a valid MDNS config + if (mdnsConfig->hostname.empty() && mdnsConfig->service.empty()) + { + // Initialize the MDNS library + std::string hostname; + std::string service; + // Initialize the MDNS library + if (mdns_init() != ESP_OK) + { + log_e("Error initializing MDNS Query"); + return; + } + int services_found = MDNS.queryService("openiristracker", "tcp"); + + if (services_found == 0) + { + log_e("No services found!"); + log_e("Setting a default hostname of 'openiristracker'"); + hostname.assign("openiristracker"); + log_i("Hostname: %s", hostname.c_str()); + service.assign("openiristracker"); + } + else + { + log_i("Services found: %d", services_found); + for (int i = 0; i < services_found; i++) + { + log_i("------------------------"); + log_i("Service #%d", i); + log_i(" - Hostname: %s", MDNS.hostname(i).c_str()); + log_i(" - IP: %s", MDNS.IP(i).toString().c_str()); + log_i(" - Port: %d", MDNS.port(i)); + log_i("------------------------"); + } + // append one greater than the number of services found to the hostname + // this will allow for multiple trackers to be found + hostname.assign(MDNS.hostname(services_found).c_str()); + hostname.append(std::to_string(services_found)); + + service.assign(MDNS.hostname(services_found).c_str()); + service.append(std::to_string(services_found)); + } + mdns_free(); // Free the MDNS library + stateManager->setState(MDNSState_e::MDNSState_QueryComplete); + return; + } + stateManager->setState(MDNSState_e::MDNSState_QueryComplete); + return; +} \ No newline at end of file diff --git a/ESP/lib/src/network/mDNS/queryMDNS.hpp b/ESP/lib/src/network/mDNS/queryMDNS.hpp index db30cf7..240d1e3 100644 --- a/ESP/lib/src/network/mDNS/queryMDNS.hpp +++ b/ESP/lib/src/network/mDNS/queryMDNS.hpp @@ -1,13 +1,14 @@ #pragma once #ifndef QUERYMDNSSERVICE_HPP #define QUERYMDNSSERVICE_HPP +#include #include #include "data/StateManager/StateManager.hpp" #include "data/utilities/Observer.hpp" #include "data/utilities/helpers.hpp" #include "data/config/project_config.hpp" -class QueryMDNSService : public IObserver +class QueryMDNSService { private: StateManager *stateManager; @@ -16,8 +17,8 @@ private: public: QueryMDNSService(StateManager *stateManager, ProjectConfig *configManager); + virtual ~QueryMDNSService(); void queryMDNS(); - void update(ObserverEvent::Event event); }; #endif // QUERYMDNSSERVICE_HPP \ No newline at end of file diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index f9e2457..819ee12 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -1,10 +1,12 @@ #include #include #include +#include #include #include #include #include + //! TODO: Setup OTA enabled state to be controllable by API if enabled at compile time #if ENABLE_OTA #include @@ -20,13 +22,14 @@ int CONTROL_SERVER_PORT = 81; ProjectConfig deviceConfig; #if ENABLE_OTA -OTA ota(&deviceConfig, "openiristracker"); +OTA ota(&deviceConfig); #endif // ENABLE_OTA LEDManager ledManager(33); CameraHandler cameraHandler(&deviceConfig, &ledStateManager); // SerialManager serialManager(&deviceConfig); WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); APIServer apiServer(CONTROL_SERVER_PORT, &deviceConfig, &cameraHandler, &wifiStateManager, "/control"); +QueryMDNSService mdnsQuery(&mdnsStateManager, &deviceConfig); MDNSHandler mdnsHandler(&mdnsStateManager, &deviceConfig); StreamServer streamServer(STREAM_SERVER_PORT); @@ -76,7 +79,17 @@ void setup() log_d("[SETUP]: Starting Stream Server"); apiServer.begin(); log_d("[SETUP]: Starting API Server"); - mdnsHandler.startMDNS(); + + mdnsQuery.queryMDNS(); // Query MDNS for hostname + switch (mdnsStateManager.getCurrentState()) + { + case MDNSState_e::MDNSState_QueryComplete: + { + log_d("[SETUP]: MDNS Query Complete"); + mdnsHandler.startMDNS(); + break; + } + } break; } case WiFiState_e::WiFiState_Connecting: diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 022e7e6..f1efb20 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -288 \ No newline at end of file +300 \ No newline at end of file From a223039a5af36ef22b72a61b154da37696404e98 Mon Sep 17 00:00:00 2001 From: lorow Date: Fri, 11 Nov 2022 00:43:55 +0100 Subject: [PATCH 126/153] implement getJsonConfig command --- ESP/lib/src/data/config/project_config.cpp | 21 +++++++++---- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 33 +++++++++++++++++++-- ESP/tools/versioning | 2 +- 3 files changed, 47 insertions(+), 9 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 36be6c3..ca9a2b9 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -297,16 +297,27 @@ void ProjectConfig::setAPWifiConfig(const std::string &ssid, const std::string & std::string ProjectConfig::DeviceConfig_t::toRepresentation() { std::string json = Helpers::format_string( - "device_config: {\"OTAPassword\": \"%s\", \"OTAPort\": %u}", + "\"device_config\": {\"OTAPassword\": \"%s\", \"OTAPort\": %u}", this->OTAPassword.c_str(), - this->OTAPort); + this->OTAPort + ); + return json; +} + +std::string ProjectConfig::MDNSConfig_t::toRepresentation() +{ + std::string json = Helpers::format_string( + "\"mdns_config\": {\"hostname\": \"%s\", \"service\": \"%s\"}", + this->hostname.c_str(), + this->service.c_str() + ); return json; } std::string ProjectConfig::CameraConfig_t::toRepresentation() { std::string json = Helpers::format_string( - "camera_config: {\"vflip\": %d,\"framesize\": %d,\"href\": %d,\"quality\": %d,\"brightness\": %d}", + "\"camera_config\": {\"vflip\": %d,\"framesize\": %d,\"href\": %d,\"quality\": %d,\"brightness\": %d}", this->vflip, this->framesize, this->href, @@ -318,7 +329,7 @@ std::string ProjectConfig::CameraConfig_t::toRepresentation() std::string ProjectConfig::WiFiConfig_t::toRepresentation() { std::string json = Helpers::format_string( - "wifi_config: {\"name\": \"%s\", \"ssid\": \"%s\", \"password\": \"%s\", \"channel\": %u, \"adhoc\": %s}", + "{\"name\": \"%s\", \"ssid\": \"%s\", \"password\": \"%s\", \"channel\": %u, \"adhoc\": %s}", this->name.c_str(), this->ssid.c_str(), this->password.c_str(), @@ -330,7 +341,7 @@ std::string ProjectConfig::WiFiConfig_t::toRepresentation() std::string ProjectConfig::AP_WiFiConfig_t::toRepresentation() { std::string json = Helpers::format_string( - "ap_wifi_config: {\"ssid\": \"%s\", \"password\": \"%s\", \"channel\": %u, \"adhoc\": %s}", + "\"ap_wifi_config\": {\"ssid\": \"%s\", \"password\": \"%s\", \"channel\": %u, \"adhoc\": %s}", this->ssid.c_str(), this->password.c_str(), this->channel, diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 24c98de..239d3fb 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -125,9 +125,36 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) void BaseAPI::getJsonConfig(AsyncWebServerRequest *request) { - // go through the config and build the response uisng toRepresentation methods - // consider moving handling the data to fromRepresentation - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + // returns the current stored config in case it get's deleted on the PC. + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + std::string wifiConfigSerialized ="\"wifi_config\": ["; + auto networksConfigs = projectConfig->getWifiConfigs(); + for(auto networkIterator = networksConfigs->begin(); networkIterator != networksConfigs->end(); networkIterator++) + { + wifiConfigSerialized += networkIterator->toRepresentation() + (std::next(networkIterator) != networksConfigs->end() ? "," : ""); + } + wifiConfigSerialized += "]"; + + std::string json = Helpers::format_string( + "{%s, %s, %s, %s, %s}", + projectConfig->getDeviceConfig()->toRepresentation().c_str(), + projectConfig->getCameraConfig()->toRepresentation().c_str(), + wifiConfigSerialized.c_str(), + projectConfig->getMDNSConfig()->toRepresentation().c_str(), + projectConfig->getAPWifiConfig()->toRepresentation().c_str() + ); + request->send(200, MIMETYPE_JSON, json.c_str()); + break; + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + } } void BaseAPI::setDeviceConfig(AsyncWebServerRequest *request) diff --git a/ESP/tools/versioning b/ESP/tools/versioning index f1efb20..7b89b22 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -300 \ No newline at end of file +406 \ No newline at end of file From a7dc565b994d50a6c3c849ec163a484fdbdd7882 Mon Sep 17 00:00:00 2001 From: DaOfficialWizard <45744329+ZanzyTHEbar@users.noreply.github.com> Date: Mon, 14 Nov 2022 12:46:28 +0000 Subject: [PATCH 127/153] Create devcontainer.json --- .devcontainer/devcontainer.json | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .devcontainer/devcontainer.json diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..7e91476 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,7 @@ +{ + "image": "mcr.microsoft.com/devcontainers/universal:2", + "features": { + "ghcr.io/devcontainers/features/git:1": {}, + "ghcr.io/devcontainers/features/github-cli:1": {} + } +} From 1fec7f6e3eafe4abe348aaa59dda62f748e19ceb Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 17 Nov 2022 21:29:55 +0000 Subject: [PATCH 128/153] update - add cpu clock setting --- ESP/src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 819ee12..8f59f5d 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -35,7 +35,7 @@ StreamServer streamServer(STREAM_SERVER_PORT); void setup() { - + setCpuFrequencyMhz(240); // set to 240mhz for performance boost Serial.begin(115200); Serial.setDebugOutput(DEBUG_MODE); Serial.println("\n"); From 656f8e80f5e26d9785218c4821a7da11334f1c1a Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 17 Nov 2022 21:38:13 +0000 Subject: [PATCH 129/153] update - basic formatting --- ESP/src/main.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 8f59f5d..2187dc2 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -40,19 +40,13 @@ void setup() Serial.setDebugOutput(DEBUG_MODE); Serial.println("\n"); Logo::printASCII(); - ledManager.begin(); - deviceConfig.attach(&cameraHandler); deviceConfig.attach(&mdnsHandler); - deviceConfig.initConfig(); deviceConfig.load(); - wifiHandler._enable_adhoc = ENABLE_ADHOC; - wifiHandler.setupWifi(); - switch (wifiStateManager.getCurrentState()) { case WiFiState_e::WiFiState_Disconnected: From e20d960dece29b98070e5c77da53fc84b4cd3b17 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 17 Nov 2022 22:51:22 +0000 Subject: [PATCH 130/153] update - fix query service - save result of query service to the config --- ESP/lib/src/network/mDNS/queryMDNS.cpp | 14 +++++++------- ESP/tools/versioning | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ESP/lib/src/network/mDNS/queryMDNS.cpp b/ESP/lib/src/network/mDNS/queryMDNS.cpp index cee205c..abe5f49 100644 --- a/ESP/lib/src/network/mDNS/queryMDNS.cpp +++ b/ESP/lib/src/network/mDNS/queryMDNS.cpp @@ -12,12 +12,11 @@ QueryMDNSService::~QueryMDNSService() void QueryMDNSService::queryMDNS() { - stateManager->setState(MDNSState_e::MDNSState_QueryComplete); + stateManager->setState(MDNSState_e::MDNSState_QueryStarted); ProjectConfig::MDNSConfig_t *mdnsConfig = configManager->getMDNSConfig(); // check if we have a valid MDNS config if (mdnsConfig->hostname.empty() && mdnsConfig->service.empty()) { - // Initialize the MDNS library std::string hostname; std::string service; // Initialize the MDNS library @@ -35,6 +34,7 @@ void QueryMDNSService::queryMDNS() hostname.assign("openiristracker"); log_i("Hostname: %s", hostname.c_str()); service.assign("openiristracker"); + configManager->setMDNSConfig(hostname, service, true); } else { @@ -50,11 +50,11 @@ void QueryMDNSService::queryMDNS() } // append one greater than the number of services found to the hostname // this will allow for multiple trackers to be found - hostname.assign(MDNS.hostname(services_found).c_str()); - hostname.append(std::to_string(services_found)); - - service.assign(MDNS.hostname(services_found).c_str()); - service.append(std::to_string(services_found)); + hostname.assign("openiristracker"); + hostname.append(std::to_string(services_found + 1)); + hostname.assign("openiristracker"); + service.append(std::to_string(services_found + 1)); + configManager->setMDNSConfig(hostname, service, true); } mdns_free(); // Free the MDNS library stateManager->setState(MDNSState_e::MDNSState_QueryComplete); diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 7b89b22..0ad1c6b 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -406 \ No newline at end of file +408 \ No newline at end of file From 6a2f0037617d0d06c872c0d11ab2905617d9cf2d Mon Sep 17 00:00:00 2001 From: lorow Date: Wed, 23 Nov 2022 00:06:25 +0100 Subject: [PATCH 131/153] Extract queryMDNS to feature/mdns-query --- ESP/lib/src/network/mDNS/queryMDNS.cpp | 65 -------------------------- ESP/lib/src/network/mDNS/queryMDNS.hpp | 24 ---------- ESP/src/main.cpp | 3 -- ESP/tools/versioning | 2 +- 4 files changed, 1 insertion(+), 93 deletions(-) delete mode 100644 ESP/lib/src/network/mDNS/queryMDNS.cpp delete mode 100644 ESP/lib/src/network/mDNS/queryMDNS.hpp diff --git a/ESP/lib/src/network/mDNS/queryMDNS.cpp b/ESP/lib/src/network/mDNS/queryMDNS.cpp deleted file mode 100644 index abe5f49..0000000 --- a/ESP/lib/src/network/mDNS/queryMDNS.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include "queryMDNS.hpp" - -QueryMDNSService::QueryMDNSService(StateManager *stateManager, - ProjectConfig *configManager) : stateManager(stateManager), - configManager(configManager) {} - -QueryMDNSService::~QueryMDNSService() -{ - // Finalize the MDNS library - mdns_free(); -} - -void QueryMDNSService::queryMDNS() -{ - stateManager->setState(MDNSState_e::MDNSState_QueryStarted); - ProjectConfig::MDNSConfig_t *mdnsConfig = configManager->getMDNSConfig(); - // check if we have a valid MDNS config - if (mdnsConfig->hostname.empty() && mdnsConfig->service.empty()) - { - std::string hostname; - std::string service; - // Initialize the MDNS library - if (mdns_init() != ESP_OK) - { - log_e("Error initializing MDNS Query"); - return; - } - int services_found = MDNS.queryService("openiristracker", "tcp"); - - if (services_found == 0) - { - log_e("No services found!"); - log_e("Setting a default hostname of 'openiristracker'"); - hostname.assign("openiristracker"); - log_i("Hostname: %s", hostname.c_str()); - service.assign("openiristracker"); - configManager->setMDNSConfig(hostname, service, true); - } - else - { - log_i("Services found: %d", services_found); - for (int i = 0; i < services_found; i++) - { - log_i("------------------------"); - log_i("Service #%d", i); - log_i(" - Hostname: %s", MDNS.hostname(i).c_str()); - log_i(" - IP: %s", MDNS.IP(i).toString().c_str()); - log_i(" - Port: %d", MDNS.port(i)); - log_i("------------------------"); - } - // append one greater than the number of services found to the hostname - // this will allow for multiple trackers to be found - hostname.assign("openiristracker"); - hostname.append(std::to_string(services_found + 1)); - hostname.assign("openiristracker"); - service.append(std::to_string(services_found + 1)); - configManager->setMDNSConfig(hostname, service, true); - } - mdns_free(); // Free the MDNS library - stateManager->setState(MDNSState_e::MDNSState_QueryComplete); - return; - } - stateManager->setState(MDNSState_e::MDNSState_QueryComplete); - return; -} \ No newline at end of file diff --git a/ESP/lib/src/network/mDNS/queryMDNS.hpp b/ESP/lib/src/network/mDNS/queryMDNS.hpp deleted file mode 100644 index 240d1e3..0000000 --- a/ESP/lib/src/network/mDNS/queryMDNS.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -#ifndef QUERYMDNSSERVICE_HPP -#define QUERYMDNSSERVICE_HPP -#include -#include -#include "data/StateManager/StateManager.hpp" -#include "data/utilities/Observer.hpp" -#include "data/utilities/helpers.hpp" -#include "data/config/project_config.hpp" - -class QueryMDNSService -{ -private: - StateManager *stateManager; - ProjectConfig *configManager; - -public: - QueryMDNSService(StateManager *stateManager, - ProjectConfig *configManager); - virtual ~QueryMDNSService(); - void queryMDNS(); -}; - -#endif // QUERYMDNSSERVICE_HPP \ No newline at end of file diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 2187dc2..8914fb5 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -1,7 +1,6 @@ #include #include #include -#include #include #include #include @@ -29,7 +28,6 @@ CameraHandler cameraHandler(&deviceConfig, &ledStateManager); // SerialManager serialManager(&deviceConfig); WiFiHandler wifiHandler(&deviceConfig, &wifiStateManager, WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL); APIServer apiServer(CONTROL_SERVER_PORT, &deviceConfig, &cameraHandler, &wifiStateManager, "/control"); -QueryMDNSService mdnsQuery(&mdnsStateManager, &deviceConfig); MDNSHandler mdnsHandler(&mdnsStateManager, &deviceConfig); StreamServer streamServer(STREAM_SERVER_PORT); @@ -74,7 +72,6 @@ void setup() apiServer.begin(); log_d("[SETUP]: Starting API Server"); - mdnsQuery.queryMDNS(); // Query MDNS for hostname switch (mdnsStateManager.getCurrentState()) { case MDNSState_e::MDNSState_QueryComplete: diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 0ad1c6b..95bae2d 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -408 \ No newline at end of file +446 \ No newline at end of file From 5dc236af06a620578bc394b3812de9bf4fbff28a Mon Sep 17 00:00:00 2001 From: lorow Date: Wed, 23 Nov 2022 00:08:51 +0100 Subject: [PATCH 132/153] Add documentation regarding passing down empty fields in baseAPI --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 239d3fb..d60259a 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -98,7 +98,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } - + // note: We're passing empty params by design, this is done to reset specific fields projectConfig->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); /* if (WiFiStateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) @@ -195,6 +195,7 @@ void BaseAPI::setDeviceConfig(AsyncWebServerRequest *request) ota_password = param->value().c_str(); } } + // note: We're passing empty params by design, this is done to reset specific fields projectConfig->setDeviceConfig(ota_password, &ota_port, true); projectConfig->setMDNSConfig(hostname, service, true); } @@ -280,7 +281,7 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) temp_camera_brightness = (uint8_t)param->value().toInt(); } } - + // note: We're passing empty params by design, this is done to reset specific fields projectConfig->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, &temp_camera_brightness, true); projectConfig->cameraConfigSave(); From 18ac6ff484dbc2cb16f2b40af4d5915cce454a18 Mon Sep 17 00:00:00 2001 From: lorow Date: Wed, 23 Nov 2022 01:23:51 +0100 Subject: [PATCH 133/153] Fix wifi command not updating/adding new networks --- ESP/lib/src/data/config/project_config.cpp | 55 +++++++++++---------- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 8 ++- 2 files changed, 36 insertions(+), 27 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index ca9a2b9..e944b20 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -242,40 +242,45 @@ void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t void ProjectConfig::setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify) { - WiFiConfig_t *networkToUpdate = nullptr; - // we store the ADHOC flag as false because the networks we store in the config are the ones we want the esp to connect to, rather than host as AP, and here we're just updating them size_t size = this->config.networks.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - if (strcmp(this->config.networks[i].name.c_str(), networkName.c_str()) == 0) - networkToUpdate = &this->config.networks[i]; - //! push_back creates a copy of the object, so we need to use emplace_back - if (networkToUpdate != nullptr) - { - this->config.networks.emplace_back( - networkName, - ssid, - password, - *channel, - false); - } - log_d("Updating wifi config"); - } - } - else - { - //! push_back creates a copy of the object, so we need to use emplace_back + // we're allowing to store up to three additional networks + if (size == 0) { + Serial.println("No networks, We're adding a new network"); + this->config.networks.emplace_back( + networkName, + ssid, + password, + *channel, + false); + } + + int networkToUpdate = -1; + for (int i = 0; i < size; i++){ + if (strcmp(this->config.networks[i].name.c_str(), networkName.c_str()) == 0){ + // we've found a preexisting network, let's upate it + networkToUpdate = i; + break; + } + } + + if (networkToUpdate >= 0) { + this->config.networks[networkToUpdate].name = networkName; + this->config.networks[networkToUpdate].ssid = ssid; + this->config.networks[networkToUpdate].password = password; + this->config.networks[networkToUpdate].channel = *channel; + this->config.networks[networkToUpdate].adhoc = false; + } else if (size < 3) { + Serial.println("We're adding a new network"); + // we don't have that network yet, we can add it as we still have some space + // we're using emplace_back as push_back will create a copy of it, we want to avoid that this->config.networks.emplace_back( networkName, ssid, password, *channel, false); - networkToUpdate = &this->config.networks[0]; } if (shouldNotify) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index d60259a..6e30d29 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -69,7 +69,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) case POST: { int params = request->params(); - + std::string networkName; std::string ssid; std::string password; uint8_t channel = 0; @@ -79,6 +79,10 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) for (int i = 0; i < params; i++) { AsyncWebParameter *param = request->getParam(i); + if (param->name() == "networkName") + { + networkName = param->value().c_str(); + } if (param->name() == "ssid") { ssid = param->value().c_str(); @@ -99,7 +103,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } // note: We're passing empty params by design, this is done to reset specific fields - projectConfig->setWifiConfig(ssid, ssid, password, &channel, adhoc, true); + projectConfig->setWifiConfig(networkName,ssid, password, &channel, adhoc, true); /* if (WiFiStateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { From 1be8e5fe19e9c18325fedfe1de3f9b221bdacdc3 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 27 Nov 2022 21:04:22 +0000 Subject: [PATCH 134/153] set default TX level to 5dBm --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 3 ++- ESP/tools/versioning | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 8d593bf..a1a2a88 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -56,7 +56,8 @@ void WiFiHandler::setupWifi() int progress = 0; WiFi.mode(WIFI_STA); - WiFi.setSleep(WIFI_PS_NONE); + WiFi.setTxPower(WIFI_POWER_5dBm); + WiFi.setSleep(WIFI_PS_NONE); for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) { log_i("Trying to connect to the %s network", networkIterator->ssid.c_str()); diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 95bae2d..2415c06 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -446 \ No newline at end of file +448 \ No newline at end of file From 8fde33b172aa872c57ca5d2a75eba39d29186313 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sun, 27 Nov 2022 21:21:16 +0000 Subject: [PATCH 135/153] update - change if to else if for handlers in baseAPI --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 6e30d29..c26c5ef 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -83,7 +83,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) { networkName = param->value().c_str(); } - if (param->name() == "ssid") + else if (param->name() == "ssid") { ssid = param->value().c_str(); } @@ -186,15 +186,15 @@ void BaseAPI::setDeviceConfig(AsyncWebServerRequest *request) { hostname = param->value().c_str(); } - if (param->name() == "service") + else if (param->name() == "service") { service = param->value().c_str(); } - if (param->name() == "ota_port") + else if (param->name() == "ota_port") { ota_port = atoi(param->value().c_str()); } - if (param->name() == "ota_password") + else if (param->name() == "ota_password") { ota_password = param->value().c_str(); } From 3f3e7215198694086b18a74093d38c4aac9cc877 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 28 Nov 2022 18:05:59 +0000 Subject: [PATCH 136/153] update - move Wifi.setTxPower below Wifi.begin --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 6 +++--- ESP/tools/versioning | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index a1a2a88..d4548a2 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -29,7 +29,7 @@ void WiFiHandler::setupWifi() // check size of networks log_i("Found %d networks stored in the config", networks->size()); - + //? Maybe this way is better? I don't know /* if (networks->empty()) { @@ -56,12 +56,12 @@ void WiFiHandler::setupWifi() int progress = 0; WiFi.mode(WIFI_STA); - WiFi.setTxPower(WIFI_POWER_5dBm); - WiFi.setSleep(WIFI_PS_NONE); + WiFi.setSleep(WIFI_PS_NONE); for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) { log_i("Trying to connect to the %s network", networkIterator->ssid.c_str()); WiFi.begin(networkIterator->ssid.c_str(), networkIterator->password.c_str()); + WiFi.setTxPower(WIFI_POWER_5dBm); count++; while (WiFi.status() != WL_CONNECTED) diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 2415c06..e966f90 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -448 \ No newline at end of file +450 \ No newline at end of file From 42413febeefc592972c9a0e0c8e61507e1604829 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 28 Nov 2022 18:12:29 +0000 Subject: [PATCH 137/153] update - remove WiFi.mode and WiFi.setSleep from initSTA - these methods were called twice if there is networks in the config however they fail to connect for some reason --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index d4548a2..3375631 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -44,6 +44,8 @@ void WiFiHandler::setupWifi() { log_e("No networks found in config"); stateManager->setState(WiFiState_e::WiFiState_Error); + WiFi.mode(WIFI_STA); + WiFi.setSleep(WIFI_PS_NONE); this->iniSTA(); return; } @@ -149,9 +151,6 @@ void WiFiHandler::iniSTA() return; } - WiFi.mode(WIFI_STA); - WiFi.setSleep(WIFI_PS_NONE); - WiFi.begin(this->ssid.c_str(), this->password.c_str(), this->channel); while (WiFi.status() != WL_CONNECTED) { From a63603636508b451d514618bd72ecd74fac983ac Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 28 Nov 2022 18:15:43 +0000 Subject: [PATCH 138/153] add setTxPower to initSTA --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 3375631..2aee637 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -152,6 +152,7 @@ void WiFiHandler::iniSTA() } WiFi.begin(this->ssid.c_str(), this->password.c_str(), this->channel); + WiFi.setTxPower(WIFI_POWER_5dBm); while (WiFi.status() != WL_CONNECTED) { stateManager->setState(WiFiState_e::WiFiState_Connecting); From 6a1192b356edfe4c294cf0330c5f29b3353789eb Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 1 Dec 2022 20:44:04 +0000 Subject: [PATCH 139/153] update - add deviceConfigSave - add mdnsConfigSave - add request send 200 to setDeviceConfig api event --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index c26c5ef..5128631 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -103,7 +103,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } // note: We're passing empty params by design, this is done to reset specific fields - projectConfig->setWifiConfig(networkName,ssid, password, &channel, adhoc, true); + projectConfig->setWifiConfig(networkName, ssid, password, &channel, adhoc, true); /* if (WiFiStateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { @@ -129,15 +129,15 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) void BaseAPI::getJsonConfig(AsyncWebServerRequest *request) { - // returns the current stored config in case it get's deleted on the PC. + // returns the current stored config in case it get's deleted on the PC. switch (_networkMethodsMap_enum[request->method()]) { - case GET: + case GET: { - std::string wifiConfigSerialized ="\"wifi_config\": ["; + std::string wifiConfigSerialized = "\"wifi_config\": ["; auto networksConfigs = projectConfig->getWifiConfigs(); - for(auto networkIterator = networksConfigs->begin(); networkIterator != networksConfigs->end(); networkIterator++) - { + for (auto networkIterator = networksConfigs->begin(); networkIterator != networksConfigs->end(); networkIterator++) + { wifiConfigSerialized += networkIterator->toRepresentation() + (std::next(networkIterator) != networksConfigs->end() ? "," : ""); } wifiConfigSerialized += "]"; @@ -148,12 +148,11 @@ void BaseAPI::getJsonConfig(AsyncWebServerRequest *request) projectConfig->getCameraConfig()->toRepresentation().c_str(), wifiConfigSerialized.c_str(), projectConfig->getMDNSConfig()->toRepresentation().c_str(), - projectConfig->getAPWifiConfig()->toRepresentation().c_str() - ); + projectConfig->getAPWifiConfig()->toRepresentation().c_str()); request->send(200, MIMETYPE_JSON, json.c_str()); break; } - default: + default: { request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); break; @@ -202,6 +201,9 @@ void BaseAPI::setDeviceConfig(AsyncWebServerRequest *request) // note: We're passing empty params by design, this is done to reset specific fields projectConfig->setDeviceConfig(ota_password, &ota_port, true); projectConfig->setMDNSConfig(hostname, service, true); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Device Config has been set.\"}"); + projectConfig->deviceConfigSave(); + projectConfig->mdnsConfigSave(); } } } From c850372243879201cba102f11fac2ecbb2e818ab Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Thu, 1 Dec 2022 21:25:29 +0000 Subject: [PATCH 140/153] update - implement setTxPower into main API - implement temporary dedicated global method - implement wifiConfig method per network --- ESP/lib/src/data/config/project_config.cpp | 83 ++++++++++++------- ESP/lib/src/data/config/project_config.hpp | 17 +++- ESP/lib/src/data/utilities/Observer.hpp | 1 + .../src/network/WifiHandler/WifiHandler.hpp | 2 + .../src/network/WifiHandler/wifiHandler.cpp | 12 ++- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 37 ++++++++- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 1 + ESP/lib/src/network/api/webserverHandler.cpp | 17 ++-- ESP/tools/versioning | 2 +- 9 files changed, 126 insertions(+), 46 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index e944b20..f8833d0 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -75,6 +75,7 @@ void ProjectConfig::wifiConfigSave() std::string ssid = "ssid"; std::string password = "pass"; std::string channel = "channel"; + std::string power = "power"; for (int i = 0; i < this->config.networks.size(); i++) { char buffer[2]; @@ -84,16 +85,13 @@ void ProjectConfig::wifiConfigSave() ssid.append(iter_str); password.append(iter_str); channel.append(iter_str); + power.append(iter_str); putString(name.c_str(), this->config.networks[i].name.c_str()); putString(ssid.c_str(), this->config.networks[i].ssid.c_str()); putString(password.c_str(), this->config.networks[i].password.c_str()); - putInt(channel.c_str(), this->config.networks[i].channel); - - name = "name"; - ssid = "ssid"; - password = "pass"; - channel = "channel"; + putUInt(channel.c_str(), this->config.networks[i].channel); + putUInt(power.c_str(), this->config.networks[i].power); } /* AP Config */ @@ -118,6 +116,12 @@ void ProjectConfig::mdnsConfigSave() putString("service", this->config.mdns.service.c_str()); } +void ProjectConfig::wifiTxPowerConfigSave() +{ + /* Device Config */ + putInt("power", this->config.txpower.power); +} + void ProjectConfig::cameraConfigSave() { /* Camera Config */ @@ -150,12 +154,16 @@ void ProjectConfig::load() /* MDNS Config */ this->config.mdns.hostname = getString("hostname").c_str(); this->config.mdns.service = getString("service").c_str(); + + /* Wifi TX Power Config */ + this->config.txpower.power = getUInt("power"); /* WiFi Config */ int networkCount = getInt("networkCount", 0); std::string name = "name"; std::string ssid = "ssid"; std::string password = "pass"; std::string channel = "channel"; + std::string power = "power"; for (int i = 0; i < networkCount; i++) { char buffer[2]; @@ -165,16 +173,13 @@ void ProjectConfig::load() ssid.append(iter_str); password.append(iter_str); channel.append(iter_str); + power.append(iter_str); const std::string &temp_1 = getString(name.c_str()).c_str(); const std::string &temp_2 = getString(ssid.c_str()).c_str(); const std::string &temp_3 = getString(password.c_str()).c_str(); uint8_t temp_4 = getUInt(channel.c_str()); - - name = "name"; - ssid = "ssid"; - password = "pass"; - channel = "channel"; + uint8_t temp_5 = getUInt(power.c_str()); //! push_back creates a copy of the object, so we need to use emplace_back this->config.networks.emplace_back( @@ -182,6 +187,7 @@ void ProjectConfig::load() temp_2, temp_3, temp_4, + temp_5, false); // false because the networks we store in the config are the ones we want the esp to connect to, rather than host as AP } @@ -240,38 +246,46 @@ void ProjectConfig::setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t this->notify(ObserverEvent::cameraConfigUpdated); } -void ProjectConfig::setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify) +void ProjectConfig::setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, uint8_t *power, bool adhoc, bool shouldNotify) { // we store the ADHOC flag as false because the networks we store in the config are the ones we want the esp to connect to, rather than host as AP, and here we're just updating them size_t size = this->config.networks.size(); - // we're allowing to store up to three additional networks - if (size == 0) { + // we're allowing to store up to three additional networks + if (size == 0) + { Serial.println("No networks, We're adding a new network"); this->config.networks.emplace_back( networkName, ssid, password, *channel, + *power, false); - } - + } + int networkToUpdate = -1; - for (int i = 0; i < size; i++){ - if (strcmp(this->config.networks[i].name.c_str(), networkName.c_str()) == 0){ + for (int i = 0; i < size; i++) + { + if (strcmp(this->config.networks[i].name.c_str(), networkName.c_str()) == 0) + { // we've found a preexisting network, let's upate it networkToUpdate = i; break; } } - if (networkToUpdate >= 0) { - this->config.networks[networkToUpdate].name = networkName; - this->config.networks[networkToUpdate].ssid = ssid; - this->config.networks[networkToUpdate].password = password; - this->config.networks[networkToUpdate].channel = *channel; - this->config.networks[networkToUpdate].adhoc = false; - } else if (size < 3) { + if (networkToUpdate >= 0) + { + this->config.networks[networkToUpdate].name = networkName; + this->config.networks[networkToUpdate].ssid = ssid; + this->config.networks[networkToUpdate].password = password; + this->config.networks[networkToUpdate].channel = *channel; + this->config.networks[networkToUpdate].power = *power; + this->config.networks[networkToUpdate].adhoc = false; + } + else if (size < 3) + { Serial.println("We're adding a new network"); // we don't have that network yet, we can add it as we still have some space // we're using emplace_back as push_back will create a copy of it, we want to avoid that @@ -280,6 +294,7 @@ void ProjectConfig::setWifiConfig(const std::string &networkName, const std::str ssid, password, *channel, + *power, false); } @@ -299,13 +314,21 @@ void ProjectConfig::setAPWifiConfig(const std::string &ssid, const std::string & this->notify(ObserverEvent::networksConfigUpdated); } +void ProjectConfig::setWiFiTxPower(uint8_t *power, bool shouldNotify) +{ + this->config.txpower.power = *power; + + log_d("Updating wifi tx power"); + if (shouldNotify) + this->notify(ObserverEvent::wifiTxPowerUpdated); +} + std::string ProjectConfig::DeviceConfig_t::toRepresentation() { std::string json = Helpers::format_string( "\"device_config\": {\"OTAPassword\": \"%s\", \"OTAPort\": %u}", this->OTAPassword.c_str(), - this->OTAPort - ); + this->OTAPort); return json; } @@ -314,8 +337,7 @@ std::string ProjectConfig::MDNSConfig_t::toRepresentation() std::string json = Helpers::format_string( "\"mdns_config\": {\"hostname\": \"%s\", \"service\": \"%s\"}", this->hostname.c_str(), - this->service.c_str() - ); + this->service.c_str()); return json; } @@ -364,4 +386,5 @@ ProjectConfig::DeviceConfig_t *ProjectConfig::getDeviceConfig() { return &this-> ProjectConfig::CameraConfig_t *ProjectConfig::getCameraConfig() { return &this->config.camera; } std::vector *ProjectConfig::getWifiConfigs() { return &this->config.networks; } ProjectConfig::AP_WiFiConfig_t *ProjectConfig::getAPWifiConfig() { return &this->config.ap_network; } -ProjectConfig::MDNSConfig_t *ProjectConfig::getMDNSConfig() { return &this->config.mdns; } \ No newline at end of file +ProjectConfig::MDNSConfig_t *ProjectConfig::getMDNSConfig() { return &this->config.mdns; } +ProjectConfig::WiFiTxPower_t *ProjectConfig::getWiFiTxPowerConfig() { return &this->config.txpower; } \ No newline at end of file diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 667fdd0..2acb43d 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -20,6 +20,7 @@ public: void cameraConfigSave(); void deviceConfigSave(); void mdnsConfigSave(); + void wifiTxPowerConfigSave(); bool reset(); void initConfig(); @@ -55,15 +56,18 @@ public: const std::string &ssid, const std::string &password, uint8_t channel, + uint8_t power, bool adhoc) : name(std::move(name)), ssid(std::move(ssid)), password(std::move(password)), channel(channel), - adhoc(adhoc) {} + adhoc(adhoc), + power(power) {} std::string name; std::string ssid; std::string password; uint8_t channel; + uint8_t power; bool adhoc; std::string toRepresentation(); @@ -78,6 +82,12 @@ public: std::string toRepresentation(); }; + struct WiFiTxPower_t + { + uint8_t power; + std::string toRepresentation(); + }; + struct TrackerConfig_t { DeviceConfig_t device; @@ -85,6 +95,7 @@ public: std::vector networks; AP_WiFiConfig_t ap_network; MDNSConfig_t mdns; + WiFiTxPower_t txpower; }; DeviceConfig_t *getDeviceConfig(); @@ -92,12 +103,14 @@ public: std::vector *getWifiConfigs(); AP_WiFiConfig_t *getAPWifiConfig(); MDNSConfig_t *getMDNSConfig(); + WiFiTxPower_t *getWiFiTxPowerConfig(); void setDeviceConfig(const std::string &OTAPassword, int *OTAPort, bool shouldNotify); void setMDNSConfig(const std::string &hostname, const std::string &service, bool shouldNotify); void setCameraConfig(uint8_t *vflip, uint8_t *framesize, uint8_t *href, uint8_t *quality, uint8_t *brightness, bool shouldNotify); - void setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify); + void setWifiConfig(const std::string &networkName, const std::string &ssid, const std::string &password, uint8_t *channel, uint8_t *power, bool adhoc, bool shouldNotify); void setAPWifiConfig(const std::string &ssid, const std::string &password, uint8_t *channel, bool adhoc, bool shouldNotify); + void setWiFiTxPower(uint8_t *power, bool shouldNotify); private: TrackerConfig_t config; diff --git a/ESP/lib/src/data/utilities/Observer.hpp b/ESP/lib/src/data/utilities/Observer.hpp index 2be42ea..f9265dd 100644 --- a/ESP/lib/src/data/utilities/Observer.hpp +++ b/ESP/lib/src/data/utilities/Observer.hpp @@ -12,6 +12,7 @@ namespace ObserverEvent cameraConfigUpdated = 3, networksConfigUpdated = 4, mdnsConfigUpdated = 5, + wifiTxPowerUpdated = 6, }; } diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index c9f38d2..f0bdc8c 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -21,6 +21,7 @@ public: ProjectConfig *configManager; StateManager *stateManager; + ProjectConfig::WiFiTxPower_t *txpower; bool _enable_adhoc; @@ -32,5 +33,6 @@ private: std::string ssid; std::string password; uint8_t channel; + uint8_t power; }; #endif // WIFIHANDLER_HPP diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 2aee637..f5d7d80 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -7,15 +7,18 @@ WiFiHandler::WiFiHandler(ProjectConfig *configManager, const std::string &password, uint8_t channel) : configManager(configManager), stateManager(stateManager), + txpower(NULL), ssid(ssid), password(password), channel(channel), + power(0), _enable_adhoc(false) {} WiFiHandler::~WiFiHandler() {} void WiFiHandler::setupWifi() { + txpower = configManager->getWiFiTxPowerConfig(); if (this->_enable_adhoc || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { this->setUpADHOC(); @@ -63,9 +66,10 @@ void WiFiHandler::setupWifi() { log_i("Trying to connect to the %s network", networkIterator->ssid.c_str()); WiFi.begin(networkIterator->ssid.c_str(), networkIterator->password.c_str()); - WiFi.setTxPower(WIFI_POWER_5dBm); + // WiFi.setTxPower(WIFI_POWER_5dBm); + // WiFi.setTxPower((wifi_power_t)networkIterator->power); + WiFi.setTxPower((wifi_power_t)txpower->power); count++; - while (WiFi.status() != WL_CONNECTED) { progress++; @@ -101,7 +105,7 @@ void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) 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. WiFi.softAP(ssid, password, channel); // AP mode with password - WiFi.setTxPower(WIFI_POWER_11dBm); + WiFi.setTxPower((wifi_power_t)txpower->power); } /* @@ -152,7 +156,7 @@ void WiFiHandler::iniSTA() } WiFi.begin(this->ssid.c_str(), this->password.c_str(), this->channel); - WiFi.setTxPower(WIFI_POWER_5dBm); + WiFi.setTxPower((wifi_power_t)txpower->power); while (WiFi.status() != WL_CONNECTED) { stateManager->setState(WiFiState_e::WiFiState_Connecting); diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 5128631..04aec7b 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -73,6 +73,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) std::string ssid; std::string password; uint8_t channel = 0; + uint8_t power = 0; uint8_t adhoc = 0; log_d("Number of Params: %d", params); @@ -95,6 +96,10 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) { channel = (uint8_t)atoi(param->value().c_str()); } + else if (param->name() == "power") + { + power = (uint8_t)atoi(param->value().c_str()); + } else if (param->name() == "adhoc") { adhoc = (uint8_t)atoi(param->value().c_str()); @@ -103,7 +108,7 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) log_i("%s[%s]: %s\n", _networkMethodsMap[request->method()].c_str(), param->name().c_str(), param->value().c_str()); } // note: We're passing empty params by design, this is done to reset specific fields - projectConfig->setWifiConfig(networkName, ssid, password, &channel, adhoc, true); + projectConfig->setWifiConfig(networkName, ssid, password, &channel, &power, adhoc, true); /* if (WiFiStateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { @@ -208,6 +213,36 @@ void BaseAPI::setDeviceConfig(AsyncWebServerRequest *request) } } +void BaseAPI::setWiFiTXPower(AsyncWebServerRequest *request) +{ + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + case POST: + { + int params = request->params(); + + uint8_t txPower = 0; + + for (int i = 0; i < params; i++) + { + AsyncWebParameter *param = request->getParam(i); + if (param->name() == "txPower") + { + txPower = atoi(param->value().c_str()); + } + } + projectConfig->setWiFiTxPower(&txPower, true); + projectConfig->wifiTxPowerConfigSave(); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. TX Power has been set.\"}"); + } + } +} + void BaseAPI::rebootDevice(AsyncWebServerRequest *request) { switch (_networkMethodsMap_enum[request->method()]) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index e6f4d96..fd8d377 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -44,6 +44,7 @@ protected: protected: /* Commands */ void setWiFi(AsyncWebServerRequest *request); + void setWiFiTXPower(AsyncWebServerRequest *request); void getJsonConfig(AsyncWebServerRequest *request); void factoryReset(AsyncWebServerRequest *request); void setDeviceConfig(AsyncWebServerRequest *request); diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 9dea50f..1423a35 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -5,14 +5,14 @@ //********************************************************************************************* APIServer::APIServer(int CONTROL_PORT, - ProjectConfig *projectConfig, - CameraHandler *camera, - StateManager *WiFiStateManager, - const std::string &api_url) : BaseAPI(CONTROL_PORT, - projectConfig, - camera, - WiFiStateManager, - api_url){} + ProjectConfig *projectConfig, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url) : BaseAPI(CONTROL_PORT, + projectConfig, + camera, + WiFiStateManager, + api_url) {} APIServer::~APIServer() {} @@ -38,6 +38,7 @@ void APIServer::setupServer() routes.emplace("setDevice", &APIServer::setDeviceConfig); routes.emplace("rebootDevice", &APIServer::rebootDevice); routes.emplace("getStoredConfig", &APIServer::getJsonConfig); + routes.emplace("setTxPower", &APIServer::setWiFiTXPower); // Camera Routes routes.emplace("setCamera", &APIServer::setCamera); routes.emplace("restartCamera", &APIServer::restartCamera); diff --git a/ESP/tools/versioning b/ESP/tools/versioning index e966f90..ee2b836 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -450 \ No newline at end of file +456 \ No newline at end of file From e137601fc551dfd5e09b20fb9da74fc5c1433378 Mon Sep 17 00:00:00 2001 From: lorow Date: Thu, 1 Dec 2022 23:03:30 +0100 Subject: [PATCH 141/153] Add ping and save routes, remove atomic saves from config endpoints --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 16 ++++++++++++---- ESP/lib/src/network/api/baseAPI/baseAPI.hpp | 2 ++ ESP/lib/src/network/api/webserverHandler.cpp | 2 ++ 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 04aec7b..afd6350 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -120,7 +120,6 @@ void BaseAPI::setWiFi(AsyncWebServerRequest *request) } */ request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Wifi Creds have been set.\"}"); - projectConfig->wifiConfigSave(); break; } default: @@ -207,8 +206,6 @@ void BaseAPI::setDeviceConfig(AsyncWebServerRequest *request) projectConfig->setDeviceConfig(ota_password, &ota_port, true); projectConfig->setMDNSConfig(hostname, service, true); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Device Config has been set.\"}"); - projectConfig->deviceConfigSave(); - projectConfig->mdnsConfigSave(); } } } @@ -324,7 +321,6 @@ void BaseAPI::setCamera(AsyncWebServerRequest *request) } // note: We're passing empty params by design, this is done to reset specific fields projectConfig->setCameraConfig(&temp_camera_vflip, &temp_camera_framesize, &temp_camera_hflip, &temp_camera_quality, &temp_camera_brightness, true); - projectConfig->cameraConfigSave(); request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera Settings have been set.\"}"); break; @@ -345,3 +341,15 @@ void BaseAPI::restartCamera(AsyncWebServerRequest *request) request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera had been restarted.\"}"); } + + +void BaseAPI::ping(AsyncWebServerRequest *request) +{ + request->send(200, MIMETYPE_JSON, "{\"status\": \"ok\" }"); +} + +void BaseAPI::save(AsyncWebServerRequest *request) +{ + projectConfig->save(); + request->send(200, MIMETYPE_JSON, "{\"status\": \"ok\" }"); +} \ No newline at end of file diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp index fd8d377..7dee85c 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.hpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -49,6 +49,8 @@ protected: void factoryReset(AsyncWebServerRequest *request); void setDeviceConfig(AsyncWebServerRequest *request); void rebootDevice(AsyncWebServerRequest *request); + void ping(AsyncWebServerRequest *request); + void save(AsyncWebServerRequest *request); /* Camera Handlers */ void setCamera(AsyncWebServerRequest *request); diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 1423a35..0b1bd18 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -42,6 +42,8 @@ void APIServer::setupServer() // Camera Routes routes.emplace("setCamera", &APIServer::setCamera); routes.emplace("restartCamera", &APIServer::restartCamera); + routes.emplace("ping", &APIServer::ping); + routes.emplace("save", &APIServer::save); //! reserve enough memory for all routes - must be called after adding routes and before adding routes to route_map indexes.reserve(routes.size()); // this is done to avoid reallocation of memory and copying of data From 2827ab8717c6f65c6a0ec894eb9fc6765c7cc61e Mon Sep 17 00:00:00 2001 From: lorow Date: Thu, 1 Dec 2022 23:37:40 +0100 Subject: [PATCH 142/153] make api responses consistent: status -> msg --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 4 ++-- ESP/tools/versioning | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index afd6350..9d288b0 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -345,11 +345,11 @@ void BaseAPI::restartCamera(AsyncWebServerRequest *request) void BaseAPI::ping(AsyncWebServerRequest *request) { - request->send(200, MIMETYPE_JSON, "{\"status\": \"ok\" }"); + request->send(200, MIMETYPE_JSON, "{\"msg\": \"ok\" }"); } void BaseAPI::save(AsyncWebServerRequest *request) { projectConfig->save(); - request->send(200, MIMETYPE_JSON, "{\"status\": \"ok\" }"); + request->send(200, MIMETYPE_JSON, "{\"msg\": \"ok\" }"); } \ No newline at end of file diff --git a/ESP/tools/versioning b/ESP/tools/versioning index ee2b836..2d3d9c2 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -456 \ No newline at end of file +472 \ No newline at end of file From e7ea1341a307b15161ff7882d03aa45f65255e73 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 3 Dec 2022 02:08:08 +0000 Subject: [PATCH 143/153] update - remove MDNS name build flag --- ESP/platformio.ini | 1 - ESP/tools/versioning | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 28b4360..51cd2bd 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -88,7 +88,6 @@ build_flags = -DADHOC_CHANNEL=${wifi.adhocChannel} ; -DWIFI_CHANNEL=${wifi.channel} ; -DENABLE_OTA=${wifi.enableOTA} ; - '-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 '-DOTA_PASSWORD=${wifi.OTAPassword}' ; Set the OTA password '-DWIFI_SSID=${wifi.ssid}' ; Set the users wifi network name '-DWIFI_PASSWORD=${wifi.password}' ; Set the users wifi network password diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 2d3d9c2..d7b14a6 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -472 \ No newline at end of file +476 \ No newline at end of file From 74f3f27b569267f321527781211460fbff28e1d4 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 3 Dec 2022 02:27:59 +0000 Subject: [PATCH 144/153] fix mDNS handler not starting bug --- ESP/src/main.cpp | 12 +----------- ESP/tools/versioning | 2 +- 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 8914fb5..b7985fa 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -71,17 +71,7 @@ void setup() log_d("[SETUP]: Starting Stream Server"); apiServer.begin(); log_d("[SETUP]: Starting API Server"); - - switch (mdnsStateManager.getCurrentState()) - { - case MDNSState_e::MDNSState_QueryComplete: - { - log_d("[SETUP]: MDNS Query Complete"); - mdnsHandler.startMDNS(); - break; - } - } - break; + mdnsHandler.startMDNS(); } case WiFiState_e::WiFiState_Connecting: { diff --git a/ESP/tools/versioning b/ESP/tools/versioning index d7b14a6..1e27e32 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -476 \ No newline at end of file +478 \ No newline at end of file From 09bfc2c964fe6f131862e43b8387f2612aeac30d Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 3 Dec 2022 02:30:48 +0000 Subject: [PATCH 145/153] add back-in missing break statement --- ESP/src/main.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index b7985fa..229ce80 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -72,6 +72,7 @@ void setup() apiServer.begin(); log_d("[SETUP]: Starting API Server"); mdnsHandler.startMDNS(); + break; } case WiFiState_e::WiFiState_Connecting: { From 70c8d1697b37e1eb68cef9adb8ec84ef9764b2b3 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 3 Dec 2022 04:49:08 +0000 Subject: [PATCH 146/153] update - fix bug in mDNS handler --- ESP/lib/src/data/config/project_config.cpp | 6 +++--- ESP/lib/src/network/mDNS/MDNSManager.cpp | 24 +++++++++++----------- ESP/lib/src/network/mDNS/MDNSManager.hpp | 3 +-- ESP/src/main.cpp | 2 +- ESP/tools/versioning | 2 +- 5 files changed, 18 insertions(+), 19 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index f8833d0..a5d4ba3 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -152,11 +152,11 @@ void ProjectConfig::load() this->config.device.OTAPort = getInt("OTAPort", 3232); /* MDNS Config */ - this->config.mdns.hostname = getString("hostname").c_str(); - this->config.mdns.service = getString("service").c_str(); + this->config.mdns.hostname = getString("hostname", "openiristracker").c_str(); + this->config.mdns.service = getString("service", "_openiristracker").c_str(); /* Wifi TX Power Config */ - this->config.txpower.power = getUInt("power"); + this->config.txpower.power = getUInt("power", 52); /* WiFi Config */ int networkCount = getInt("networkCount", 0); std::string name = "name"; diff --git a/ESP/lib/src/network/mDNS/MDNSManager.cpp b/ESP/lib/src/network/mDNS/MDNSManager.cpp index 0a6340d..2b05bc2 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.cpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.cpp @@ -4,24 +4,24 @@ MDNSHandler::MDNSHandler(StateManager *stateManager, ProjectConfig *configManager) : stateManager(stateManager), configManager(configManager) {} -void MDNSHandler::startMDNS() +bool MDNSHandler::startMDNS() { ProjectConfig::MDNSConfig_t *mdnsConfig = configManager->getMDNSConfig(); - if (MDNS.begin(mdnsConfig->hostname.c_str())) // lowercase only - as this will be the url - { - stateManager->setState(MDNSState_e::MDNSState_Starting); - MDNS.addService(mdnsConfig->hostname.c_str(), "tcp", 80); - char port[20]; - //! Add service needs leading _ on ESP32 implementation for some reason (according to the docs) - MDNS.addServiceTxt(("_" + mdnsConfig->hostname).c_str(), "_tcp", "_stream_port", (const char *)Helpers::itoa(80, port, 10)); //! convert int to const char* using a very efficient implemenation of itoa - log_i("MDNS initialized!"); - stateManager->setState(MDNSState_e::MDNSState_Started); - } - else + if (!MDNS.begin(mdnsConfig->hostname.c_str())) // lowercase only - as this will be the url { stateManager->setState(MDNSState_e::MDNSState_Error); log_e("Error initializing MDNS"); + return false; } + + stateManager->setState(MDNSState_e::MDNSState_Starting); + MDNS.addService(mdnsConfig->hostname.c_str(), "tcp", 80); + char port[20]; + //! Add service needs leading _ on ESP32 implementation for some reason (according to the docs) + MDNS.addServiceTxt(("_" + mdnsConfig->hostname).c_str(), "_tcp", "stream_port", (const char *)Helpers::itoa(80, port, 10)); //! convert int to const char* using a very efficient implemenation of itoa + log_i("MDNS initialized!"); + stateManager->setState(MDNSState_e::MDNSState_Started); + return true; } void MDNSHandler::update(ObserverEvent::Event event) diff --git a/ESP/lib/src/network/mDNS/MDNSManager.hpp b/ESP/lib/src/network/mDNS/MDNSManager.hpp index a33be12..b71f97f 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.hpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.hpp @@ -1,4 +1,3 @@ -#pragma once #ifndef MDNSHANDLER_HPP #define MDNSHANDLER_HPP #include @@ -16,7 +15,7 @@ private: public: MDNSHandler(StateManager *stateManager, ProjectConfig *configManager); - void startMDNS(); + bool startMDNS(); void update(ObserverEvent::Event event); }; diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 229ce80..731551f 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -45,6 +45,7 @@ void setup() deviceConfig.load(); wifiHandler._enable_adhoc = ENABLE_ADHOC; wifiHandler.setupWifi(); + mdnsHandler.startMDNS(); switch (wifiStateManager.getCurrentState()) { case WiFiState_e::WiFiState_Disconnected: @@ -71,7 +72,6 @@ void setup() log_d("[SETUP]: Starting Stream Server"); apiServer.begin(); log_d("[SETUP]: Starting API Server"); - mdnsHandler.startMDNS(); break; } case WiFiState_e::WiFiState_Connecting: diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 1e27e32..d9bf67e 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -478 \ No newline at end of file +484 \ No newline at end of file From 5ca84d23166ee3c8f62ce5136e4786c08b5b0ade Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 3 Dec 2022 05:03:40 +0000 Subject: [PATCH 147/153] update - set mDNS default valeu to be dynamic --- ESP/lib/src/data/config/project_config.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index a5d4ba3..a6b313c 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -152,8 +152,11 @@ void ProjectConfig::load() this->config.device.OTAPort = getInt("OTAPort", 3232); /* MDNS Config */ - this->config.mdns.hostname = getString("hostname", "openiristracker").c_str(); - this->config.mdns.service = getString("service", "_openiristracker").c_str(); + const std::string default_hostname = this->config.mdns.hostname; + std::string default_service = "_"; + default_service.append(this->config.mdns.service); + this->config.mdns.hostname = getString("hostname", default_hostname.c_str()).c_str(); + this->config.mdns.service = getString("service", default_service.c_str()).c_str(); /* Wifi TX Power Config */ this->config.txpower.power = getUInt("power", 52); From 061e3cb8d3e6ad35e4ffd1b3aefa6dcadc8e7421 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 3 Dec 2022 05:17:30 +0000 Subject: [PATCH 148/153] update - setup default mDNS hostname to be user configurable --- ESP/lib/src/data/config/project_config.cpp | 21 ++++++++++++++------- ESP/lib/src/data/config/project_config.hpp | 6 ++++-- ESP/platformio.ini | 2 ++ ESP/src/main.cpp | 8 +++++++- ESP/tools/versioning | 2 +- 5 files changed, 28 insertions(+), 11 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index a6b313c..5d2ece7 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -1,6 +1,9 @@ #include "project_config.hpp" -ProjectConfig::ProjectConfig(const std::string &name) : _name(std::move(name)), _already_loaded(false) {} +ProjectConfig::ProjectConfig(const std::string &name, + const std::string &mdnsName) : _name(std::move(name)), + _mdnsName(std::move(mdnsName)), + _already_loaded(false) {} ProjectConfig::~ProjectConfig() {} @@ -32,11 +35,18 @@ void ProjectConfig::initConfig() 3232, }; + if (_mdnsName.empty()) + { + log_e("MDNS name is null\n Autoassigning name to 'easynetwork'"); + _mdnsName = "openiristracker"; + } this->config.mdns = { - "openiristracker", + _mdnsName, "", }; + log_i("MDNS name: %s", _mdnsName.c_str()); + this->config.ap_network = { "", "", @@ -152,11 +162,8 @@ void ProjectConfig::load() this->config.device.OTAPort = getInt("OTAPort", 3232); /* MDNS Config */ - const std::string default_hostname = this->config.mdns.hostname; - std::string default_service = "_"; - default_service.append(this->config.mdns.service); - this->config.mdns.hostname = getString("hostname", default_hostname.c_str()).c_str(); - this->config.mdns.service = getString("service", default_service.c_str()).c_str(); + this->config.mdns.hostname = getString("hostname", _mdnsName.c_str()).c_str(); + this->config.mdns.service = getString("service").c_str(); /* Wifi TX Power Config */ this->config.txpower.power = getUInt("power", 52); diff --git a/ESP/lib/src/data/config/project_config.hpp b/ESP/lib/src/data/config/project_config.hpp index 2acb43d..388f5b0 100644 --- a/ESP/lib/src/data/config/project_config.hpp +++ b/ESP/lib/src/data/config/project_config.hpp @@ -12,7 +12,8 @@ class ProjectConfig : public Preferences, public ISubject { public: - ProjectConfig(const std::string &name = std::string()); + ProjectConfig(const std::string &name = std::string(), + const std::string &mdnsName = std::string()); virtual ~ProjectConfig(); void load(); void save(); @@ -114,8 +115,9 @@ public: private: TrackerConfig_t config; - bool _already_loaded; std::string _name; + std::string _mdnsName; + bool _already_loaded; }; #endif // PROJECT_CONFIG_HPP \ No newline at end of file diff --git a/ESP/platformio.ini b/ESP/platformio.ini index 51cd2bd..413379f 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -16,6 +16,7 @@ default_envs = esp32Cam ; do not change this value [wifi] ssid="" ; your wifi network name goes here password="" ; your wifi network password goes here +mDNSName="openiristracker" ; the name of the tracker as it will appear on your network channel=1 ; wifi channel ap_ssid="EyeTrackVR" ; your AP wifi network name goes here ap_password="test" ; Place your AP Wifi password here @@ -88,6 +89,7 @@ build_flags = -DADHOC_CHANNEL=${wifi.adhocChannel} ; -DWIFI_CHANNEL=${wifi.channel} ; -DENABLE_OTA=${wifi.enableOTA} ; + '-DMDNS_HOSTNAME=${wifi.mDNSName}' ; Set the OTA password '-DOTA_PASSWORD=${wifi.OTAPassword}' ; Set the OTA password '-DWIFI_SSID=${wifi.ssid}' ; Set the users wifi network name '-DWIFI_PASSWORD=${wifi.password}' ; Set the users wifi network password diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 731551f..1ca31a7 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -19,7 +19,13 @@ int STREAM_SERVER_PORT = 80; int CONTROL_SERVER_PORT = 81; -ProjectConfig deviceConfig; +/** + * @brief ProjectConfig object + * @brief This is the main configuration object for the project + * @param name The name of the project config partition + * @param mdnsName The mDNS hostname to use + */ +ProjectConfig deviceConfig("openiris", MDNS_HOSTNAME); #if ENABLE_OTA OTA ota(&deviceConfig); #endif // ENABLE_OTA diff --git a/ESP/tools/versioning b/ESP/tools/versioning index d9bf67e..eb1f494 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -484 \ No newline at end of file +500 \ No newline at end of file From b2f9c86205b5eefca849efae30bdf26d47a962f6 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Sat, 3 Dec 2022 05:23:23 +0000 Subject: [PATCH 149/153] update - minor change to log statement --- ESP/lib/src/data/config/project_config.cpp | 2 +- ESP/tools/versioning | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index 5d2ece7..f406b22 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -37,7 +37,7 @@ void ProjectConfig::initConfig() if (_mdnsName.empty()) { - log_e("MDNS name is null\n Autoassigning name to 'easynetwork'"); + log_e("MDNS name is null\n Autoassigning name to 'openiristracker'"); _mdnsName = "openiristracker"; } this->config.mdns = { diff --git a/ESP/tools/versioning b/ESP/tools/versioning index eb1f494..99f9f07 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -500 \ No newline at end of file +502 \ No newline at end of file From 935f8c1c204a163a37aee14f12c11a3cf3cc742d Mon Sep 17 00:00:00 2001 From: lorow Date: Sun, 4 Dec 2022 17:14:02 +0100 Subject: [PATCH 150/153] Rewrite WiFi connection stack --- .../src/network/WifiHandler/WifiHandler.hpp | 2 +- .../src/network/WifiHandler/wifiHandler.cpp | 134 +++++++----------- 2 files changed, 49 insertions(+), 87 deletions(-) diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index f0bdc8c..4311415 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -28,7 +28,7 @@ public: private: void setUpADHOC(); void adhoc(const char *ssid, const char *password, uint8_t channel); - void iniSTA(); + bool iniSTA(const char *ssid, const char *password, uint8_t channel, wifi_power_t power); std::string ssid; std::string password; diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index f5d7d80..51716c7 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -18,78 +18,51 @@ WiFiHandler::~WiFiHandler() {} void WiFiHandler::setupWifi() { - txpower = configManager->getWiFiTxPowerConfig(); if (this->_enable_adhoc || stateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) { this->setUpADHOC(); return; } + txpower = configManager->getWiFiTxPowerConfig(); + WiFi.mode(WIFI_STA); + WiFi.setSleep(WIFI_PS_NONE); - log_i("Initializing connection to wifi"); + log_i("Initializing connection to wifi \n\r"); stateManager->setState(WiFiState_e::WiFiState_Connecting); std::vector *networks = configManager->getWifiConfigs(); - // check size of networks - log_i("Found %d networks stored in the config", networks->size()); - - //? Maybe this way is better? I don't know - /* if (networks->empty()) + if (networks->empty()) { - log_e("No networks found in config"); - this->iniSTA(); - stateManager->setState(WiFiState_e::WiFiState_Error); - return; - } */ - - //* Check if there are networks in the config, if not move on to values used in ini file. - if (networks->size() == 0) - { - log_e("No networks found in config"); - stateManager->setState(WiFiState_e::WiFiState_Error); - WiFi.mode(WIFI_STA); - WiFi.setSleep(WIFI_PS_NONE); - this->iniSTA(); - return; + log_i("No networks found in config, trying the default one \n\r"); + if(this->iniSTA(this->ssid.c_str(), this->password.c_str(), this->channel, (wifi_power_t)txpower->power)) + { + return; + } + else + { + log_i("Could not connect to the hardcoded network, setting up ADHOC network \n\r"); + this->setUpADHOC(); + } } - int connection_timeout = 30000; // 30 seconds - - int count = 0; - unsigned long currentMillis = millis(); - unsigned long _previousMillis = currentMillis; - int progress = 0; - - WiFi.mode(WIFI_STA); - WiFi.setSleep(WIFI_PS_NONE); - 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.c_str()); - WiFi.begin(networkIterator->ssid.c_str(), networkIterator->password.c_str()); - // WiFi.setTxPower(WIFI_POWER_5dBm); - // WiFi.setTxPower((wifi_power_t)networkIterator->power); - WiFi.setTxPower((wifi_power_t)txpower->power); - count++; - while (WiFi.status() != WL_CONNECTED) + if(this->iniSTA(networkIterator->ssid.c_str(), networkIterator->password.c_str(), networkIterator->channel, (wifi_power_t)networkIterator->power)) { - progress++; - stateManager->setState(WiFiState_e::WiFiState_Connecting); - currentMillis = millis(); - Helpers::update_progress_bar(progress, 100); - delay(301); - if (((currentMillis - _previousMillis) >= connection_timeout) && (count >= networks->size())) - { - log_i("\n[INFO]: WiFi connection timed out.\n"); - // we've tried all saved networks, none worked, let's error out - log_e("\nCould not connect to any of the saved networks, check your Wifi credentials"); - stateManager->setState(WiFiState_e::WiFiState_Disconnected); - log_i("\n[INFO]: Attempting to connect to hardcoded network"); - this->iniSTA(); - return; - } + return; } - log_i("\n\rSuccessfully connected to %s\n\r", networkIterator->ssid.c_str()); - stateManager->setState(WiFiState_e::WiFiState_Connected); + } + + // at this point, we've tried every network, let's just setup adhoc + log_i("We've gone through every network, each timed out. Trying to connect to hardcoded network: %s \n\r", this->ssid.c_str()); + if(this->iniSTA(this->ssid.c_str(), this->password.c_str(), this->channel, (wifi_power_t)txpower->power)) + { + log_i("Successfully connected to the hardcoded network. \n\r"); + } else + { + log_i("Could not connect to the hardcoded network, setting up adhoc. \n\r"); + this->setUpADHOC(); } } @@ -108,9 +81,6 @@ void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) WiFi.setTxPower((wifi_power_t)txpower->power); } -/* - * * - */ void WiFiHandler::setUpADHOC() { log_i("\n[INFO]: Setting Access Point...\n"); @@ -138,43 +108,35 @@ void WiFiHandler::setUpADHOC() log_d("\n[DEBUG]: channel: %d\n", channel); } -void WiFiHandler::iniSTA() +bool WiFiHandler::iniSTA(const char *ssid, const char *password, uint8_t channel, wifi_power_t power) { - log_i("\n[INFO]: Setting up station...\n"); - int connection_timeout = 30000; // 30 seconds unsigned long currentMillis = millis(); - unsigned long _previousMillis = currentMillis; + unsigned long startingMillis = currentMillis; + int connectionTimeout = 30000; // 30 seconds int progress = 0; - log_i("Trying to connect to the %s network", this->ssid.c_str()); - // check size of networks - if (this->ssid.size() == 0) - { - log_e("No networks passed into the constructor"); - stateManager->setState(WiFiState_e::WiFiState_Error); - this->setUpADHOC(); - return; - } - WiFi.begin(this->ssid.c_str(), this->password.c_str(), this->channel); - WiFi.setTxPower((wifi_power_t)txpower->power); - while (WiFi.status() != WL_CONNECTED) + stateManager->setState(WiFiState_e::WiFiState_Connecting); + log_i("Trying to connect to: %s \n\r", ssid); + + WiFi.begin(ssid, password, channel); + while(WiFi.status() != WL_CONNECTED) { - stateManager->setState(WiFiState_e::WiFiState_Connecting); + progress++; currentMillis = millis(); Helpers::update_progress_bar(progress, 100); delay(301); - if ((currentMillis - _previousMillis) >= connection_timeout) + if ((currentMillis - startingMillis) >= connectionTimeout) { - log_i("\n[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->setUpADHOC(); - log_w("Setting up adhoc mode"); - log_w("Please use adhoc mode and the app to set your WiFi credentials and reboot the device"); - return; - } + log_e("Connection to: %s TIMEOUT \n\r", ssid); + return false; + } } - log_i("\n\rSuccessfully connected to %s\n\r", this->ssid.c_str()); + stateManager->setState(WiFiState_e::WiFiState_Connected); + log_i("Successfully connected to %s \n\r", ssid); + log_i("Setting TX power to: %d \n\r", (uint8_t)power); + WiFi.setTxPower(power); + + return true; } From 85a56050642f720c6c52391acb3e9c1f46a73217 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 5 Dec 2022 15:20:49 +0000 Subject: [PATCH 151/153] update - fix a few bugs in adhoc and project config - format --- ESP/lib/src/data/config/project_config.cpp | 1 + .../src/network/WifiHandler/WifiHandler.hpp | 3 +- .../src/network/WifiHandler/wifiHandler.cpp | 58 ++++++++++--------- ESP/lib/src/network/api/webserverHandler.cpp | 1 - ESP/tools/versioning | 2 +- 5 files changed, 34 insertions(+), 31 deletions(-) diff --git a/ESP/lib/src/data/config/project_config.cpp b/ESP/lib/src/data/config/project_config.cpp index f406b22..de8c625 100644 --- a/ESP/lib/src/data/config/project_config.cpp +++ b/ESP/lib/src/data/config/project_config.cpp @@ -70,6 +70,7 @@ void ProjectConfig::save() mdnsConfigSave(); cameraConfigSave(); wifiConfigSave(); + wifiTxPowerConfigSave(); end(); // we call end() here to close the connection to the NVS partition, we only do this because we call ESP.restart() next. ESP.restart(); } diff --git a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp index 4311415..f1bdaa6 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -3,6 +3,7 @@ #define WIFIHANDLER_HPP #include #include +#include #include #include "data/StateManager/StateManager.hpp" #include "data/config/project_config.hpp" @@ -27,7 +28,7 @@ public: private: void setUpADHOC(); - void adhoc(const char *ssid, const char *password, uint8_t channel); + void adhoc(const char *ssid, uint8_t channel, const char *password = NULL); bool iniSTA(const char *ssid, const char *password, uint8_t channel, wifi_power_t power); std::string ssid; diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 51716c7..1ce1cf5 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -1,5 +1,4 @@ #include "WifiHandler.hpp" -#include WiFiHandler::WiFiHandler(ProjectConfig *configManager, StateManager *stateManager, @@ -35,7 +34,7 @@ void WiFiHandler::setupWifi() if (networks->empty()) { log_i("No networks found in config, trying the default one \n\r"); - if(this->iniSTA(this->ssid.c_str(), this->password.c_str(), this->channel, (wifi_power_t)txpower->power)) + if (this->iniSTA(this->ssid.c_str(), this->password.c_str(), this->channel, (wifi_power_t)txpower->power)) { return; } @@ -43,30 +42,32 @@ void WiFiHandler::setupWifi() { log_i("Could not connect to the hardcoded network, setting up ADHOC network \n\r"); this->setUpADHOC(); + return; } } - for(auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) + for (auto networkIterator = networks->begin(); networkIterator != networks->end(); ++networkIterator) { - if(this->iniSTA(networkIterator->ssid.c_str(), networkIterator->password.c_str(), networkIterator->channel, (wifi_power_t)networkIterator->power)) + if (this->iniSTA(networkIterator->ssid.c_str(), networkIterator->password.c_str(), networkIterator->channel, (wifi_power_t)networkIterator->power)) { return; } } - // at this point, we've tried every network, let's just setup adhoc + // at this point, we've tried every network, let's just setup adhoc log_i("We've gone through every network, each timed out. Trying to connect to hardcoded network: %s \n\r", this->ssid.c_str()); - if(this->iniSTA(this->ssid.c_str(), this->password.c_str(), this->channel, (wifi_power_t)txpower->power)) + if (this->iniSTA(this->ssid.c_str(), this->password.c_str(), this->channel, (wifi_power_t)txpower->power)) { log_i("Successfully connected to the hardcoded network. \n\r"); - } else + } + else { log_i("Could not connect to the hardcoded network, setting up adhoc. \n\r"); this->setUpADHOC(); } } -void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) +void WiFiHandler::adhoc(const char *ssid, uint8_t channel, const char *password) { stateManager->setState(WiFiState_e::WiFiState_ADHOC); log_i("\n[INFO]: Setting Access Point...\n"); @@ -84,28 +85,29 @@ void WiFiHandler::adhoc(const char *ssid, const char *password, uint8_t channel) void WiFiHandler::setUpADHOC() { log_i("\n[INFO]: Setting Access Point...\n"); - size_t ssidLen = strlen(configManager->getAPWifiConfig()->ssid.c_str()); - size_t passwordLen = strlen(configManager->getAPWifiConfig()->password.c_str()); - char ssid[ssidLen + 1]; - char password[passwordLen + 1]; - uint8_t channel = configManager->getAPWifiConfig()->channel; - if (ssidLen > 0 || passwordLen > 0) + size_t ssidLen = configManager->getAPWifiConfig()->ssid.length(); + size_t passwordLen = configManager->getAPWifiConfig()->password.length(); + if (ssidLen <= 0) { - strcpy(ssid, configManager->getAPWifiConfig()->ssid.c_str()); - strcpy(password, configManager->getAPWifiConfig()->password.c_str()); - channel = configManager->getAPWifiConfig()->channel; + this->adhoc("OpenIris", 1, "12345678"); + return; } - else + + if (passwordLen <= 0) { - strcpy(ssid, "OpenIris"); - strcpy(password, "12345678"); - channel = 1; + log_i("\n[INFO]: Configuring access point without a password\n"); + this->adhoc(configManager->getAPWifiConfig()->ssid.c_str(), + configManager->getAPWifiConfig()->channel); + return; } - this->adhoc(ssid, password, channel); + + this->adhoc(configManager->getAPWifiConfig()->ssid.c_str(), + configManager->getAPWifiConfig()->channel, + configManager->getAPWifiConfig()->password.c_str()); log_i("\n[INFO]: Configuring access point...\n"); - log_d("\n[DEBUG]: ssid: %s\n", ssid); - log_d("\n[DEBUG]: password: %s\n", password); - log_d("\n[DEBUG]: channel: %d\n", channel); + log_d("\n[DEBUG]: ssid: %s\n", configManager->getAPWifiConfig()->ssid.c_str()); + log_d("\n[DEBUG]: password: %s\n", configManager->getAPWifiConfig()->password.c_str()); + log_d("\n[DEBUG]: channel: %d\n", configManager->getAPWifiConfig()->channel); } bool WiFiHandler::iniSTA(const char *ssid, const char *password, uint8_t channel, wifi_power_t power) @@ -117,9 +119,9 @@ bool WiFiHandler::iniSTA(const char *ssid, const char *password, uint8_t channel stateManager->setState(WiFiState_e::WiFiState_Connecting); log_i("Trying to connect to: %s \n\r", ssid); - + WiFi.begin(ssid, password, channel); - while(WiFi.status() != WL_CONNECTED) + while (WiFi.status() != WL_CONNECTED) { progress++; currentMillis = millis(); @@ -130,7 +132,7 @@ bool WiFiHandler::iniSTA(const char *ssid, const char *password, uint8_t channel stateManager->setState(WiFiState_e::WiFiState_Error); log_e("Connection to: %s TIMEOUT \n\r", ssid); return false; - } + } } stateManager->setState(WiFiState_e::WiFiState_Connected); diff --git a/ESP/lib/src/network/api/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp index 0b1bd18..1428284 100644 --- a/ESP/lib/src/network/api/webserverHandler.cpp +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -27,7 +27,6 @@ void APIServer::begin() log_d("API URL: %s", buffer); server->on(buffer, 0b01111111, [&](AsyncWebServerRequest *request) { handleRequest(request); }); - server->begin(); } diff --git a/ESP/tools/versioning b/ESP/tools/versioning index 99f9f07..fc42ce4 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -502 \ No newline at end of file +504 \ No newline at end of file From d7024a256be047c86a2759edc700cf516983fb03 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 5 Dec 2022 16:24:27 +0000 Subject: [PATCH 152/153] update - set hostname from config in wifihandler --- ESP/lib/src/network/WifiHandler/wifiHandler.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp index 1ce1cf5..f53f686 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -120,6 +120,9 @@ bool WiFiHandler::iniSTA(const char *ssid, const char *password, uint8_t channel stateManager->setState(WiFiState_e::WiFiState_Connecting); log_i("Trying to connect to: %s \n\r", ssid); + auto mdnsConfig = configManager->getMDNSConfig(); + WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE); // need to call before setting hostname + WiFi.setHostname(mdnsConfig->hostname.c_str()); WiFi.begin(ssid, password, channel); while (WiFi.status() != WL_CONNECTED) { From 311fada522e0aba77a23795ee367fd2c30100749 Mon Sep 17 00:00:00 2001 From: ZanzyTHEbar Date: Mon, 5 Dec 2022 18:43:52 +0000 Subject: [PATCH 153/153] update - temporarily set GET requests on TxPowerLevel --- ESP/lib/src/network/api/baseAPI/baseAPI.cpp | 19 ++++++++++++++++--- ESP/tools/versioning | 2 +- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp index 9d288b0..ec60e1b 100644 --- a/ESP/lib/src/network/api/baseAPI/baseAPI.cpp +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -216,7 +216,21 @@ void BaseAPI::setWiFiTXPower(AsyncWebServerRequest *request) { case GET: { - request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + int params = request->params(); + + uint8_t txPower = 0; + + for (int i = 0; i < params; i++) + { + AsyncWebParameter *param = request->getParam(i); + if (param->name() == "txPower") + { + txPower = atoi(param->value().c_str()); + } + } + projectConfig->setWiFiTxPower(&txPower, true); + projectConfig->wifiTxPowerConfigSave(); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. TX Power has been set.\"}"); break; } case POST: @@ -342,13 +356,12 @@ void BaseAPI::restartCamera(AsyncWebServerRequest *request) request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Camera had been restarted.\"}"); } - void BaseAPI::ping(AsyncWebServerRequest *request) { request->send(200, MIMETYPE_JSON, "{\"msg\": \"ok\" }"); } -void BaseAPI::save(AsyncWebServerRequest *request) +void BaseAPI::save(AsyncWebServerRequest *request) { projectConfig->save(); request->send(200, MIMETYPE_JSON, "{\"msg\": \"ok\" }"); diff --git a/ESP/tools/versioning b/ESP/tools/versioning index fc42ce4..eed0d1a 100644 --- a/ESP/tools/versioning +++ b/ESP/tools/versioning @@ -1 +1 @@ -504 \ No newline at end of file +506 \ No newline at end of file