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": {} + } +} diff --git a/ESP/.gitignore b/ESP/.gitignore index 10a4823..31f4c8f 100644 --- a/ESP/.gitignore +++ b/ESP/.gitignore @@ -1,3 +1,4 @@ -.pio -.vscode -build \ No newline at end of file +.pio/ +.vscode/ +build/ +*.log 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}) 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 diff --git a/ESP/lib/src/data/Observer/Observer.h b/ESP/lib/src/data/Observer/Observer.h deleted file mode 100644 index e87c831..0000000 --- a/ESP/lib/src/data/Observer/Observer.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once -#include - -namespace ObserverEvent -{ - enum Event - { - configLoaded = 1, - deviceConfigUpdated = 2, - cameraConfigUpdated = 3, - networksConfigUpdated = 4, - }; -} - -class IObserver -{ -public: - void update(ObserverEvent::Event event){}; -}; - -class ISubject -{ -private: - std::set observers; - -public: - void attach(IObserver *observer) - { - this->observers.insert(observer); - } - - void detach(IObserver *observer) - { - this->observers.erase(observer); - } - - void notify(ObserverEvent::Event event) - { - std::set::iterator iterator = observers.begin(); - - while (iterator != observers.end()) - { - (*iterator)->update(event); - ++iterator; - } - } -}; \ No newline at end of file diff --git a/ESP/lib/src/data/StateManager/StateManager.cpp b/ESP/lib/src/data/StateManager/StateManager.cpp index d1fae57..ec64375 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 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 9fc7e6b..039563e 100644 --- a/ESP/lib/src/data/StateManager/StateManager.hpp +++ b/ESP/lib/src/data/StateManager/StateManager.hpp @@ -6,74 +6,100 @@ * 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, + _LEDBlinkFast, + _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_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, + MDNSState_QueryStarted, + MDNSState_QueryComplete + }; - 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 }; }; @@ -107,12 +133,20 @@ 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 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 ledStateManager; +extern StateManager streamStateManager; #endif // STATEMANAGER_HPP \ No newline at end of file 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..de8c625 --- /dev/null +++ b/ESP/lib/src/data/config/project_config.cpp @@ -0,0 +1,401 @@ +#include "project_config.hpp" + +ProjectConfig::ProjectConfig(const std::string &name, + const std::string &mdnsName) : _name(std::move(name)), + _mdnsName(std::move(mdnsName)), + _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::initConfig() +{ + 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"); + + /* + * 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 = { + "12345678", + 3232, + }; + + if (_mdnsName.empty()) + { + log_e("MDNS name is null\n Autoassigning name to 'openiristracker'"); + _mdnsName = "openiristracker"; + } + this->config.mdns = { + _mdnsName, + "", + }; + + log_i("MDNS name: %s", _mdnsName.c_str()); + + this->config.ap_network = { + "", + "", + 1, + false, + }; + + this->config.camera = { + .vflip = 0, + .href = 0, + .framesize = 4, + .quality = 7, + .brightness = 2, + }; +} + +void ProjectConfig::save() +{ + log_d("Saving project config"); + deviceConfigSave(); + 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(); +} + +void ProjectConfig::wifiConfigSave() +{ + log_d("Saving wifi config"); + + /* WiFi Config */ + putInt("networkCount", this->config.networks.size()); + + 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 < 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); + 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()); + putUInt(channel.c_str(), this->config.networks[i].channel); + putUInt(power.c_str(), this->config.networks[i].power); + } + + /* 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"); +} + +void ProjectConfig::deviceConfigSave() +{ + /* Device Config */ + putString("OTAPassword", this->config.device.OTAPassword.c_str()); + putInt("OTAPort", this->config.device.OTAPort); +} + +void ProjectConfig::mdnsConfigSave() +{ + /* Device Config */ + putString("hostname", this->config.mdns.hostname.c_str()); + putString("service", this->config.mdns.service.c_str()); +} + +void ProjectConfig::wifiTxPowerConfigSave() +{ + /* Device Config */ + putInt("power", this->config.txpower.power); +} + +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); +} + +bool ProjectConfig::reset() +{ + 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; + } + + /* Device Config */ + this->config.device.OTAPassword = getString("OTAPassword", "12345678").c_str(); + this->config.device.OTAPort = getInt("OTAPort", 3232); + + /* MDNS Config */ + 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); + /* 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]; + 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); + 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()); + 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( + temp_1, + 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 + } + + /* 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); + + this->_already_loaded = true; + this->notify(ObserverEvent::configLoaded); +} + +//********************************************************************************************************************** +//* +//! DeviceConfig +//* +//********************************************************************************************************************** +void ProjectConfig::setDeviceConfig(const std::string &OTAPassword, int *OTAPort, bool shouldNotify) +{ + log_d("Updating device config"); + this->config.device.OTAPassword.assign(OTAPassword); + this->config.device.OTAPort = *OTAPort; + + if (shouldNotify) + 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"); + 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); +} + +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) + { + 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) + { + // 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].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 + this->config.networks.emplace_back( + networkName, + ssid, + password, + *channel, + *power, + false); + } + + 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; + + log_d("Updating access point config"); + if (shouldNotify) + 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); + 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}", + this->vflip, + this->framesize, + this->href, + this->quality, + this->brightness); + return json; +} + +std::string ProjectConfig::WiFiConfig_t::toRepresentation() +{ + std::string json = Helpers::format_string( + "{\"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; } +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 new file mode 100644 index 0000000..388f5b0 --- /dev/null +++ b/ESP/lib/src/data/config/project_config.hpp @@ -0,0 +1,123 @@ +#pragma once +#ifndef PROJECT_CONFIG_HPP +#define PROJECT_CONFIG_HPP +#include +#include +#include +#include + +#include "data/utilities/Observer.hpp" +#include "data/utilities/helpers.hpp" + +class ProjectConfig : public Preferences, public ISubject +{ +public: + ProjectConfig(const std::string &name = std::string(), + const std::string &mdnsName = std::string()); + virtual ~ProjectConfig(); + void load(); + void save(); + void wifiConfigSave(); + void cameraConfigSave(); + void deviceConfigSave(); + void mdnsConfigSave(); + void wifiTxPowerConfigSave(); + bool reset(); + void initConfig(); + + struct DeviceConfig_t + { + std::string OTAPassword; + int OTAPort; + std::string toRepresentation(); + }; + + struct MDNSConfig_t + { + std::string hostname; + std::string service; + std::string toRepresentation(); + }; + + struct CameraConfig_t + { + uint8_t vflip; + uint8_t href; + uint8_t framesize; + uint8_t quality; + uint8_t brightness; + + 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, + uint8_t power, + bool adhoc) : name(std::move(name)), + ssid(std::move(ssid)), + password(std::move(password)), + channel(channel), + adhoc(adhoc), + power(power) {} + std::string name; + std::string ssid; + std::string password; + uint8_t channel; + uint8_t power; + bool adhoc; + + std::string toRepresentation(); + }; + + struct AP_WiFiConfig_t + { + std::string ssid; + std::string password; + uint8_t channel; + bool adhoc; + std::string toRepresentation(); + }; + + struct WiFiTxPower_t + { + uint8_t power; + std::string toRepresentation(); + }; + + struct TrackerConfig_t + { + DeviceConfig_t device; + CameraConfig_t camera; + std::vector networks; + AP_WiFiConfig_t ap_network; + MDNSConfig_t mdns; + WiFiTxPower_t txpower; + }; + + DeviceConfig_t *getDeviceConfig(); + CameraConfig_t *getCameraConfig(); + 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, 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; + std::string _name; + std::string _mdnsName; + bool _already_loaded; +}; + +#endif // PROJECT_CONFIG_HPP \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/Observer.hpp b/ESP/lib/src/data/utilities/Observer.hpp new file mode 100644 index 0000000..f9265dd --- /dev/null +++ b/ESP/lib/src/data/utilities/Observer.hpp @@ -0,0 +1,50 @@ +#pragma once +#ifndef OBSERVER_HPP +#define OBSERVER_HPP +#include + +namespace ObserverEvent +{ + enum Event + { + configLoaded = 1, + deviceConfigUpdated = 2, + cameraConfigUpdated = 3, + networksConfigUpdated = 4, + mdnsConfigUpdated = 5, + wifiTxPowerUpdated = 6, + }; +} + +class IObserver +{ +public: + virtual void update(ObserverEvent::Event event) = 0; +}; + +class ISubject +{ +private: + std::set observers; + +public: + void attach(IObserver *observer) + { + this->observers.insert(observer); + } + + void detach(IObserver *observer) + { + this->observers.erase(observer); + } + + void notify(ObserverEvent::Event event) + { + for (auto observer : this->observers) + { + observer->update(event); + } + } +}; + +#endif // !OBSERVER_HPP \ No newline at end of file diff --git a/ESP/lib/src/data/utilities/enuminheritance.hpp b/ESP/lib/src/data/utilities/enuminheritance.hpp new file mode 100644 index 0000000..b26aecf --- /dev/null +++ b/ESP/lib/src/data/utilities/enuminheritance.hpp @@ -0,0 +1,49 @@ +#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); diff --git a/ESP/lib/src/data/utilities/helpers.cpp b/ESP/lib/src/data/utilities/helpers.cpp new file mode 100644 index 0000000..52af448 --- /dev/null +++ b/ESP/lib/src/data/utilities/helpers.cpp @@ -0,0 +1,99 @@ +#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(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. */ + tokens.emplace_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.emplace_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; +} + +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 new file mode 100644 index 0000000..0f1d0a4 --- /dev/null +++ b/ESP/lib/src/data/utilities/helpers.hpp @@ -0,0 +1,37 @@ +#ifndef HELPERS_HPP +#define HELPERS_HPP +#include +#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); + + /// @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/data/utilities/makeunique.hpp b/ESP/lib/src/data/utilities/makeunique.hpp new file mode 100644 index 0000000..3b33374 --- /dev/null +++ b/ESP/lib/src/data/utilities/makeunique.hpp @@ -0,0 +1,51 @@ +#pragma once +#ifndef MAKE_UNIQUE_HPP +#define MAKE_UNIQUE_HPP +#include +#include +#include +#include + +/** + * @brief override the STD namespace to add make_unique function + * + * @tparam T + * @tparam Args + * @return std::unique_ptr + */ +namespace std +{ + template + struct _Unique_if + { + 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; +} + +#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..aca862a --- /dev/null +++ b/ESP/lib/src/data/utilities/network_utilities.cpp @@ -0,0 +1,76 @@ +#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 + my_delay(0.1); + 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(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 + //! 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.02); // delay 20ms + } + 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(); + my_delay(0.02); + } + 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 > 0; 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 new file mode 100644 index 0000000..a26db42 --- /dev/null +++ b/ESP/lib/src/data/utilities/network_utilities.hpp @@ -0,0 +1,17 @@ +#pragma once +#ifndef UTILITIES_hpp +#define UTILITIES_hpp +#include +#include +#include +#include "mbedtls/md.h" +namespace Network_Utilities +{ + bool LoopWifiScan(); + void SetupWifiScan(); + 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/io/LEDManager/LEDManager.cpp b/ESP/lib/src/io/LEDManager/LEDManager.cpp index 7a35e9d..cbe7a75 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.cpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.cpp @@ -1,39 +1,126 @@ #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}}, + {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. + +LEDManager::LEDManager(byte pin) : _ledPin(pin), + _previousMillis(0), + _ledState(false) {} LEDManager::~LEDManager() {} void LEDManager::begin() { - pinMode(_ledPin, OUTPUT); - onOff(false); - - /* for (auto &led : _leds) - { - if (led > 0) - { - pinMode(led, OUTPUT); - } - } */ + pinMode(_ledPin, OUTPUT); + onOff(false); } +/** + * @brief Control the LED + * @details This function must be called in the main loop + * + */ +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 + { + _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"); + stateManager->setState(LEDStates_e::_LEDOff); // Set the state to off + onOff(false); +} + +/** + * @brief Turn the LED on or off + * + * @param state + */ void LEDManager::onOff(bool state) const { - digitalWrite(_ledPin, state); + digitalWrite(_ledPin, state); } -void LEDManager::blink(unsigned long time) +/** + * @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 number of times to blink + * @param delayTime delay between each blink + */ +void LEDManager::blink(StateManager *stateManager) { - unsigned long currentMillis = millis(); - if (currentMillis - _previousMillis >= time) - { - _previousMillis = currentMillis; - _ledState = !_ledState; - onOff(_ledState); - } -} -void LEDManager::displayStatus() -{ -} \ No newline at end of file + if (ledStateMap.find(stateManager->getCurrentState()) != ledStateMap.end()) + { + BlinkPatterns_t 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 70f09e8..2966f1a 100644 --- a/ESP/lib/src/io/LEDManager/LEDManager.hpp +++ b/ESP/lib/src/io/LEDManager/LEDManager.hpp @@ -1,22 +1,33 @@ #ifndef LEDMANAGER_HPP #define LEDMANAGER_HPP #include +#include +#include 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 handleLED(StateManager *stateManager); + void onOff(bool state) const; + void blink(StateManager *stateManager); private: - byte _ledPin; - unsigned long _previousMillis; - bool _ledState; + byte _ledPin; + unsigned long _previousMillis; + bool _ledState; + + struct BlinkPatterns_t + { + int times; + int delayTime; + }; + + typedef std::unordered_map ledStateMap_t; + static ledStateMap_t ledStateMap; }; #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 new file mode 100644 index 0000000..bc8a670 --- /dev/null +++ b/ESP/lib/src/io/SerialManager/serialmanager.cpp @@ -0,0 +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), + serReader(std::make_unique()) +{ +} + +SerialManager::~SerialManager() {} + +void SerialManager::begin() +{ + 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" + + //! 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; + } +} + +void SerialManager::handleSerial() +{ + 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()); + + 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 new file mode 100644 index 0000000..3d94a5d --- /dev/null +++ b/ESP/lib/src/io/SerialManager/serialmanager.hpp @@ -0,0 +1,43 @@ +#pragma once +#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 +{ +public: + SerialManager(ProjectConfig *projectConfig); + virtual ~SerialManager(); + + void begin(); + void handleSerial(); + + friend void readStr(const char *inStr); + +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/io/camera/cameraHandler.cpp b/ESP/lib/src/io/camera/cameraHandler.cpp index edfc086..98b076d 100644 --- a/ESP/lib/src/io/camera/cameraHandler.cpp +++ b/ESP/lib/src/io/camera/cameraHandler.cpp @@ -1,109 +1,167 @@ #include "cameraHandler.hpp" -int CameraHandler::setupCamera() +CameraHandler::CameraHandler(ProjectConfig *configManager, + StateManager *stateManager) : configManager(configManager), + stateManager(stateManager) {} + +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; + 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 = 16500000; // 10000000 stable, + // 16500000 optimal, + // 20000000 max fps +} - 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; +void CameraHandler::setupBasicResolution() +{ + config.pixel_format = PIXFORMAT_JPEG; + config.frame_size = FRAMESIZE_240X240; + if (!psramFound()) + { + log_e("Did not find psram, setting lower image quality"); + config.jpeg_quality = 1; + config.fb_count = 1; + return; + } - 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; - } + 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; +} - esp_err_t err = esp_camera_init(&config); +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 + 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) +bool CameraHandler::setupCamera() +{ + this->setupCameraPinout(); + this->setupBasicResolution(); + esp_err_t hasCameraBeenInitialized = esp_camera_init(&config); - 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 (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"); + stateManager->setState(LEDStates_e::_Camera_Error); + return false; + } + + this->setupCameraSensor(); + stateManager->setState(LEDStates_e::_Camera_Success); + 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); + camera_sensor->set_agc_gain(camera_sensor, cameraConfig->brightness); +} + +void CameraHandler::update(ObserverEvent::Event event) +{ + switch (event) + { + case ObserverEvent::Event::configLoaded: + this->setupCamera(); + this->loadConfigData(); + break; + case ObserverEvent::Event::cameraConfigUpdated: + this->loadConfigData(); + break; + default: + break; + } } 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); +} + +//! either hardware(1) or software(0) +void CameraHandler::resetCamera(bool type) +{ + if (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 + digitalWrite(PWDN_GPIO_NUM, LOW); + 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.05); + 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 3448c2a..ffd2d93 100644 --- a/ESP/lib/src/io/camera/cameraHandler.hpp +++ b/ESP/lib/src/io/camera/cameraHandler.hpp @@ -1,17 +1,32 @@ #pragma once -#include "esp_camera.h" #include +#include +#include "data/utilities/Observer.hpp" +#include "data/utilities/network_utilities.hpp" +#include "data/config/project_config.hpp" +#include "data/StateManager/StateManager.hpp" -class CameraHandler +class CameraHandler : public IObserver { private: - sensor_t *camera_sensor; - camera_config_t config; + sensor_t *camera_sensor; + camera_config_t config; + ProjectConfig *configManager; + StateManager *stateManager; public: - 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); -}; \ No newline at end of file + CameraHandler(ProjectConfig *configManager, StateManager *stateManager); + 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/lib/src/logo/logo.hpp b/ESP/lib/src/logo/logo.hpp new file mode 100644 index 0000000..2512ddd --- /dev/null +++ b/ESP/lib/src/logo/logo.hpp @@ -0,0 +1,67 @@ + +namespace Logo +{ + inline 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 diff --git a/ESP/lib/src/network/OTA/OTA.cpp b/ESP/lib/src/network/OTA/OTA.cpp new file mode 100644 index 0000000..9f18de7 --- /dev/null +++ b/ESP/lib/src/network/OTA/OTA.cpp @@ -0,0 +1,75 @@ +#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.c_str(), "") == 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"); + auto mdnsConfig = _deviceConfig->getMDNSConfig(); + ArduinoOTA.setHostname(mdnsConfig->hostname.c_str()); + ArduinoOTA.begin(); + _bootTimestamp = millis(); +} + +void OTA::HandleOTAUpdate() +{ + if (_isOtaEnabled) + { + if (_bootTimestamp + (60000 * 5) < millis()) + { + // 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; + } + 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 1712993..0a60e7d 100644 --- a/ESP/lib/src/network/OTA/OTA.hpp +++ b/ESP/lib/src/network/OTA/OTA.hpp @@ -1,54 +1,20 @@ -#pragma once +#ifndef OTA_HPP +#define OTA_HPP #include +#include +#include "data/config/project_config.hpp" class OTA { -private: - bool isOTAEnabled = false; - public: - void SetupOTA(const char *OTAPassword, uint16_t OTAServerPort) - { - log_i("Setting up OTA updates"); + OTA(ProjectConfig *_deviceConfig); + virtual ~OTA(); + void SetupOTA(); + void HandleOTAUpdate(); - if (OTAPassword == nullptr) - { - log_e("THE PASSWORD IS REQUIRED, [[ABORTING]]"); - return; - } - ArduinoOTA.setPort(OTAServerPort); - isOTAEnabled = true; - - 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() - { - if (isOTAEnabled) - { - ArduinoOTA.handle(); - } - } -}; \ No newline at end of file +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 c656c5a..f1bdaa6 100644 --- a/ESP/lib/src/network/WifiHandler/WifiHandler.hpp +++ b/ESP/lib/src/network/WifiHandler/WifiHandler.hpp @@ -1,8 +1,39 @@ #pragma once +#ifndef WIFIHANDLER_HPP +#define WIFIHANDLER_HPP +#include +#include +#include #include -#include "../../data/StateManager/StateManager.hpp" +#include "data/StateManager/StateManager.hpp" +#include "data/config/project_config.hpp" +#include "data/utilities/helpers.hpp" -namespace WiFiHandler +class WiFiHandler { - void setupWifi(const char *ssid, const char *password, StateManager *stateManager); -} \ No newline at end of file +public: + WiFiHandler(ProjectConfig *configManager, + StateManager *stateManager, + const std::string &ssid, + const std::string &password, + uint8_t channel); + virtual ~WiFiHandler(); + void setupWifi(); + + ProjectConfig *configManager; + StateManager *stateManager; + ProjectConfig::WiFiTxPower_t *txpower; + + bool _enable_adhoc; + +private: + void setUpADHOC(); + 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; + 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 86eda8e..f53f686 100644 --- a/ESP/lib/src/network/WifiHandler/wifiHandler.cpp +++ b/ESP/lib/src/network/WifiHandler/wifiHandler.cpp @@ -1,39 +1,147 @@ #include "WifiHandler.hpp" -void WiFiHandler::setupWifi(const char *ssid, const char *password, StateManager *stateManager) +WiFiHandler::WiFiHandler(ProjectConfig *configManager, + StateManager *stateManager, + const std::string &ssid, + 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() { - log_d("Initializing connection to wifi"); + 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); - WiFi.mode(WIFI_STA); - WiFi.setSleep(WIFI_PS_NONE); - WiFi.begin(ssid, password); - WiFi.setTxPower(WIFI_POWER_5dBm); + log_i("Initializing connection to wifi \n\r"); + stateManager->setState(WiFiState_e::WiFiState_Connecting); - log_d("connecting"); - int time_spent_connecting = 0; - int connection_timeout = 6400; - int wifi_status = WiFi.status(); + std::vector *networks = configManager->getWifiConfigs(); - while (time_spent_connecting < connection_timeout || wifi_status != WL_CONNECTED) - { - wifi_status = WiFi.status(); - Serial.print("."); - stateManager->setState((ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connecting)); - time_spent_connecting += 1600; - delay(1600); - } + 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)) + { + return; + } + else + { + log_i("Could not connect to the hardcoded network, setting up ADHOC network \n\r"); + this->setUpADHOC(); + 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; - } -} \ No newline at end of file + 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)) + { + return; + } + } + + // 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(); + } +} + +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"); + 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()); + // 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_t)txpower->power); +} + +void WiFiHandler::setUpADHOC() +{ + log_i("\n[INFO]: Setting Access Point...\n"); + size_t ssidLen = configManager->getAPWifiConfig()->ssid.length(); + size_t passwordLen = configManager->getAPWifiConfig()->password.length(); + if (ssidLen <= 0) + { + this->adhoc("OpenIris", 1, "12345678"); + return; + } + + if (passwordLen <= 0) + { + log_i("\n[INFO]: Configuring access point without a password\n"); + this->adhoc(configManager->getAPWifiConfig()->ssid.c_str(), + configManager->getAPWifiConfig()->channel); + return; + } + + 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", 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) +{ + unsigned long currentMillis = millis(); + unsigned long startingMillis = currentMillis; + int connectionTimeout = 30000; // 30 seconds + int progress = 0; + + 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) + { + progress++; + currentMillis = millis(); + Helpers::update_progress_bar(progress, 100); + delay(301); + if ((currentMillis - startingMillis) >= connectionTimeout) + { + stateManager->setState(WiFiState_e::WiFiState_Error); + log_e("Connection to: %s TIMEOUT \n\r", ssid); + return false; + } + } + + 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; +} 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..ec60e1b --- /dev/null +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.cpp @@ -0,0 +1,368 @@ +#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) : server(new AsyncWebServer(CONTROL_PORT)), + projectConfig(projectConfig), + camera(camera), + WiFiStateManager(WiFiStateManager), + api_url(api_url) {} + +BaseAPI::~BaseAPI() {} + +void BaseAPI::begin() +{ + //! 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::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 +//********************************************************************************************* +void BaseAPI::setWiFi(AsyncWebServerRequest *request) +{ + switch (_networkMethodsMap_enum[request->method()]) + { + case POST: + { + int params = request->params(); + std::string networkName; + 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); + for (int i = 0; i < params; i++) + { + AsyncWebParameter *param = request->getParam(i); + if (param->name() == "networkName") + { + networkName = param->value().c_str(); + } + else if (param->name() == "ssid") + { + ssid = param->value().c_str(); + } + else if (param->name() == "password") + { + password = param->value().c_str(); + } + else if (param->name() == "channel") + { + 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()); + } + + 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, &power, adhoc, true); + + /* if (WiFiStateManager->getCurrentState() == WiFiState_e::WiFiState_ADHOC) + { + projectConfig->setAPWifiConfig(ssid, password, &channel, adhoc, true); + } + else + { + + } */ + + 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; + } + } +} + +void BaseAPI::getJsonConfig(AsyncWebServerRequest *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) +{ + 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++) + { + AsyncWebParameter *param = request->getParam(i); + if (param->name() == "hostname") + { + hostname = param->value().c_str(); + } + else if (param->name() == "service") + { + service = param->value().c_str(); + } + else if (param->name() == "ota_port") + { + ota_port = atoi(param->value().c_str()); + } + else if (param->name() == "ota_password") + { + 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); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Done. Device Config has been set.\"}"); + } + } +} + +void BaseAPI::setWiFiTXPower(AsyncWebServerRequest *request) +{ + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + 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: + { + 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()]) + { + case GET: + { + 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"); + projectConfig->reset(); + request->send(200, MIMETYPE_JSON, "{\"msg\":\"Factory Reset\"}"); + } + default: + { + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Request\"}"); + break; + } + } +} + +//********************************************************************************************* +//! Camera Command Functions +//********************************************************************************************* + +void BaseAPI::setCamera(AsyncWebServerRequest *request) +{ + switch (_networkMethodsMap_enum[request->method()]) + { + case GET: + { + // create temporary variables to store the values + uint8_t temp_camera_framesize = 0; + 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(); + //! 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); + if (param->name() == "framesize") + { + temp_camera_framesize = (uint8_t)param->value().toInt(); + } + else if (param->name() == "vflip") + { + temp_camera_vflip = (uint8_t)param->value().toInt(); + } + else if (param->name() == "hflip") + { + temp_camera_hflip = (uint8_t)param->value().toInt(); + } + else if (param->name() == "quality") + { + temp_camera_quality = (uint8_t)param->value().toInt(); + } + else if (param->name() == "brightness") + { + 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); + + 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; + } + } +} + +void BaseAPI::restartCamera(AsyncWebServerRequest *request) +{ + bool mode = (bool)atoi(request->arg("mode").c_str()); + camera->resetCamera(mode); + + 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) +{ + projectConfig->save(); + request->send(200, MIMETYPE_JSON, "{\"msg\": \"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 new file mode 100644 index 0000000..7dee85c --- /dev/null +++ b/ESP/lib/src/network/api/baseAPI/baseAPI.hpp @@ -0,0 +1,114 @@ +#ifndef BASEAPI_HPP +#define BASEAPI_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" + +#include "data/config/project_config.hpp" +#include "data/StateManager/StateManager.hpp" +#include "io/camera/cameraHandler.hpp" + +class BaseAPI +{ +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; + +protected: + /* Commands */ + void setWiFi(AsyncWebServerRequest *request); + void setWiFiTXPower(AsyncWebServerRequest *request); + void getJsonConfig(AsyncWebServerRequest *request); + 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); + void restartCamera(AsyncWebServerRequest *request); + + /* Route Command types */ + using route_method = void (BaseAPI::*)(AsyncWebServerRequest *); + typedef std::unordered_map route_t; + typedef std::unordered_map route_map_t; + + 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, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url); + + 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/webserverHandler.cpp b/ESP/lib/src/network/api/webserverHandler.cpp new file mode 100644 index 0000000..1428284 --- /dev/null +++ b/ESP/lib/src/network/api/webserverHandler.cpp @@ -0,0 +1,117 @@ +#include "webserverHandler.hpp" + +//********************************************************************************************* +//! API Server +//********************************************************************************************* + +APIServer::APIServer(int CONTROL_PORT, + ProjectConfig *projectConfig, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url) : BaseAPI(CONTROL_PORT, + projectConfig, + camera, + WiFiStateManager, + api_url) {} + +APIServer::~APIServer() {} + +void APIServer::begin() +{ + log_d("Initializing REST API Server"); + 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() +{ + routes.emplace("wifi", &APIServer::setWiFi); + routes.emplace("resetConfig", &APIServer::factoryReset); + 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); + 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 + addRouteMap("builtin", routes, indexes); // add new route map to the route_map +} + +void APIServer::findParam(AsyncWebServerRequest *request, const char *param, std::string &value) +{ + if (request->hasParam(param)) + { + value = request->getParam(param)->value().c_str(); + } +} + +/** + * @brief Add a command handler to the API + * + * @param index + * @param funct + * @param indexes \c std::vector a list of the routes of the command handlers + * + * @return void + * + */ +void APIServer::addRouteMap(const std::string &index, route_t route, std::vector &indexes) +{ + route_map.emplace(index, route); + + for (const auto &key : route) + { + indexes.emplace_back(key.first); // add the route to the list of routes - use emplace_back to avoid copying + } +} + +void APIServer::handleRequest(AsyncWebServerRequest *request) +{ + try + { + // Get the route + log_i("Request URL: %s", request->url().c_str()); + log_i("Request: %s", request->pathArg(0).c_str()); + log_i("Request: %s", request->pathArg(1).c_str()); + + auto it_map = route_map.find(request->pathArg(0).c_str()); + auto it_method = it_map->second.find(request->pathArg(1).c_str()); + + 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 + { + log_e("Invalid Command"); + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Command\"}"); + return; + } + } + else + { + log_e("Invalid Map Index"); + request->send(400, MIMETYPE_JSON, "{\"msg\":\"Invalid Map Index\"}"); + return; + } + } + catch (...) + { + log_e("Error handling request"); + } +} diff --git a/ESP/lib/src/network/api/webserverHandler.hpp b/ESP/lib/src/network/api/webserverHandler.hpp new file mode 100644 index 0000000..adb0b03 --- /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, + ProjectConfig *projectConfig, + CameraHandler *camera, + StateManager *WiFiStateManager, + const std::string &api_url); + + virtual ~APIServer(); + void begin(); + void setupServer(); + 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: + std::vector indexes; +}; +#endif // WEBSERVERHANDLER_HPP diff --git a/ESP/lib/src/network/mDNS/MDNSManager.cpp b/ESP/lib/src/network/mDNS/MDNSManager.cpp index 6d87a2c..2b05bc2 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.cpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.cpp @@ -1,17 +1,38 @@ #include "MDNSManager.hpp" -void MDNSHandler::setupMDNS(const char *trackerName, StateManager *stateManager) +MDNSHandler::MDNSHandler(StateManager *stateManager, + ProjectConfig *configManager) : stateManager(stateManager), + configManager(configManager) {} + +bool MDNSHandler::startMDNS() { - if (MDNS.begin(trackerName)) - { - stateManager->setState(ProgramStates::DeviceStates::MDNSState_e::MDNSState_Started); - MDNS.addService("openIrisTracker", "tcp", 80); - MDNS.addServiceTxt("openIrisTracker", "tcp", "stream_port", String(80)); - log_d("MDNS initialized!"); - } - else - { - stateManager->setState(ProgramStates::DeviceStates::MDNSState_e::MDNSState_Error); - log_e("Error initializing MDNS"); - } + 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_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) +{ + switch (event) + { + case ObserverEvent::Event::mdnsConfigUpdated: + MDNS.end(); + startMDNS(); + break; + default: + break; + } } \ 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 f0cf69c..b71f97f 100644 --- a/ESP/lib/src/network/mDNS/MDNSManager.hpp +++ b/ESP/lib/src/network/mDNS/MDNSManager.hpp @@ -1,7 +1,22 @@ -#pragma once +#ifndef MDNSHANDLER_HPP +#define MDNSHANDLER_HPP #include -#include "../../data/StateManager/StateManager.hpp" -namespace MDNSHandler +#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 { - void setupMDNS(const char *trackerName, StateManager *stateManager); -} \ No newline at end of file +private: + StateManager *stateManager; + ProjectConfig *configManager; + +public: + MDNSHandler(StateManager *stateManager, + ProjectConfig *configManager); + bool startMDNS(); + void update(ObserverEvent::Event event); +}; + +#endif // MDNSHANDLER_HPP \ 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 72d6141..bb98b48 100644 --- a/ESP/lib/src/network/stream/streamServer.cpp +++ b/ESP/lib/src/network/stream/streamServer.cpp @@ -6,105 +6,108 @@ 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[256]; - 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() { - 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; - config.ctrl_port = this->STREAM_SERVER_PORT; - config.stack_size = 20480; + // 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; + config.stack_size = 20480; - 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; - } -} \ No newline at end of file + if (status != ESP_OK) + return -1; + else + { + httpd_register_uri_handler(camera_stream, &stream_page); + 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 bf66f84..b226590 100644 --- a/ESP/lib/src/network/stream/streamServer.hpp +++ b/ESP/lib/src/network/stream/streamServer.hpp @@ -1,24 +1,34 @@ #pragma once +#ifndef STREAM_SERVER_HPP +#define STREAM_SERVER_HPP #define PART_BOUNDARY "123456789000000000000987654321" #include -#include "esp_camera.h" -#include "esp_http_server.h" +#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); + 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(); -}; \ No newline at end of file + StreamServer(int STREAM_PORT) : STREAM_SERVER_PORT(STREAM_PORT) {} + int startStreamServer(); +}; + +#endif // STREAM_SERVER_HPP diff --git a/ESP/lib/src/network/webserver/webserverHandler.cpp b/ESP/lib/src/network/webserver/webserverHandler.cpp index 94ca8c9..e69de29 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.cpp +++ b/ESP/lib/src/network/webserver/webserverHandler.cpp @@ -1,39 +0,0 @@ -#include "webserverHandler.hpp" - -APIServer::APIServer(int CONTROL_PORT, CameraHandler *cameraHandler) -{ - this->server = new AsyncWebServer(CONTROL_PORT); - this->cameraHandler = cameraHandler; -} - -void APIServer::startAPIServer() -{ - this->server->on( - "/control", - HTTP_GET, - std::bind(&APIServer::command_handler, this, std::placeholders::_1)); - - log_d("Initializing web server"); - this->server->begin(); -} - -void APIServer::command_handler(AsyncWebServerRequest *request) -{ - if (request->hasParam("framesize")) - { - 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())); - } - - request->send(200); -} \ 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 4b88f79..e69de29 100644 --- a/ESP/lib/src/network/webserver/webserverHandler.hpp +++ b/ESP/lib/src/network/webserver/webserverHandler.hpp @@ -1,19 +0,0 @@ -#pragma once -#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; - -public: - APIServer(int CONTROL_PORT, CameraHandler *cameraHandler); - void startAPIServer(); -}; \ No newline at end of file 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.ini b/ESP/platformio.ini index 48fdc7b..413379f 100644 --- a/ESP/platformio.ini +++ b/ESP/platformio.ini @@ -9,18 +9,25 @@ ; 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="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 +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 +OTAPassword="12345678" 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 -[pinouts] +[pinoutsESPCAM] ; AI Tinker camera, the ov2650 PWDN_GPIO_NUM = 32 RESET_GPIO_NUM = -1 @@ -39,125 +46,239 @@ 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 framework = arduino 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 - - '-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 - - -DDEBUG_ESP_PORT=Serial - - -DBOARD_HAS_PSRAM - - -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 - - ; 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 -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 - -[env:debug] -platform = ${common.platform} -board = ${common.board} -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 + +;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 = - ${common.build_flags} - -DCORE_DEBUG_LEVEL=4 - -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} + !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_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 + '-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 + ; 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+ +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 + ; geeksville/Micro-RTSP @ ^0.1.6 ; Micro-RTSP library for streaming video over RTSP - will be implemented soon + https://github.com/me-no-dev/ESPAsyncWebServer.git + https://github.com/me-no-dev/AsyncTCP.git + https://github.com/bblanchon/ArduinoJson.git -[env:release] +build_type = debug +extra_scripts = pre:tools/customname.py + +[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} -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} +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} + -DDEBUG_MODE=1 ; Set the debug mode + +[env:esp32Cam_release] +platform = ${common.platform} +board = esp32cam +framework = ${common.framework} +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} ; +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 ; 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} - -DCORE_DEBUG_LEVEL=1 - -DDEBUG_ESP_OTA - -DVERSION=${common.release_version} -lib_deps = - ${common.lib_deps} +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} -; extra_scripts = ${common.extra_scripts} -board_build.partitions = ${common.board_build.partitions} +;build_unflags = ${common.build_unflags} +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 +upload_flags = + --port=3232 + --auth=12345678 +build_type = release +extra_scripts = ${common.extra_scripts} + +[env:wrover] +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} ; 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} +;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 = ${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} +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} ; 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} +;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 = ${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] +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} ; 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} +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 +upload_port = 192.168.1.38 +upload_protocol = espota upload_flags = --port=3232 --auth=12345678 \ No newline at end of file diff --git a/ESP/src/main.cpp b/ESP/src/main.cpp index 3ec0c50..1ca31a7 100644 --- a/ESP/src/main.cpp +++ b/ESP/src/main.cpp @@ -4,43 +4,103 @@ #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 +//#include // Serial Manager int STREAM_SERVER_PORT = 80; int CONTROL_SERVER_PORT = 81; -OTA ota; +/** + * @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 LEDManager ledManager(33); -CameraHandler cameraHandler; -APIServer apiServer(CONTROL_SERVER_PORT, &cameraHandler); +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"); +MDNSHandler mdnsHandler(&mdnsStateManager, &deviceConfig); StreamServer streamServer(STREAM_SERVER_PORT); void setup() { - setCpuFrequencyMhz(240); // 240 MHz - Serial.begin(115200); - Serial.setDebugOutput(true); - ledManager.begin(); - cameraHandler.setupCamera(); - - WiFiHandler::setupWifi(WIFI_SSID, WIFI_PASSWORD, &wifiStateManager); - MDNSHandler::setupMDNS(MDNS_TRACKER_NAME, &mdnsStateManager); - - if (wifiStateManager.getCurrentState() == ProgramStates::DeviceStates::WiFiState_e::WiFiState_Connected) - { - apiServer.startAPIServer(); - streamServer.startStreamServer(); - } - - ledManager.onOff(true); - - ota.SetupOTA(OTA_PASSWORD, OTA_SERVER_PORT); + setCpuFrequencyMhz(240); // set to 240mhz for performance boost + Serial.begin(115200); + 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(); + 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(); + log_d("[SETUP]: Starting Stream Server"); + apiServer.begin(); + log_d("[SETUP]: Starting API Server"); + break; + } + case WiFiState_e::WiFiState_Connected: + { + streamServer.startStreamServer(); + log_d("[SETUP]: Starting Stream Server"); + apiServer.begin(); + log_d("[SETUP]: Starting API Server"); + break; + } + case WiFiState_e::WiFiState_Connecting: + { + //! TODO: Implement + break; + } + case WiFiState_e::WiFiState_Error: + { + //! TODO: Implement + break; + } + } +#if ENABLE_OTA + ota.SetupOTA(); +#endif // ENABLE_OTA } void loop() { - ota.HandleOTAUpdate(); - ledManager.displayStatus(); +#if ENABLE_OTA + ota.HandleOTAUpdate(); +#endif // ENABLE_OTA + ledManager.handleLED(&ledStateManager); + // 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/customname.py b/ESP/tools/customname.py new file mode 100644 index 0000000..73b7f8a --- /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" % + (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 new file mode 100644 index 0000000..bbdc837 --- /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 diff --git a/ESP/tools/versioning b/ESP/tools/versioning new file mode 100644 index 0000000..eed0d1a --- /dev/null +++ b/ESP/tools/versioning @@ -0,0 +1 @@ +506 \ No newline at end of file