Modernize the code a bit, clean up most compilation warnings

This commit is contained in:
Lorow
2025-05-18 17:33:05 +02:00
parent 0635bbd5c2
commit 4f0ab541cb
26 changed files with 329 additions and 383 deletions

View File

@@ -99,10 +99,8 @@ void CameraManager::setupBasicResolution()
config.fb_count = 2; config.fb_count = 2;
return; return;
} }
else
{ ESP_LOGE(CAMERA_MANAGER_TAG, "PSRAM size: %u", esp_psram_get_size());
ESP_LOGE(CAMERA_MANAGER_TAG, "PSRAM size: %u", esp_psram_get_size());
}
} }
void CameraManager::setupCameraSensor() void CameraManager::setupCameraSensor()
@@ -177,14 +175,13 @@ bool CameraManager::setupCamera()
// this->setupBasicResolution(); // this->setupBasicResolution();
ESP_LOGI(CAMERA_MANAGER_TAG, "Initializing camera..."); ESP_LOGI(CAMERA_MANAGER_TAG, "Initializing camera...");
esp_err_t hasCameraBeenInitialized = esp_camera_init(&config);
if (hasCameraBeenInitialized == ESP_OK) if (auto const hasCameraBeenInitialized = esp_camera_init(&config); hasCameraBeenInitialized == ESP_OK)
{ {
ESP_LOGI(CAMERA_MANAGER_TAG, "Camera initialized: %s \r\n", ESP_LOGI(CAMERA_MANAGER_TAG, "Camera initialized: %s \r\n",
esp_err_to_name(hasCameraBeenInitialized)); esp_err_to_name(hasCameraBeenInitialized));
SystemEvent event = {EventSource::CAMERA, CameraState_e::Camera_Success}; constexpr auto event = SystemEvent{EventSource::CAMERA, CameraState_e::Camera_Success};
xQueueSend(this->eventQueue, &event, 10); xQueueSend(this->eventQueue, &event, 10);
} }
else else
@@ -195,27 +192,23 @@ bool CameraManager::setupCamera()
"Please " "Please "
"fix the " "fix the "
"camera and reboot the device.\r\n"); "camera and reboot the device.\r\n");
SystemEvent event = {EventSource::CAMERA, CameraState_e::Camera_Error}; constexpr auto event = SystemEvent{EventSource::CAMERA, CameraState_e::Camera_Error};
xQueueSend(this->eventQueue, &event, 10); xQueueSend(this->eventQueue, &event, 10);
return false; return false;
} }
#if CONFIG_WIRED_MODE #if CONFIG_WIRED_MODE
auto temp_sensor = esp_camera_sensor_get(); const auto temp_sensor = esp_camera_sensor_get();
auto camera_id = temp_sensor->id.PID;
switch (camera_id)
{
// Thanks to lick_it, we discovered that OV5640 likes to overheat when // Thanks to lick_it, we discovered that OV5640 likes to overheat when
// running at higher than usual xclk frequencies. // running at higher than usual xclk frequencies.
// Hence why we're limit the faster ones for OV2640 // Hence, why we're limiting the faster ones for OV2640
case OV5640_PID: if (const auto camera_id = temp_sensor->id.PID; camera_id == OV5640_PID) {
config.xclk_freq_hz = OV5640_XCLK_FREQ_HZ; config.xclk_freq_hz = OV5640_XCLK_FREQ_HZ;
esp_camera_deinit(); esp_camera_deinit();
esp_camera_init(&config); esp_camera_init(&config);
break;
default:
break;
} }
#endif #endif
this->setupCameraSensor(); this->setupCameraSensor();
@@ -229,13 +222,13 @@ void CameraManager::loadConfigData()
CameraConfig_t cameraConfig = projectConfig->getCameraConfig(); CameraConfig_t cameraConfig = projectConfig->getCameraConfig();
this->setHFlip(cameraConfig.href); this->setHFlip(cameraConfig.href);
this->setVFlip(cameraConfig.vflip); this->setVFlip(cameraConfig.vflip);
this->setCameraResolution((framesize_t)cameraConfig.framesize); this->setCameraResolution(static_cast<framesize_t>(cameraConfig.framesize));
camera_sensor->set_quality(camera_sensor, cameraConfig.quality); camera_sensor->set_quality(camera_sensor, cameraConfig.quality);
camera_sensor->set_agc_gain(camera_sensor, cameraConfig.brightness); camera_sensor->set_agc_gain(camera_sensor, cameraConfig.brightness);
ESP_LOGD(CAMERA_MANAGER_TAG, "Loading camera config data done"); ESP_LOGD(CAMERA_MANAGER_TAG, "Loading camera config data done");
} }
int CameraManager::setCameraResolution(framesize_t frameSize) int CameraManager::setCameraResolution(const framesize_t frameSize)
{ {
if (camera_sensor->pixformat == PIXFORMAT_JPEG) if (camera_sensor->pixformat == PIXFORMAT_JPEG)
{ {
@@ -244,12 +237,12 @@ int CameraManager::setCameraResolution(framesize_t frameSize)
return -1; return -1;
} }
int CameraManager::setVFlip(int direction) int CameraManager::setVFlip(const int direction)
{ {
return camera_sensor->set_vflip(camera_sensor, direction); return camera_sensor->set_vflip(camera_sensor, direction);
} }
int CameraManager::setHFlip(int direction) int CameraManager::setHFlip(const int direction)
{ {
return camera_sensor->set_hmirror(camera_sensor, direction); return camera_sensor->set_hmirror(camera_sensor, direction);
} }

View File

@@ -17,45 +17,42 @@ std::unordered_map<std::string, CommandType> commandTypeMap = {
{"restart_device", CommandType::RESTART_DEVICE}, {"restart_device", CommandType::RESTART_DEVICE},
}; };
std::function<CommandResult()> CommandManager::createCommand(CommandType type, std::string_view json) std::function<CommandResult()> CommandManager::createCommand(CommandType type, std::string_view json) const {
{
typedef std::function<CommandResult()> CommandFunction;
switch (type) switch (type)
{ {
case CommandType::PING: case CommandType::PING:
return CommandFunction(PingCommand); return { PingCommand };
case CommandType::SET_WIFI: case CommandType::SET_WIFI:
return CommandFunction(std::bind(setWiFiCommand, this->registry, json)); return [this, json] { return setWiFiCommand(this->registry, json); };
case CommandType::UPDATE_WIFI: case CommandType::UPDATE_WIFI:
return CommandFunction(std::bind(updateWiFiCommand, this->registry, json)); return [this, json] { return updateWiFiCommand(this->registry, json); };
case CommandType::UPDATE_AP_WIFI: case CommandType::UPDATE_AP_WIFI:
return CommandFunction(std::bind(updateAPWiFiCommand, this->registry, json)); return [this, json] { return updateAPWiFiCommand(this->registry, json); };
case CommandType::DELETE_NETWORK: case CommandType::DELETE_NETWORK:
return CommandFunction(std::bind(deleteWiFiCommand, this->registry, json)); return [this, json] { return deleteWiFiCommand(this->registry, json); };
case CommandType::SET_MDNS: case CommandType::SET_MDNS:
return CommandFunction(std::bind(setMDNSCommand, this->registry, json)); return [this, json] { return setMDNSCommand(this->registry, json); };
// updating the mnds name is essentially the same operation // updating the mnds name is essentially the same operation
case CommandType::UPDATE_MDNS: case CommandType::UPDATE_MDNS:
return CommandFunction(std::bind(setMDNSCommand, this->registry, json)); return [this, json] { return setMDNSCommand(this->registry, json); };
case CommandType::UPDATE_CAMERA: case CommandType::UPDATE_CAMERA:
return CommandFunction(std::bind(updateCameraCommand, this->registry, json)); return [this, json] { return updateCameraCommand(this->registry, json); };
case CommandType::RESTART_CAMERA: case CommandType::RESTART_CAMERA:
return CommandFunction(std::bind(restartCameraCommand, this->registry, json)); return [this, json] { return restartCameraCommand(this->registry, json); };
case CommandType::GET_CONFIG: case CommandType::GET_CONFIG:
return CommandFunction(std::bind(getConfigCommand, this->registry)); return [this] { return getConfigCommand(this->registry); };
case CommandType::SAVE_CONFIG: case CommandType::SAVE_CONFIG:
return CommandFunction(std::bind(saveConfigCommand, this->registry)); return [this] { return saveConfigCommand(this->registry); };
case CommandType::RESET_CONFIG: case CommandType::RESET_CONFIG:
return CommandFunction(std::bind(resetConfigCommand, this->registry, json)); return [this, json] { return resetConfigCommand(this->registry, json); };
case CommandType::RESTART_DEVICE: case CommandType::RESTART_DEVICE:
return CommandFunction(restartDeviceCommand); return restartDeviceCommand;
default: default:
return nullptr; return nullptr;
} }
} }
CommandResult CommandManager::executeFromJson(std::string_view json) CommandResult CommandManager::executeFromJson(const std::string_view json) const
{ {
cJSON *parsedJson = cJSON_Parse(json.data()); cJSON *parsedJson = cJSON_Parse(json.data());
if (parsedJson == nullptr) if (parsedJson == nullptr)
@@ -84,9 +81,9 @@ CommandResult CommandManager::executeFromJson(std::string_view json)
} }
const cJSON *commandPayload = cJSON_GetObjectItem(commandData, "data"); const cJSON *commandPayload = cJSON_GetObjectItem(commandData, "data");
auto commandType = commandTypeMap.at(std::string(commandTypeString->valuestring)); const auto commandType = commandTypeMap.at(std::string(commandTypeString->valuestring));
std::string commandPayloadString = ""; std::string commandPayloadString;
if (commandPayload != nullptr) if (commandPayload != nullptr)
commandPayloadString = std::string(cJSON_Print(commandPayload)); commandPayloadString = std::string(cJSON_Print(commandPayload));
@@ -100,16 +97,16 @@ CommandResult CommandManager::executeFromJson(std::string_view json)
cJSON_AddItemToArray(responses, response); cJSON_AddItemToArray(responses, response);
} }
auto jsonString = cJSON_Print(responseDocument); const auto jsonString = cJSON_Print(responseDocument);
cJSON_Delete(responseDocument); cJSON_Delete(responseDocument);
cJSON_Delete(parsedJson); cJSON_Delete(parsedJson);
return CommandResult::getSuccessResult(jsonString); return CommandResult::getSuccessResult(jsonString);
} }
CommandResult CommandManager::executeFromType(CommandType type, std::string_view json) CommandResult CommandManager::executeFromType(const CommandType type, const std::string_view json) const
{ {
auto command = createCommand(type, json); const auto command = createCommand(type, json);
if (command == nullptr) if (command == nullptr)
{ {

View File

@@ -19,7 +19,7 @@
#include "commands/device_commands.hpp" #include "commands/device_commands.hpp"
#include <cJSON.h> #include <cJSON.h>
enum CommandType enum class CommandType
{ {
None, None,
PING, PING,
@@ -44,11 +44,11 @@ private:
std::shared_ptr<DependencyRegistry> registry; std::shared_ptr<DependencyRegistry> registry;
public: public:
CommandManager(std::shared_ptr<DependencyRegistry> DependencyRegistry) : registry(DependencyRegistry) {}; explicit CommandManager(const std::shared_ptr<DependencyRegistry> &DependencyRegistry) : registry(DependencyRegistry) {};
std::function<CommandResult()> createCommand(CommandType type, std::string_view json); std::function<CommandResult()> createCommand(CommandType type, std::string_view json) const;
CommandResult executeFromJson(std::string_view json); CommandResult executeFromJson(std::string_view json) const;
CommandResult executeFromType(CommandType type, std::string_view json); CommandResult executeFromType(CommandType type, std::string_view json) const;
}; };
#endif #endif

View File

@@ -16,7 +16,7 @@ private:
Status status; Status status;
std::string message; std::string message;
CommandResult(std::string message, Status status) CommandResult(std::string message, const Status status)
{ {
this->status = status; this->status = status;
if (status == Status::SUCCESS) if (status == Status::SUCCESS)
@@ -33,12 +33,12 @@ private:
public: public:
bool isSuccess() const { return status == Status::SUCCESS; } bool isSuccess() const { return status == Status::SUCCESS; }
static CommandResult getSuccessResult(std::string message) static CommandResult getSuccessResult(const std::string &message)
{ {
return CommandResult(message, Status::SUCCESS); return CommandResult(message, Status::SUCCESS);
} }
static CommandResult getErrorResult(std::string message) static CommandResult getErrorResult(const std::string &message)
{ {
return CommandResult(message, Status::FAILURE); return CommandResult(message, Status::FAILURE);
} }

View File

@@ -4,7 +4,7 @@
#include <memory> #include <memory>
#include <unordered_map> #include <unordered_map>
enum DependencyType enum class DependencyType
{ {
project_config, project_config,
camera_manager camera_manager

View File

@@ -8,11 +8,11 @@ std::optional<WifiPayload> parseSetWiFiCommandPayload(std::string_view jsonPaylo
if (parsedJson == nullptr) if (parsedJson == nullptr)
return std::nullopt; return std::nullopt;
cJSON *networkName = cJSON_GetObjectItem(parsedJson, "name"); const cJSON *networkName = cJSON_GetObjectItem(parsedJson, "name");
cJSON *ssidPtr = cJSON_GetObjectItem(parsedJson, "ssid"); const cJSON *ssidPtr = cJSON_GetObjectItem(parsedJson, "ssid");
cJSON *passwordPtr = cJSON_GetObjectItem(parsedJson, "password"); const cJSON *passwordPtr = cJSON_GetObjectItem(parsedJson, "password");
cJSON *channelPtr = cJSON_GetObjectItem(parsedJson, "channel"); const cJSON *channelPtr = cJSON_GetObjectItem(parsedJson, "channel");
cJSON *powerPtr = cJSON_GetObjectItem(parsedJson, "power"); const cJSON *powerPtr = cJSON_GetObjectItem(parsedJson, "power");
if (ssidPtr == nullptr) if (ssidPtr == nullptr)
{ {
@@ -50,12 +50,12 @@ std::optional<WifiPayload> parseSetWiFiCommandPayload(std::string_view jsonPaylo
std::optional<deleteNetworkPayload> parseDeleteWifiCommandPayload(std::string_view jsonPayload) std::optional<deleteNetworkPayload> parseDeleteWifiCommandPayload(std::string_view jsonPayload)
{ {
deleteNetworkPayload payload; deleteNetworkPayload payload;
cJSON *parsedJson = cJSON_Parse(jsonPayload.data()); auto *parsedJson = cJSON_Parse(jsonPayload.data());
if (parsedJson == nullptr) if (parsedJson == nullptr)
return std::nullopt; return std::nullopt;
cJSON *networkName = cJSON_GetObjectItem(parsedJson, "name"); const auto *networkName = cJSON_GetObjectItem(parsedJson, "name");
if (networkName == nullptr) if (networkName == nullptr)
{ {
cJSON_Delete(parsedJson); cJSON_Delete(parsedJson);
@@ -76,7 +76,7 @@ std::optional<UpdateWifiPayload> parseUpdateWifiCommandPayload(std::string_view
if (parsedJson == nullptr) if (parsedJson == nullptr)
return std::nullopt; return std::nullopt;
cJSON *networkName = cJSON_GetObjectItem(parsedJson, "name"); const cJSON *networkName = cJSON_GetObjectItem(parsedJson, "name");
if (networkName == nullptr) if (networkName == nullptr)
{ {
cJSON_Delete(parsedJson); cJSON_Delete(parsedJson);
@@ -85,10 +85,10 @@ std::optional<UpdateWifiPayload> parseUpdateWifiCommandPayload(std::string_view
payload.networkName = std::string(networkName->valuestring); payload.networkName = std::string(networkName->valuestring);
cJSON *ssidObject = cJSON_GetObjectItem(parsedJson, "ssid"); const auto *ssidObject = cJSON_GetObjectItem(parsedJson, "ssid");
cJSON *passwordObject = cJSON_GetObjectItem(parsedJson, "password"); const auto *passwordObject = cJSON_GetObjectItem(parsedJson, "password");
cJSON *channelObject = cJSON_GetObjectItem(parsedJson, "channel"); const auto *channelObject = cJSON_GetObjectItem(parsedJson, "channel");
cJSON *powerObject = cJSON_GetObjectItem(parsedJson, "power"); const auto *powerObject = cJSON_GetObjectItem(parsedJson, "power");
if (ssidObject != nullptr && (strcmp(ssidObject->valuestring, "") == 0)) if (ssidObject != nullptr && (strcmp(ssidObject->valuestring, "") == 0))
{ {
@@ -113,7 +113,7 @@ std::optional<UpdateWifiPayload> parseUpdateWifiCommandPayload(std::string_view
return payload; return payload;
} }
std::optional<UpdateAPWiFiPayload> parseUpdateAPWiFiCommandPayload(std::string_view jsonPayload) std::optional<UpdateAPWiFiPayload> parseUpdateAPWiFiCommandPayload(const std::string_view jsonPayload)
{ {
UpdateAPWiFiPayload payload; UpdateAPWiFiPayload payload;
cJSON *parsedJson = cJSON_Parse(jsonPayload.data()); cJSON *parsedJson = cJSON_Parse(jsonPayload.data());
@@ -123,9 +123,9 @@ std::optional<UpdateAPWiFiPayload> parseUpdateAPWiFiCommandPayload(std::string_v
return std::nullopt; return std::nullopt;
} }
cJSON *ssidObject = cJSON_GetObjectItem(parsedJson, "ssid"); const cJSON *ssidObject = cJSON_GetObjectItem(parsedJson, "ssid");
cJSON *passwordObject = cJSON_GetObjectItem(parsedJson, "password"); const cJSON *passwordObject = cJSON_GetObjectItem(parsedJson, "password");
cJSON *channelObject = cJSON_GetObjectItem(parsedJson, "channel"); const cJSON *channelObject = cJSON_GetObjectItem(parsedJson, "channel");
if (ssidObject != nullptr) if (ssidObject != nullptr)
payload.ssid = std::string(ssidObject->valuestring); payload.ssid = std::string(ssidObject->valuestring);
@@ -142,13 +142,13 @@ std::optional<UpdateAPWiFiPayload> parseUpdateAPWiFiCommandPayload(std::string_v
CommandResult setWiFiCommand(std::shared_ptr<DependencyRegistry> registry, std::string_view jsonPayload) CommandResult setWiFiCommand(std::shared_ptr<DependencyRegistry> registry, std::string_view jsonPayload)
{ {
auto payload = parseSetWiFiCommandPayload(jsonPayload); const auto payload = parseSetWiFiCommandPayload(jsonPayload);
if (!payload.has_value()) if (!payload.has_value())
{ {
return CommandResult::getErrorResult("Invalid payload"); return CommandResult::getErrorResult("Invalid payload");
} }
auto wifiConfig = payload.value(); const auto wifiConfig = payload.value();
std::shared_ptr<ProjectConfig> projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config); std::shared_ptr<ProjectConfig> projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config);
projectConfig->setWifiConfig( projectConfig->setWifiConfig(
@@ -163,11 +163,11 @@ CommandResult setWiFiCommand(std::shared_ptr<DependencyRegistry> registry, std::
CommandResult deleteWiFiCommand(std::shared_ptr<DependencyRegistry> registry, std::string_view jsonPayload) CommandResult deleteWiFiCommand(std::shared_ptr<DependencyRegistry> registry, std::string_view jsonPayload)
{ {
auto payload = parseDeleteWifiCommandPayload(jsonPayload); const auto payload = parseDeleteWifiCommandPayload(jsonPayload);
if (!payload.has_value()) if (!payload.has_value())
return CommandResult::getErrorResult("Invalid payload"); return CommandResult::getErrorResult("Invalid payload");
std::shared_ptr<ProjectConfig> projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config); auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config);
projectConfig->deleteWifiConfig(payload.value().networkName); projectConfig->deleteWifiConfig(payload.value().networkName);
return CommandResult::getSuccessResult("Config updated"); return CommandResult::getSuccessResult("Config updated");
@@ -175,7 +175,7 @@ CommandResult deleteWiFiCommand(std::shared_ptr<DependencyRegistry> registry, st
CommandResult updateWiFiCommand(std::shared_ptr<DependencyRegistry> registry, std::string_view jsonPayload) CommandResult updateWiFiCommand(std::shared_ptr<DependencyRegistry> registry, std::string_view jsonPayload)
{ {
auto payload = parseUpdateWifiCommandPayload(jsonPayload); const auto payload = parseUpdateWifiCommandPayload(jsonPayload);
if (!payload.has_value()) if (!payload.has_value())
{ {
return CommandResult::getErrorResult("Invalid payload"); return CommandResult::getErrorResult("Invalid payload");
@@ -183,13 +183,12 @@ CommandResult updateWiFiCommand(std::shared_ptr<DependencyRegistry> registry, st
auto updatedConfig = payload.value(); auto updatedConfig = payload.value();
std::shared_ptr<ProjectConfig> projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config); auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config);
auto storedNetworks = projectConfig->getWifiConfigs(); auto storedNetworks = projectConfig->getWifiConfigs();
if (auto networkToUpdate = std::find_if( if (const auto networkToUpdate = std::ranges::find_if(
storedNetworks.begin(), storedNetworks,
storedNetworks.end(), [&](auto &network){ return network.name == updatedConfig.networkName; }
[&](auto &network) );
{ return network.name == updatedConfig.networkName; });
networkToUpdate != storedNetworks.end()) networkToUpdate != storedNetworks.end())
{ {
projectConfig->setWifiConfig( projectConfig->setWifiConfig(
@@ -207,15 +206,15 @@ CommandResult updateWiFiCommand(std::shared_ptr<DependencyRegistry> registry, st
CommandResult updateAPWiFiCommand(std::shared_ptr<DependencyRegistry> registry, std::string_view jsonPayload) CommandResult updateAPWiFiCommand(std::shared_ptr<DependencyRegistry> registry, std::string_view jsonPayload)
{ {
auto payload = parseUpdateAPWiFiCommandPayload(jsonPayload); const auto payload = parseUpdateAPWiFiCommandPayload(jsonPayload);
if (!payload.has_value()) if (!payload.has_value())
return CommandResult::getErrorResult("Invalid payload"); return CommandResult::getErrorResult("Invalid payload");
auto updatedConfig = payload.value(); auto updatedConfig = payload.value();
std::shared_ptr<ProjectConfig> projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config); auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config);
auto previousAPConfig = projectConfig->getAPWifiConfig(); const auto previousAPConfig = projectConfig->getAPWifiConfig();
projectConfig->setAPWifiConfig( projectConfig->setAPWifiConfig(
updatedConfig.ssid.has_value() ? updatedConfig.ssid.value() : previousAPConfig.ssid, updatedConfig.ssid.has_value() ? updatedConfig.ssid.value() : previousAPConfig.ssid,

View File

@@ -4,7 +4,7 @@ const char *LED_MANAGER_TAG = "[LED_MANAGER]";
ledStateMap_t LEDManager::ledStateMap = { ledStateMap_t LEDManager::ledStateMap = {
{ {
LEDStates_e::_LedStateNone, LEDStates_e::LedStateNone,
{ {
false, false,
false, false,
@@ -12,7 +12,7 @@ ledStateMap_t LEDManager::ledStateMap = {
}, },
}, },
{ {
LEDStates_e::_LedStateStreaming, LEDStates_e::LedStateStreaming,
{ {
false, false,
true, true,
@@ -20,7 +20,7 @@ ledStateMap_t LEDManager::ledStateMap = {
}, },
}, },
{ {
LEDStates_e::_LedStateStoppedStreaming, LEDStates_e::LedStateStoppedStreaming,
{ {
false, false,
true, true,
@@ -28,7 +28,7 @@ ledStateMap_t LEDManager::ledStateMap = {
}, },
}, },
{ {
LEDStates_e::_Camera_Error, LEDStates_e::CameraError,
{ {
true, true,
true, true,
@@ -36,7 +36,7 @@ ledStateMap_t LEDManager::ledStateMap = {
}, },
}, },
{ {
LEDStates_e::_WiFiState_Connecting, LEDStates_e::WiFiStateConnecting,
{ {
false, false,
true, true,
@@ -44,15 +44,18 @@ ledStateMap_t LEDManager::ledStateMap = {
}, },
}, },
{ {
LEDStates_e::_WiFiState_Connected, LEDStates_e::WiFiStateConnected,
{ {
false, false,
false, false,
{{LED_ON, 200}, {LED_OFF, 200}, {LED_ON, 200}, {LED_OFF, 200}, {LED_ON, 200}, {LED_OFF, 200}, {LED_ON, 200}, {LED_OFF, 200}, {LED_ON, 200}, {LED_OFF, 200}}, {
{LED_ON, 200}, {LED_OFF, 200}, {LED_ON, 200}, {LED_OFF, 200}, {LED_ON, 200}, {LED_OFF, 200},
{LED_ON, 200}, {LED_OFF, 200}, {LED_ON, 200}, {LED_OFF, 200}
},
}, },
}, },
{ {
LEDStates_e::_WiFiState_Error, LEDStates_e::WiFiStateError,
{ {
true, true,
true, true,
@@ -61,18 +64,19 @@ ledStateMap_t LEDManager::ledStateMap = {
}, },
}; };
LEDManager::LEDManager(gpio_num_t pin, gpio_num_t illumninator_led_pin, QueueHandle_t ledStateQueue) : blink_led_pin(pin), LEDManager::LEDManager(gpio_num_t pin, gpio_num_t illumninator_led_pin,
illumninator_led_pin(illumninator_led_pin), ledStateQueue(ledStateQueue), currentState(LEDStates_e::_LedStateNone) QueueHandle_t ledStateQueue) : blink_led_pin(pin),
{ illumninator_led_pin(illumninator_led_pin),
ledStateQueue(ledStateQueue),
currentState(LEDStates_e::LedStateNone) {
} }
void LEDManager::setup() void LEDManager::setup() {
{ ESP_LOGD(LED_MANAGER_TAG, "Setting up status led.");
ESP_LOGD(LED_MANAGER_TAG, "Setting up status led."); gpio_reset_pin(blink_led_pin);
gpio_reset_pin(blink_led_pin); /* Set the GPIO as a push/pull output */
/* Set the GPIO as a push/pull output */ gpio_set_direction(blink_led_pin, GPIO_MODE_OUTPUT);
gpio_set_direction(blink_led_pin, GPIO_MODE_OUTPUT); this->toggleLED(LED_OFF);
this->toggleLED(LED_OFF);
#ifdef CONFIG_SUPPORTS_EXTERNAL_LED_CONTROL #ifdef CONFIG_SUPPORTS_EXTERNAL_LED_CONTROL
ESP_LOGD(LED_MANAGER_TAG, "Setting up illuminator led."); ESP_LOGD(LED_MANAGER_TAG, "Setting up illuminator led.");
@@ -100,81 +104,68 @@ void LEDManager::setup()
ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel)); ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
#endif #endif
ESP_LOGD(LED_MANAGER_TAG, "Done."); ESP_LOGD(LED_MANAGER_TAG, "Done.");
} }
void LEDManager::handleLED() void LEDManager::handleLED() {
{ if (!this->finishedPattern) {
if (!this->finishedPattern) displayCurrentPattern();
{ return;
displayCurrentPattern(); }
return;
} if (xQueueReceive(this->ledStateQueue, &buffer, 10)) {
this->updateState(buffer);
if (xQueueReceive(this->ledStateQueue, &buffer, 10)) } else {
{ // we've finished displaying the pattern, so let's check if it's repeatable and if so - reset it
this->updateState(buffer); if (ledStateMap[this->currentState].isRepeatable || ledStateMap[this->currentState].isError) {
} this->currentPatternIndex = 0;
else this->finishedPattern = false;
{ }
// we've finished displaying the pattern, so let's check if it's repeatable and if so - reset it
if (this->ledStateMap[this->currentState].isRepeatable || this->ledStateMap[this->currentState].isError)
{
this->currentPatternIndex = 0;
this->finishedPattern = false;
} }
}
} }
void LEDManager::displayCurrentPattern() void LEDManager::displayCurrentPattern() {
{ auto [state, delayTime] = ledStateMap[this->currentState].patterns[this->currentPatternIndex];
BlinkPatterns_t ledState = this->ledStateMap[this->currentState].patterns[this->currentPatternIndex]; this->toggleLED(state);
this->toggleLED(ledState.state); this->timeToDelayFor = delayTime;
this->timeToDelayFor = ledState.delayTime;
if (!(this->currentPatternIndex >= this->ledStateMap[this->currentState].patterns.size() - 1)) if (this->currentPatternIndex < ledStateMap[this->currentState].patterns.size() - 1)
this->currentPatternIndex++; this->currentPatternIndex++;
else else {
{ this->finishedPattern = true;
this->finishedPattern = true; this->toggleLED(LED_OFF);
this->toggleLED(LED_OFF); }
}
} }
void LEDManager::updateState(LEDStates_e newState) void LEDManager::updateState(const LEDStates_e newState) {
{ // we should change the displayed state
// we should change the displayed state // only if we finished displaying the current one - which is handled by the task
// only if we finished displaying the current one - which is handled by the task // if the new state is not the same as the current one
// if the new state is not the same as the current one // and if can actually display the state
// and if can actually display the state
// if we've got an error state - that's it, we'll just keep repeating it indefinitely // if we've got an error state - that's it, we'll just keep repeating it indefinitely
if (this->ledStateMap[this->currentState].isError) if (ledStateMap[this->currentState].isError)
return; return;
if (newState == this->currentState) if (newState == this->currentState)
return; return;
if (this->ledStateMap.contains(newState)) if (ledStateMap.contains(newState)) {
{ this->currentState = newState;
this->currentState = newState; this->currentPatternIndex = 0;
this->currentPatternIndex = 0; this->finishedPattern = false;
this->finishedPattern = false; }
}
} }
void LEDManager::toggleLED(bool state) const void LEDManager::toggleLED(const bool state) const {
{ gpio_set_level(blink_led_pin, state);
gpio_set_level(blink_led_pin, state);
} }
void HandleLEDDisplayTask(void *pvParameter) void HandleLEDDisplayTask(void *pvParameter) {
{ auto *ledManager = static_cast<LEDManager *>(pvParameter);
LEDManager *ledManager = static_cast<LEDManager *>(pvParameter);
while (1) while (true) {
{ ledManager->handleLED();
ledManager->handleLED(); vTaskDelay(ledManager->getTimeToDelayFor());
vTaskDelay(ledManager->getTimeToDelayFor()); }
} }
}

View File

@@ -37,8 +37,7 @@ esp_err_t MDNSManager::start()
{"api_port", "81"}, {"api_port", "81"},
}; };
result = mdns_service_add(nullptr, mdnsName.c_str(), "_tcp", 80, serviceTxtData, 2); mdns_service_add(nullptr, mdnsName.c_str(), "_tcp", 80, serviceTxtData, 2);
result = mdns_service_instance_name_set(mdnsName.c_str(), "_tcp", mdnsName.c_str()); result = mdns_service_instance_name_set(mdnsName.c_str(), "_tcp", mdnsName.c_str());
if (result != ESP_OK) if (result != ESP_OK)
{ {

View File

@@ -3,7 +3,7 @@
void OpenIrisTasks::ScheduleRestart(int milliseconds) void OpenIrisTasks::ScheduleRestart(int milliseconds)
{ {
taskYIELD(); taskYIELD();
int initialTime = Helpers::getTimeInMillis(); const auto initialTime = Helpers::getTimeInMillis();
while (Helpers::getTimeInMillis() - initialTime <= milliseconds) while (Helpers::getTimeInMillis() - initialTime <= milliseconds)
{ {
continue; continue;

View File

@@ -8,7 +8,7 @@
#include <cstdint> #include <cstdint>
#include <string> #include <string>
#include <cstring> #include <cstring>
#include <math.h> #include <cmath>
#include "esp_log.h" #include "esp_log.h"
#include "nvs_flash.h" #include "nvs_flash.h"
#include "nvs.h" #include "nvs.h"

View File

@@ -3,6 +3,7 @@
#define _PROJECT_CONFIG_MODELS_HPP_ #define _PROJECT_CONFIG_MODELS_HPP_
#include <string> #include <string>
#include <utility>
#include <vector> #include <vector>
#include <helpers.hpp> #include <helpers.hpp>
#include "sdkconfig.h" #include "sdkconfig.h"
@@ -29,19 +30,18 @@ struct DeviceConfig_t : BaseConfigModel
void load() void load()
{ {
this->OTALogin = this->pref->getString("OTALogin", "openiris").c_str(); this->OTALogin = this->pref->getString("OTALogin", "openiris");
this->OTAPassword = this->pref->getString("OTAPassword", "openiris").c_str(); this->OTAPassword = this->pref->getString("OTAPassword", "openiris");
this->OTAPort = this->pref->getInt("OTAPort", 3232); this->OTAPort = this->pref->getInt("OTAPort", 3232);
}; };
void save() void save() const {
{
this->pref->putString("OTALogin", this->OTALogin.c_str()); this->pref->putString("OTALogin", this->OTALogin.c_str());
this->pref->putString("OTAPassword", this->OTAPassword.c_str()); this->pref->putString("OTAPassword", this->OTAPassword.c_str());
this->pref->putInt("OTAPort", this->OTAPort); this->pref->putInt("OTAPort", this->OTAPort);
}; };
std::string toRepresentation() std::string toRepresentation() const
{ {
return Helpers::format_string( return Helpers::format_string(
"\"device_config\": {\"OTALogin\": \"%s\", \"OTAPassword\": \"%s\", " "\"device_config\": {\"OTALogin\": \"%s\", \"OTAPassword\": \"%s\", "
@@ -50,7 +50,7 @@ struct DeviceConfig_t : BaseConfigModel
}; };
}; };
struct MDNSConfig_t : public BaseConfigModel struct MDNSConfig_t : BaseConfigModel
{ {
MDNSConfig_t(Preferences *pref) : BaseConfigModel(pref) {} MDNSConfig_t(Preferences *pref) : BaseConfigModel(pref) {}
@@ -67,11 +67,10 @@ struct MDNSConfig_t : public BaseConfigModel
default_hostname = "openiristracker"; default_hostname = "openiristracker";
} }
this->hostname = this->pref->getString("hostname", default_hostname).c_str(); this->hostname = this->pref->getString("hostname", default_hostname);
}; };
void save() void save() const {
{
this->pref->putString("hostname", this->hostname.c_str()); this->pref->putString("hostname", this->hostname.c_str());
}; };
@@ -102,8 +101,7 @@ struct CameraConfig_t : BaseConfigModel
this->brightness = this->pref->getInt("brightness", 2); this->brightness = this->pref->getInt("brightness", 2);
}; };
void save() void save() const {
{
this->pref->putInt("vflip", this->vflip); this->pref->putInt("vflip", this->vflip);
this->pref->putInt("href", this->href); this->pref->putInt("href", this->href);
this->pref->putInt("framesize", this->framesize); this->pref->putInt("framesize", this->framesize);
@@ -132,12 +130,12 @@ struct WiFiConfig_t : BaseConfigModel
WiFiConfig_t( WiFiConfig_t(
Preferences *pref, Preferences *pref,
uint8_t index, const uint8_t index,
const std::string &name, std::string name,
const std::string &ssid, std::string ssid,
const std::string &password, std::string password,
uint8_t channel, const uint8_t channel,
uint8_t power) const uint8_t power)
: BaseConfigModel(pref), : BaseConfigModel(pref),
index(index), index(index),
name(std::move(name)), name(std::move(name)),
@@ -153,23 +151,22 @@ struct WiFiConfig_t : BaseConfigModel
uint8_t channel; uint8_t channel;
uint8_t power; uint8_t power;
void load(uint8_t index) void load(const uint8_t index)
{ {
this->index = index; this->index = index;
char buffer[2]; char buffer[2];
std::string iter_str = Helpers::itoa(index, buffer, 10); auto const iter_str = std::string(Helpers::itoa(index, buffer, 10));
this->name = this->pref->getString(("name" + iter_str).c_str(), "").c_str(); this->name = this->pref->getString(("name" + iter_str).c_str(), "");
this->ssid = this->pref->getString(("ssid" + iter_str).c_str(), "").c_str(); this->ssid = this->pref->getString(("ssid" + iter_str).c_str(), "");
this->password = this->pref->getString(("password" + iter_str).c_str(), "").c_str(); this->password = this->pref->getString(("password" + iter_str).c_str(), "");
this->channel = this->pref->getUInt(("channel" + iter_str).c_str()); this->channel = this->pref->getUInt(("channel" + iter_str).c_str());
this->power = this->pref->getUInt(("power" + iter_str).c_str()); this->power = this->pref->getUInt(("power" + iter_str).c_str());
}; };
void save() void save() const {
{
char buffer[2]; char buffer[2];
std::string iter_str = Helpers::itoa(this->index, buffer, 10); auto const iter_str = std::string(Helpers::itoa(this->index, buffer, 10));
this->pref->putString(("name" + iter_str).c_str(), this->name.c_str()); this->pref->putString(("name" + iter_str).c_str(), this->name.c_str());
this->pref->putString(("ssid" + iter_str).c_str(), this->ssid.c_str()); this->pref->putString(("ssid" + iter_str).c_str(), this->ssid.c_str());
@@ -197,12 +194,11 @@ struct AP_WiFiConfig_t : BaseConfigModel
void load() void load()
{ {
this->ssid = this->pref->getString("apSSID", CONFIG_AP_WIFI_SSID).c_str(); this->ssid = this->pref->getString("apSSID", CONFIG_AP_WIFI_SSID);
this->password = this->pref->getString("apPassword", CONFIG_AP_WIFI_PASSWORD).c_str(); this->password = this->pref->getString("apPassword", CONFIG_AP_WIFI_PASSWORD);
}; };
void save() void save() const {
{
this->pref->putString("apSSID", this->ssid.c_str()); this->pref->putString("apSSID", this->ssid.c_str());
this->pref->putString("apPass", this->password.c_str()); this->pref->putString("apPass", this->password.c_str());
this->pref->putUInt("apChannel", this->channel); this->pref->putUInt("apChannel", this->channel);
@@ -228,8 +224,7 @@ struct WiFiTxPower_t : BaseConfigModel
this->power = this->pref->getUInt("txpower", 52); this->power = this->pref->getUInt("txpower", 52);
}; };
void save() void save() const {
{
this->pref->putUInt("txpower", this->power); this->pref->putUInt("txpower", this->power);
}; };
@@ -255,19 +250,19 @@ public:
std::vector<WiFiConfig_t> networks, std::vector<WiFiConfig_t> networks,
AP_WiFiConfig_t ap_network, AP_WiFiConfig_t ap_network,
MDNSConfig_t mdns, MDNSConfig_t mdns,
WiFiTxPower_t txpower) : device(device), WiFiTxPower_t txpower) : device(std::move(device)),
camera(camera), camera(camera),
networks(networks), networks(std::move(networks)),
ap_network(ap_network), ap_network(std::move(ap_network)),
mdns(mdns), mdns(std::move(mdns)),
txpower(txpower) {} txpower(txpower) {}
std::string toRepresentation() std::string toRepresentation()
{ {
std::string WifiConfigRepresentation = ""; std::string WifiConfigRepresentation;
// we need a valid json representation, so we can't have a dangling comma at the end // we need a valid json representation, so we can't have a dangling comma at the end
if (this->networks.size() > 0) if (!this->networks.empty())
{ {
if (this->networks.size() > 1) if (this->networks.size() > 1)
{ {

View File

@@ -1,11 +1,13 @@
#include "ProjectConfig.hpp" #include "ProjectConfig.hpp"
static auto CONFIGURATION_TAG = "[CONFIGURATION]";
int getNetworkCount(Preferences *pref) int getNetworkCount(Preferences *pref)
{ {
return pref->getInt("networkcount", 0); return pref->getInt("networkcount", 0);
} }
void saveNetworkCount(Preferences *pref, int count) void saveNetworkCount(Preferences *pref, const int count)
{ {
pref->putInt("networkcount", count); pref->putInt("networkcount", count);
} }
@@ -19,10 +21,9 @@ ProjectConfig::ProjectConfig(Preferences *pref) : pref(pref),
MDNSConfig_t(pref), MDNSConfig_t(pref),
WiFiTxPower_t(pref)) {} WiFiTxPower_t(pref)) {}
ProjectConfig::~ProjectConfig() {} ProjectConfig::~ProjectConfig() = default;
void ProjectConfig::save() void ProjectConfig::save() const {
{
ESP_LOGD(CONFIGURATION_TAG, "Saving project config"); ESP_LOGD(CONFIGURATION_TAG, "Saving project config");
this->config.device.save(); this->config.device.save();
this->config.camera.save(); this->config.camera.save();
@@ -30,7 +31,7 @@ void ProjectConfig::save()
this->config.txpower.save(); this->config.txpower.save();
this->config.ap_network.save(); this->config.ap_network.save();
auto networks_count = this->config.networks.size(); auto const networks_count = static_cast<int>(this->config.networks.size());
for (int i = 0; i < networks_count; i++) for (int i = 0; i < networks_count; i++)
{ {
this->config.networks[i].save(); this->config.networks[i].save();
@@ -54,7 +55,7 @@ void ProjectConfig::load()
return; return;
} }
bool success = this->pref->begin("openiris"); const bool success = this->pref->begin("openiris");
ESP_LOGI(CONFIGURATION_TAG, "Config name: openiris"); ESP_LOGI(CONFIGURATION_TAG, "Config name: openiris");
ESP_LOGI(CONFIGURATION_TAG, "Config loaded: %s", success ? "true" : "false"); ESP_LOGI(CONFIGURATION_TAG, "Config loaded: %s", success ? "true" : "false");
@@ -65,7 +66,7 @@ void ProjectConfig::load()
this->config.txpower.load(); this->config.txpower.load();
this->config.ap_network.load(); this->config.ap_network.load();
auto networks_count = getNetworkCount(this->pref); const auto networks_count = getNetworkCount(this->pref);
ESP_LOGD(CONFIGURATION_TAG, "Loading networks: %d", networks_count); ESP_LOGD(CONFIGURATION_TAG, "Loading networks: %d", networks_count);
for (int i = 0; i < getNetworkCount(this->pref); i++) for (int i = 0; i < getNetworkCount(this->pref); i++)
{ {
@@ -90,7 +91,7 @@ bool ProjectConfig::reset()
//********************************************************************************************************************** //**********************************************************************************************************************
void ProjectConfig::setDeviceConfig(const std::string &OTALogin, void ProjectConfig::setDeviceConfig(const std::string &OTALogin,
const std::string &OTAPassword, const std::string &OTAPassword,
int OTAPort) const int OTAPort)
{ {
ESP_LOGD(CONFIGURATION_TAG, "Updating device config"); ESP_LOGD(CONFIGURATION_TAG, "Updating device config");
this->config.device.OTALogin.assign(OTALogin); this->config.device.OTALogin.assign(OTALogin);
@@ -104,11 +105,11 @@ void ProjectConfig::setMDNSConfig(const std::string &hostname)
this->config.mdns.hostname.assign(hostname); this->config.mdns.hostname.assign(hostname);
} }
void ProjectConfig::setCameraConfig(uint8_t vflip, void ProjectConfig::setCameraConfig(const uint8_t vflip,
uint8_t framesize, const uint8_t framesize,
uint8_t href, const uint8_t href,
uint8_t quality, const uint8_t quality,
uint8_t brightness) const uint8_t brightness)
{ {
ESP_LOGD(CONFIGURATION_TAG, "Updating camera config"); ESP_LOGD(CONFIGURATION_TAG, "Updating camera config");
this->config.camera.vflip = vflip; this->config.camera.vflip = vflip;
@@ -126,13 +127,11 @@ void ProjectConfig::setWifiConfig(const std::string &networkName,
uint8_t channel, uint8_t channel,
uint8_t power) uint8_t power)
{ {
size_t size = this->config.networks.size(); const auto size = this->config.networks.size();
auto it = std::find_if( const auto it = std::ranges::find_if(this->config.networks,
this->config.networks.begin(), [&](const WiFiConfig_t &network)
this->config.networks.end(), { return network.name == networkName; });
[&](WiFiConfig_t &network)
{ return network.name == networkName; });
if (it != this->config.networks.end()) if (it != this->config.networks.end())
{ {
@@ -151,7 +150,7 @@ void ProjectConfig::setWifiConfig(const std::string &networkName,
if (size == 0) if (size == 0)
{ {
ESP_LOGI(CONFIGURATION_TAG, "No networks, We're adding a new network"); ESP_LOGI(CONFIGURATION_TAG, "No networks, We're adding a new network");
this->config.networks.emplace_back(this->pref, (uint8_t)0, networkName, ssid, password, channel, this->config.networks.emplace_back(this->pref, static_cast<uint8_t>(0), networkName, ssid, password, channel,
power); power);
return; return;
} }
@@ -175,17 +174,14 @@ void ProjectConfig::setWifiConfig(const std::string &networkName,
void ProjectConfig::deleteWifiConfig(const std::string &networkName) void ProjectConfig::deleteWifiConfig(const std::string &networkName)
{ {
size_t size = this->config.networks.size(); if (const auto size = this->config.networks.size(); size == 0)
if (size == 0)
{ {
ESP_LOGI(CONFIGURATION_TAG, "No networks, nothing to delete"); ESP_LOGI(CONFIGURATION_TAG, "No networks, nothing to delete");
} }
auto it = std::find_if( const auto it = std::ranges::find_if(this->config.networks,
this->config.networks.begin(), [&](const WiFiConfig_t &network)
this->config.networks.end(), { return network.name == networkName; });
[&](WiFiConfig_t &network)
{ return network.name == networkName; });
if (it != this->config.networks.end()) if (it != this->config.networks.end())
{ {
@@ -203,7 +199,7 @@ void ProjectConfig::setWiFiTxPower(uint8_t power)
void ProjectConfig::setAPWifiConfig(const std::string &ssid, void ProjectConfig::setAPWifiConfig(const std::string &ssid,
const std::string &password, const std::string &password,
uint8_t channel) const uint8_t channel)
{ {
this->config.ap_network.ssid.assign(ssid); this->config.ap_network.ssid.assign(ssid);
this->config.ap_network.password.assign(password); this->config.ap_network.password.assign(password);

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#ifndef _PROJECT_CONFIG_HPP_ #ifndef PROJECT_CONFIG_HPP
#define _PROJECT_CONFIG_HPP_ #define PROJECT_CONFIG_HPP
#include "esp_log.h" #include "esp_log.h"
#include <algorithm> #include <algorithm>
#include <vector> #include <vector>
@@ -9,7 +9,6 @@
#include "Models.hpp" #include "Models.hpp"
#include <Preferences.hpp> #include <Preferences.hpp>
static const char *CONFIGURATION_TAG = "[CONFIGURATION]";
int getNetworkCount(Preferences *pref); int getNetworkCount(Preferences *pref);
@@ -18,11 +17,11 @@ void saveNetworkCount(Preferences *pref, int count);
class ProjectConfig class ProjectConfig
{ {
public: public:
ProjectConfig(Preferences *pref); explicit ProjectConfig(Preferences *pref);
virtual ~ProjectConfig(); virtual ~ProjectConfig();
void load(); void load();
void save(); void save() const;
void wifiConfigSave(); void wifiConfigSave();
void cameraConfigSave(); void cameraConfigSave();

View File

@@ -1,10 +1,12 @@
#include "RestAPI.hpp" #include "RestAPI.hpp"
#include <utility>
#define POST_METHOD "POST" #define POST_METHOD "POST"
RestAPI::RestAPI(std::string url, std::shared_ptr<CommandManager> commandManager) : command_manager(commandManager) RestAPI::RestAPI(std::string url, std::shared_ptr<CommandManager> commandManager) : command_manager(commandManager)
{ {
this->url = url; this->url = std::move(url);
// updates // updates
routes.emplace("/api/update/wifi/", &RestAPI::handle_update_wifi); routes.emplace("/api/update/wifi/", &RestAPI::handle_update_wifi);
routes.emplace("/api/update/device/", &RestAPI::handle_update_device); routes.emplace("/api/update/device/", &RestAPI::handle_update_device);
@@ -40,13 +42,12 @@ void RestAPI::handle_request(struct mg_connection *connection, int event, void *
{ {
if (event == MG_EV_HTTP_MSG) if (event == MG_EV_HTTP_MSG)
{ {
struct mg_http_message *message = (struct mg_http_message *)event_data; auto const *message = static_cast<struct mg_http_message *>(event_data);
std::string uri = std::string(message->uri.buf, message->uri.len); auto const uri = std::string(message->uri.buf, message->uri.len);
auto handler = this->routes[uri];
if (handler) if (auto const handler = this->routes[uri])
{ {
RequestContext *context = new RequestContext{ auto *context = new RequestContext{
.connection = connection, .connection = connection,
.method = std::string(message->method.buf, message->method.len), .method = std::string(message->method.buf, message->method.len),
.body = std::string(message->body.buf, message->body.len), .body = std::string(message->body.buf, message->body.len),
@@ -62,7 +63,7 @@ void RestAPI::handle_request(struct mg_connection *connection, int event, void *
void RestAPIHelpers::event_handler(struct mg_connection *connection, int event, void *event_data) void RestAPIHelpers::event_handler(struct mg_connection *connection, int event, void *event_data)
{ {
RestAPI *rest_api_handler = static_cast<RestAPI *>(connection->fn_data); auto *rest_api_handler = static_cast<RestAPI *>(connection->fn_data);
rest_api_handler->handle_request(connection, event, event_data); rest_api_handler->handle_request(connection, event, event_data);
} }
@@ -73,8 +74,8 @@ void RestAPI::poll()
void HandleRestAPIPollTask(void *pvParameter) void HandleRestAPIPollTask(void *pvParameter)
{ {
RestAPI *rest_api_handler = static_cast<RestAPI *>(pvParameter); auto *rest_api_handler = static_cast<RestAPI *>(pvParameter);
while (1) while (true)
{ {
rest_api_handler->poll(); rest_api_handler->poll();
vTaskDelay(1000); vTaskDelay(1000);
@@ -83,72 +84,66 @@ void HandleRestAPIPollTask(void *pvParameter)
// COMMANDS // COMMANDS
// updates // updates
void RestAPI::handle_update_wifi(RequestContext *context) void RestAPI::handle_update_wifi(RequestContext *context) {
{
if (context->method != POST_METHOD) if (context->method != POST_METHOD)
{ {
mg_http_reply(context->connection, 401, JSON_RESPONSE, "{%m:%m}", MG_ESC("error"), "Method not allowed"); mg_http_reply(context->connection, 401, JSON_RESPONSE, "{%m:%m}", MG_ESC("error"), "Method not allowed");
return; return;
} }
auto result = command_manager->executeFromType(CommandType::UPDATE_WIFI, context->body); auto const result = command_manager->executeFromType(CommandType::UPDATE_WIFI, context->body);
int code = result.isSuccess() ? 200 : 500; auto const code = result.isSuccess() ? 200 : 500;
mg_http_reply(context->connection, code, JSON_RESPONSE, result.getResult().c_str()); mg_http_reply(context->connection, code, JSON_RESPONSE, result.getResult().c_str());
} }
void RestAPI::handle_update_device(RequestContext *context) void RestAPI::handle_update_device(RequestContext *context) {
{
if (context->method != POST_METHOD) if (context->method != POST_METHOD)
{ {
mg_http_reply(context->connection, 401, JSON_RESPONSE, "{%m:%m}", MG_ESC("error"), "Method not allowed"); mg_http_reply(context->connection, 401, JSON_RESPONSE, "{%m:%m}", MG_ESC("error"), "Method not allowed");
return; return;
} }
auto result = command_manager->executeFromType(CommandType::UPDATE_DEVICE, context->body); auto const result = command_manager->executeFromType(CommandType::UPDATE_DEVICE, context->body);
int code = result.isSuccess() ? 200 : 500; auto const code = result.isSuccess() ? 200 : 500;
mg_http_reply(context->connection, code, JSON_RESPONSE, result.getResult().c_str()); mg_http_reply(context->connection, code, JSON_RESPONSE, result.getResult().c_str());
} }
void RestAPI::handle_update_camera(RequestContext *context) void RestAPI::handle_update_camera(RequestContext *context) {
{
if (context->method != POST_METHOD) if (context->method != POST_METHOD)
{ {
mg_http_reply(context->connection, 401, JSON_RESPONSE, "{%m:%m}", MG_ESC("error"), "Method not allowed"); mg_http_reply(context->connection, 401, JSON_RESPONSE, "{%m:%m}", MG_ESC("error"), "Method not allowed");
return; return;
} }
auto result = command_manager->executeFromType(CommandType::UPDATE_CAMERA, context->body); auto const result = command_manager->executeFromType(CommandType::UPDATE_CAMERA, context->body);
int code = result.isSuccess() ? 200 : 500; auto const code = result.isSuccess() ? 200 : 500;
mg_http_reply(context->connection, code, JSON_RESPONSE, result.getResult().c_str()); mg_http_reply(context->connection, code, JSON_RESPONSE, result.getResult().c_str());
} }
// gets // gets
void RestAPI::handle_get_config(RequestContext *context) void RestAPI::handle_get_config(RequestContext *context) {
{ auto const result = this->command_manager->executeFromType(CommandType::GET_CONFIG, "");
auto result = this->command_manager->executeFromType(CommandType::GET_CONFIG, "");
mg_http_reply(context->connection, 200, JSON_RESPONSE, "{%m:%m}", MG_ESC("result"), result.getResult()); mg_http_reply(context->connection, 200, JSON_RESPONSE, "{%m:%m}", MG_ESC("result"), result.getResult());
} }
// resets // resets
void RestAPI::handle_reset_config(RequestContext *context) void RestAPI::handle_reset_config(RequestContext *context) {
{
if (context->method != POST_METHOD) if (context->method != POST_METHOD)
{ {
mg_http_reply(context->connection, 401, JSON_RESPONSE, "{%m:%m}", MG_ESC("error"), "Method not allowed"); mg_http_reply(context->connection, 401, JSON_RESPONSE, "{%m:%m}", MG_ESC("error"), "Method not allowed");
return; return;
} }
auto result = this->command_manager->executeFromType(CommandType::RESET_CONFIG, "{\"section\": \"all\"}"); auto const result = this->command_manager->executeFromType(CommandType::RESET_CONFIG, "{\"section\": \"all\"}");
int code = result.isSuccess() ? 200 : 500; auto const code = result.isSuccess() ? 200 : 500;
mg_http_reply(context->connection, code, JSON_RESPONSE, "{%m:%m}", MG_ESC("result"), result.getResult()); mg_http_reply(context->connection, code, JSON_RESPONSE, "{%m:%m}", MG_ESC("result"), result.getResult());
} }
// reboots // reboots
void RestAPI::handle_reboot(RequestContext *context) void RestAPI::handle_reboot(RequestContext *context) {
{ auto const result = this->command_manager->executeFromType(CommandType::RESTART_DEVICE, "");
auto result = this->command_manager->executeFromType(CommandType::RESTART_DEVICE, "");
mg_http_reply(context->connection, 200, JSON_RESPONSE, "{%m:%m}", MG_ESC("result"), "Ok"); mg_http_reply(context->connection, 200, JSON_RESPONSE, "{%m:%m}", MG_ESC("result"), "Ok");
} }
@@ -159,18 +154,16 @@ void RestAPI::handle_camera_reboot(RequestContext *context)
// heartbeat // heartbeat
void RestAPI::pong(RequestContext *context) void RestAPI::pong(RequestContext *context) {
{ auto const result = this->command_manager->executeFromType(CommandType::PING, "");
CommandResult result = this->command_manager->executeFromType(CommandType::PING, ""); auto const code = result.isSuccess() ? 200 : 500;
int code = result.isSuccess() ? 200 : 500;
mg_http_reply(context->connection, code, JSON_RESPONSE, result.getResult().c_str()); mg_http_reply(context->connection, code, JSON_RESPONSE, result.getResult().c_str());
} }
// special // special
void RestAPI::handle_save(RequestContext *context) void RestAPI::handle_save(RequestContext *context) {
{ auto const result = this->command_manager->executeFromType(CommandType::SAVE_CONFIG, "");
CommandResult result = this->command_manager->executeFromType(CommandType::SAVE_CONFIG, ""); auto const code = result.isSuccess() ? 200 : 500;
int code = result.isSuccess() ? 200 : 500;
mg_http_reply(context->connection, code, JSON_RESPONSE, result.getResult().c_str()); mg_http_reply(context->connection, code, JSON_RESPONSE, result.getResult().c_str());
} }

View File

@@ -25,7 +25,7 @@ class RestAPI
std::string url; std::string url;
route_map routes; route_map routes;
struct mg_mgr mgr; mg_mgr mgr;
std::shared_ptr<CommandManager> command_manager; std::shared_ptr<CommandManager> command_manager;
private: private:

View File

@@ -10,7 +10,10 @@
#define BUF_SIZE (1024) #define BUF_SIZE (1024)
SerialManager::SerialManager(std::shared_ptr<CommandManager> commandManager) : commandManager(commandManager) {} SerialManager::SerialManager(std::shared_ptr<CommandManager> commandManager) : commandManager(commandManager) {
this->data = static_cast<uint8_t *>(malloc(BUF_SIZE));
this->temp_data = static_cast<uint8_t *>(malloc(256));
}
void SerialManager::setup() void SerialManager::setup()
{ {
@@ -18,9 +21,6 @@ void SerialManager::setup()
usb_serial_jtag_config.rx_buffer_size = BUF_SIZE; usb_serial_jtag_config.rx_buffer_size = BUF_SIZE;
usb_serial_jtag_config.tx_buffer_size = BUF_SIZE; usb_serial_jtag_config.tx_buffer_size = BUF_SIZE;
usb_serial_jtag_driver_install(&usb_serial_jtag_config); usb_serial_jtag_driver_install(&usb_serial_jtag_config);
// Configure a temporary buffer for the incoming data
this->data = (uint8_t *)malloc(BUF_SIZE);
this->temp_data = (uint8_t *)malloc(256);
} }
void SerialManager::try_receive() void SerialManager::try_receive()
@@ -43,17 +43,17 @@ void SerialManager::try_receive()
data[current_position] = '\0'; data[current_position] = '\0';
current_position = 0; current_position = 0;
auto result = this->commandManager->executeFromJson(std::string_view((const char *)this->data)); const auto result = this->commandManager->executeFromJson(std::string_view(reinterpret_cast<const char *>(this->data)));
auto resultMessage = result.getResult(); const auto resultMessage = result.getResult();
usb_serial_jtag_write_bytes(resultMessage.c_str(), resultMessage.length(), 1000 / 20); usb_serial_jtag_write_bytes(resultMessage.c_str(), resultMessage.length(), 1000 / 20);
} }
} }
void HandleSerialManagerTask(void *pvParameters) void HandleSerialManagerTask(void *pvParameters)
{ {
auto serialManager = static_cast<SerialManager *>(pvParameters); auto const serialManager = static_cast<SerialManager *>(pvParameters);
while (1) while (true)
{ {
serialManager->try_receive(); serialManager->try_receive();
} }

View File

@@ -19,12 +19,12 @@
class SerialManager class SerialManager
{ {
public: public:
SerialManager(std::shared_ptr<CommandManager> commandManager); explicit SerialManager(std::shared_ptr<CommandManager> commandManager);
void setup(); void setup();
void try_receive(); void try_receive();
private: private:
QueueHandle_t serialQueue; // QueueHandle_t serialQueue;
std::shared_ptr<CommandManager> commandManager; std::shared_ptr<CommandManager> commandManager;
uint8_t *data; uint8_t *data;
uint8_t *temp_data; uint8_t *temp_data;

View File

@@ -5,7 +5,7 @@ StateManager::StateManager(QueueHandle_t eventQueue, QueueHandle_t ledStateQueue
void StateManager::HandleUpdateState() void StateManager::HandleUpdateState()
{ {
SystemEvent eventBuffer; SystemEvent eventBuffer;
auto ledStreamState = LEDStates_e::_LedStateNone; auto ledStreamState = LEDStates_e::LedStateNone;
if (xQueueReceive(this->eventQueue, &eventBuffer, portMAX_DELAY)) if (xQueueReceive(this->eventQueue, &eventBuffer, portMAX_DELAY))
{ {
@@ -18,17 +18,17 @@ void StateManager::HandleUpdateState()
if (this->wifi_state == WiFiState_e::WiFiState_Connecting) if (this->wifi_state == WiFiState_e::WiFiState_Connecting)
{ {
ledStreamState = LEDStates_e::_WiFiState_Connecting; ledStreamState = LEDStates_e::WiFiStateConnecting;
xQueueSend(this->ledStateQueue, &ledStreamState, 10); xQueueSend(this->ledStateQueue, &ledStreamState, 10);
} }
if (this->wifi_state == WiFiState_e::WiFiState_Connected) if (this->wifi_state == WiFiState_e::WiFiState_Connected)
{ {
ledStreamState = LEDStates_e::_WiFiState_Connected; ledStreamState = LEDStates_e::WiFiStateConnected;
xQueueSend(this->ledStateQueue, &ledStreamState, 10); xQueueSend(this->ledStateQueue, &ledStreamState, 10);
} }
if (this->wifi_state == WiFiState_e::WiFiState_Error) if (this->wifi_state == WiFiState_e::WiFiState_Error)
{ {
ledStreamState = LEDStates_e::_WiFiState_Error; ledStreamState = LEDStates_e::WiFiStateError;
xQueueSend(this->ledStateQueue, &ledStreamState, 10); xQueueSend(this->ledStateQueue, &ledStreamState, 10);
} }
@@ -47,7 +47,7 @@ void StateManager::HandleUpdateState()
if (this->camera_state == CameraState_e::Camera_Error) if (this->camera_state == CameraState_e::Camera_Error)
{ {
ledStreamState = LEDStates_e::_Camera_Error; ledStreamState = LEDStates_e::CameraError;
xQueueSend(this->ledStateQueue, &ledStreamState, 10); xQueueSend(this->ledStateQueue, &ledStreamState, 10);
} }
@@ -60,12 +60,12 @@ void StateManager::HandleUpdateState()
if (this->stream_state == StreamState_e::Stream_ON) if (this->stream_state == StreamState_e::Stream_ON)
{ {
ledStreamState = LEDStates_e::_LedStateStreaming; ledStreamState = LEDStates_e::LedStateStreaming;
xQueueSend(this->ledStateQueue, &ledStreamState, 10); xQueueSend(this->ledStateQueue, &ledStreamState, 10);
} }
if (this->stream_state == StreamState_e::Stream_ON) if (this->stream_state == StreamState_e::Stream_ON)
{ {
ledStreamState = LEDStates_e::_LedStateStreaming; ledStreamState = LEDStates_e::LedStateStreaming;
xQueueSend(this->ledStateQueue, &ledStreamState, 10); xQueueSend(this->ledStateQueue, &ledStreamState, 10);
} }
break; break;
@@ -89,9 +89,9 @@ CameraState_e StateManager::GetCameraState()
void HandleStateManagerTask(void *pvParameters) void HandleStateManagerTask(void *pvParameters)
{ {
StateManager *stateManager = static_cast<StateManager *>(pvParameters); auto *stateManager = static_cast<StateManager *>(pvParameters);
while (1) while (true)
{ {
stateManager->HandleUpdateState(); stateManager->HandleUpdateState();
} }

View File

@@ -6,22 +6,22 @@
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/queue.h" #include "freertos/queue.h"
enum LEDStates_e enum class LEDStates_e
{ {
_LedStateNone, LedStateNone,
_LedStateStreaming, LedStateStreaming,
_LedStateStoppedStreaming, LedStateStoppedStreaming,
_Camera_Error, CameraError,
_WiFiState_Error, WiFiStateError,
_WiFiState_Connecting, WiFiStateConnecting,
_WiFiState_Connected WiFiStateConnected
}; };
enum WiFiState_e enum class WiFiState_e
{ {
WiFiState_NotInitialized, WiFiState_NotInitialized,
WiFiState_Initialized, WiFiState_Initialized,
WiFiState_ReadyToConect, WiFiState_ReadyToConnect,
WiFiState_Connecting, WiFiState_Connecting,
WiFiState_WaitingForIp, WiFiState_WaitingForIp,
WiFiState_Connected, WiFiState_Connected,
@@ -29,7 +29,7 @@ enum WiFiState_e
WiFiState_Error WiFiState_Error
}; };
enum MDNSState_e enum class MDNSState_e
{ {
MDNSState_Stopped, MDNSState_Stopped,
MDNSState_Starting, MDNSState_Starting,
@@ -40,14 +40,14 @@ enum MDNSState_e
MDNSState_QueryComplete MDNSState_QueryComplete
}; };
enum CameraState_e enum class CameraState_e
{ {
Camera_Disconnected, Camera_Disconnected,
Camera_Success, Camera_Success,
Camera_Error Camera_Error
}; };
enum StreamState_e enum class StreamState_e
{ {
Stream_OFF, Stream_OFF,
Stream_ON, Stream_ON,

View File

@@ -9,7 +9,6 @@ static esp_err_t UVCStreamHelpers::camera_start_cb(uvc_format_t format, int widt
ESP_LOGI(UVC_STREAM_TAG, "Camera Start"); ESP_LOGI(UVC_STREAM_TAG, "Camera Start");
ESP_LOGI(UVC_STREAM_TAG, "Format: %d, width: %d, height: %d, rate: %d", format, width, height, rate); ESP_LOGI(UVC_STREAM_TAG, "Format: %d, width: %d, height: %d, rate: %d", format, width, height, rate);
framesize_t frame_size = FRAMESIZE_QVGA; framesize_t frame_size = FRAMESIZE_QVGA;
int jpeg_quality = 10;
if (format != UVC_FORMAT_JPEG) if (format != UVC_FORMAT_JPEG)
{ {
@@ -20,7 +19,6 @@ static esp_err_t UVCStreamHelpers::camera_start_cb(uvc_format_t format, int widt
if (width == 240 && height == 240) if (width == 240 && height == 240)
{ {
frame_size = FRAMESIZE_240X240; frame_size = FRAMESIZE_240X240;
jpeg_quality = 10;
} }
else else
{ {
@@ -29,9 +27,9 @@ static esp_err_t UVCStreamHelpers::camera_start_cb(uvc_format_t format, int widt
} }
cameraHandler->setCameraResolution(frame_size); cameraHandler->setCameraResolution(frame_size);
cameraHandler->resetCamera(0); cameraHandler->resetCamera(false);
SystemEvent event = {EventSource::STREAM, StreamState_e::Stream_ON}; constexpr SystemEvent event = {EventSource::STREAM, StreamState_e::Stream_ON};
xQueueSend(eventQueue, &event, 10); xQueueSend(eventQueue, &event, 10);
return ESP_OK; return ESP_OK;
@@ -46,7 +44,7 @@ static void UVCStreamHelpers::camera_stop_cb(void *cb_ctx)
s_fb.cam_fb_p = nullptr; s_fb.cam_fb_p = nullptr;
} }
SystemEvent event = {EventSource::STREAM, StreamState_e::Stream_OFF}; constexpr SystemEvent event = {EventSource::STREAM, StreamState_e::Stream_OFF};
xQueueSend(eventQueue, &event, 10); xQueueSend(eventQueue, &event, 10);
} }
@@ -88,7 +86,7 @@ esp_err_t UVCStreamManager::setup()
{ {
ESP_LOGI(UVC_STREAM_TAG, "Setting up UVC Stream"); ESP_LOGI(UVC_STREAM_TAG, "Setting up UVC Stream");
uvc_buffer = (uint8_t *)malloc(UVC_MAX_FRAMESIZE_SIZE); uvc_buffer = static_cast<uint8_t *>(malloc(UVC_MAX_FRAMESIZE_SIZE));
if (uvc_buffer == nullptr) if (uvc_buffer == nullptr)
{ {
ESP_LOGE(UVC_STREAM_TAG, "Allocating buffer for UVC Device failed"); ESP_LOGE(UVC_STREAM_TAG, "Allocating buffer for UVC Device failed");
@@ -110,10 +108,7 @@ esp_err_t UVCStreamManager::setup()
ESP_LOGE(UVC_STREAM_TAG, "Configuring UVC Device failed: %s", esp_err_to_name(ret)); ESP_LOGE(UVC_STREAM_TAG, "Configuring UVC Device failed: %s", esp_err_to_name(ret));
return ret; return ret;
} }
else ESP_LOGI(UVC_STREAM_TAG, "Configured UVC Device");
{
ESP_LOGI(UVC_STREAM_TAG, "Configured UVC Device");
}
ESP_LOGI(UVC_STREAM_TAG, "Initializing UVC Device"); ESP_LOGI(UVC_STREAM_TAG, "Initializing UVC Device");
ret = uvc_device_init(); ret = uvc_device_init();
@@ -122,10 +117,7 @@ esp_err_t UVCStreamManager::setup()
ESP_LOGE(UVC_STREAM_TAG, "Initializing UVC Device failed: %s", esp_err_to_name(ret)); ESP_LOGE(UVC_STREAM_TAG, "Initializing UVC Device failed: %s", esp_err_to_name(ret));
return ret; return ret;
} }
else ESP_LOGI(UVC_STREAM_TAG, "Initialized UVC Device");
{
ESP_LOGI(UVC_STREAM_TAG, "Initialized UVC Device");
}
return ESP_OK; return ESP_OK;
} }

View File

@@ -19,7 +19,7 @@ extern QueueHandle_t eventQueue;
namespace UVCStreamHelpers namespace UVCStreamHelpers
{ {
// TODO move the camera handling code to the camera manager and have the uvc maanger initialize it in wired mode // TODO move the camera handling code to the camera manager and have the uvc manager initialize it in wired mode
typedef struct typedef struct
{ {

View File

@@ -14,13 +14,13 @@ void LoggerHelpers::ws_async_send(void *arg)
{ {
char *log_buffer = webSocketLogger.get_websocket_log_buffer(); char *log_buffer = webSocketLogger.get_websocket_log_buffer();
struct async_resp_arg *resp_arg = (struct async_resp_arg *)arg; const auto *resp_arg = static_cast<struct async_resp_arg *>(arg);
httpd_handle_t hd = resp_arg->hd; const auto hd = resp_arg->hd;
int fd = resp_arg->fd; const auto fd = resp_arg->fd;
httpd_ws_frame_t websocket_packet = httpd_ws_frame_t{}; auto websocket_packet = httpd_ws_frame_t{};
websocket_packet.payload = (uint8_t *)log_buffer; websocket_packet.payload = reinterpret_cast<uint8_t *>(log_buffer);
websocket_packet.len = strlen(log_buffer); websocket_packet.len = strlen(log_buffer);
websocket_packet.type = HTTPD_WS_TYPE_TEXT; websocket_packet.type = HTTPD_WS_TYPE_TEXT;

View File

@@ -20,9 +20,8 @@ namespace LoggerHelpers
class WebSocketLogger class WebSocketLogger
{ {
private: async_resp_arg connected_socket_client{};
async_resp_arg connected_socket_client; char ws_log_buffer[WS_LOG_BUFFER_LEN]{};
char ws_log_buffer[WS_LOG_BUFFER_LEN];
public: public:
WebSocketLogger(); WebSocketLogger();

View File

@@ -1,15 +1,16 @@
#include "wifiManager.hpp" #include "wifiManager.hpp"
static auto WIFI_MANAGER_TAG = "[WIFI_MANAGER]";
void WiFiManagerHelpers::event_handler(void *arg, esp_event_base_t event_base, void WiFiManagerHelpers::event_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data) int32_t event_id, void *event_data)
{ {
ESP_LOGI(WIFI_MAMANGER_TAG, "Trying to connect, got event: %d", (int)event_id); ESP_LOGI(WIFI_MANAGER_TAG, "Trying to connect, got event: %d", (int)event_id);
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
{ {
esp_err_t err = esp_wifi_connect(); if (const auto err = esp_wifi_connect(); err != ESP_OK)
if (err != ESP_OK)
{ {
ESP_LOGI(WIFI_MAMANGER_TAG, "esp_wifi_connect() failed: %s", esp_err_to_name(err)); ESP_LOGI(WIFI_MANAGER_TAG, "esp_wifi_connect() failed: %s", esp_err_to_name(err));
} }
} }
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
@@ -18,19 +19,19 @@ void WiFiManagerHelpers::event_handler(void *arg, esp_event_base_t event_base,
{ {
esp_wifi_connect(); esp_wifi_connect();
s_retry_num++; s_retry_num++;
ESP_LOGI(WIFI_MAMANGER_TAG, "retry to connect to the AP"); ESP_LOGI(WIFI_MANAGER_TAG, "retry to connect to the AP");
} }
else else
{ {
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT); xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
} }
ESP_LOGI(WIFI_MAMANGER_TAG, "connect to the AP fail"); ESP_LOGI(WIFI_MANAGER_TAG, "connect to the AP fail");
} }
else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
{ {
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data; const auto *event = static_cast<ip_event_got_ip_t *>(event_data);
ESP_LOGI(WIFI_MAMANGER_TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip)); ESP_LOGI(WIFI_MANAGER_TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
s_retry_num = 0; s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
} }
@@ -47,7 +48,7 @@ void WiFiManager::SetCredentials(const char *ssid, const char *password)
void WiFiManager::ConnectWithHardcodedCredentials() void WiFiManager::ConnectWithHardcodedCredentials()
{ {
SystemEvent event = {EventSource::WIFI, WiFiState_e::WiFiState_ReadyToConect}; SystemEvent event = {EventSource::WIFI, WiFiState_e::WiFiState_ReadyToConnect};
this->SetCredentials(CONFIG_WIFI_SSID, CONFIG_WIFI_PASSWORD); this->SetCredentials(CONFIG_WIFI_SSID, CONFIG_WIFI_PASSWORD);
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &_wifi_cfg)); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &_wifi_cfg));
@@ -67,7 +68,7 @@ void WiFiManager::ConnectWithHardcodedCredentials()
* happened. */ * happened. */
if (bits & WIFI_CONNECTED_BIT) if (bits & WIFI_CONNECTED_BIT)
{ {
ESP_LOGI(WIFI_MAMANGER_TAG, "connected to ap SSID:%s password:%s", ESP_LOGI(WIFI_MANAGER_TAG, "connected to ap SSID:%p password:%p",
_wifi_cfg.sta.ssid, _wifi_cfg.sta.password); _wifi_cfg.sta.ssid, _wifi_cfg.sta.password);
event.value = WiFiState_e::WiFiState_Connected; event.value = WiFiState_e::WiFiState_Connected;
@@ -76,7 +77,7 @@ void WiFiManager::ConnectWithHardcodedCredentials()
else if (bits & WIFI_FAIL_BIT) else if (bits & WIFI_FAIL_BIT)
{ {
ESP_LOGE(WIFI_MAMANGER_TAG, "Failed to connect to SSID:%s, password:%s", ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to SSID:%p, password:%p",
_wifi_cfg.sta.ssid, _wifi_cfg.sta.password); _wifi_cfg.sta.ssid, _wifi_cfg.sta.password);
event.value = WiFiState_e::WiFiState_Error; event.value = WiFiState_e::WiFiState_Error;
@@ -84,30 +85,30 @@ void WiFiManager::ConnectWithHardcodedCredentials()
} }
else else
{ {
ESP_LOGE(WIFI_MAMANGER_TAG, "UNEXPECTED EVENT"); ESP_LOGE(WIFI_MANAGER_TAG, "UNEXPECTED EVENT");
} }
} }
void WiFiManager::ConnectWithStoredCredentials() void WiFiManager::ConnectWithStoredCredentials()
{ {
SystemEvent event = {EventSource::WIFI, WiFiState_e::WiFiState_ReadyToConect}; SystemEvent event = {EventSource::WIFI, WiFiState_e::WiFiState_ReadyToConnect};
auto networks = this->deviceConfig->getWifiConfigs(); auto const networks = this->deviceConfig->getWifiConfigs();
if (networks.size() == 0) if (networks.empty())
{ {
event.value = WiFiState_e::WiFiState_Disconnected; event.value = WiFiState_e::WiFiState_Disconnected;
xQueueSend(this->eventQueue, &event, 10); xQueueSend(this->eventQueue, &event, 10);
ESP_LOGE(WIFI_MAMANGER_TAG, "No networks stored, cannot connect"); ESP_LOGE(WIFI_MANAGER_TAG, "No networks stored, cannot connect");
return; return;
} }
for (auto network : networks) for (const auto& network : networks)
{ {
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT); xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT);
this->SetCredentials(network.ssid.c_str(), network.password.c_str()); this->SetCredentials(network.ssid.c_str(), network.password.c_str());
// we need to update the config after every credentials change // we need to update the config after every credential change
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &_wifi_cfg)); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &_wifi_cfg));
xQueueSend(this->eventQueue, &event, 10); xQueueSend(this->eventQueue, &event, 10);
@@ -123,7 +124,7 @@ void WiFiManager::ConnectWithStoredCredentials()
portMAX_DELAY); portMAX_DELAY);
if (bits & WIFI_CONNECTED_BIT) if (bits & WIFI_CONNECTED_BIT)
{ {
ESP_LOGI(WIFI_MAMANGER_TAG, "connected to ap SSID:%s password:%s", ESP_LOGI(WIFI_MANAGER_TAG, "connected to ap SSID:%p password:%p",
_wifi_cfg.sta.ssid, _wifi_cfg.sta.password); _wifi_cfg.sta.ssid, _wifi_cfg.sta.password);
event.value = WiFiState_e::WiFiState_Connected; event.value = WiFiState_e::WiFiState_Connected;
@@ -131,18 +132,18 @@ void WiFiManager::ConnectWithStoredCredentials()
return; return;
} }
ESP_LOGE(WIFI_MAMANGER_TAG, "Failed to connect to SSID:%s, password:%s, trying next stored network", ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to SSID:%p, password:%p, trying next stored network",
_wifi_cfg.sta.ssid, _wifi_cfg.sta.password); _wifi_cfg.sta.ssid, _wifi_cfg.sta.password);
} }
event.value = WiFiState_e::WiFiState_Error; event.value = WiFiState_e::WiFiState_Error;
xQueueSend(this->eventQueue, &event, 10); xQueueSend(this->eventQueue, &event, 10);
ESP_LOGE(WIFI_MAMANGER_TAG, "Failed to connect to all saved networks"); ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to all saved networks");
} }
void WiFiManager::SetupAccessPoint() void WiFiManager::SetupAccessPoint()
{ {
ESP_LOGI(WIFI_MAMANGER_TAG, "Connection to stored credentials failed, starting AP"); ESP_LOGI(WIFI_MANAGER_TAG, "Connection to stored credentials failed, starting AP");
esp_netif_create_default_wifi_ap(); esp_netif_create_default_wifi_ap();
wifi_init_config_t esp_wifi_ap_init_config = WIFI_INIT_CONFIG_DEFAULT(); wifi_init_config_t esp_wifi_ap_init_config = WIFI_INIT_CONFIG_DEFAULT();
@@ -161,7 +162,7 @@ void WiFiManager::SetupAccessPoint()
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP)); ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap_wifi_config)); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap_wifi_config));
ESP_ERROR_CHECK(esp_wifi_start()); ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(WIFI_MAMANGER_TAG, "AP started."); ESP_LOGI(WIFI_MANAGER_TAG, "AP started.");
} }
void WiFiManager::Begin() void WiFiManager::Begin()
@@ -178,12 +179,12 @@ void WiFiManager::Begin()
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
ESP_EVENT_ANY_ID, ESP_EVENT_ANY_ID,
&WiFiManagerHelpers::event_handler, &WiFiManagerHelpers::event_handler,
NULL, nullptr,
&instance_any_id)); &instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
IP_EVENT_STA_GOT_IP, IP_EVENT_STA_GOT_IP,
&WiFiManagerHelpers::event_handler, &WiFiManagerHelpers::event_handler,
NULL, nullptr,
&instance_got_ip)); &instance_got_ip));
_wifi_cfg = {}; _wifi_cfg = {};
@@ -193,24 +194,24 @@ void WiFiManager::Begin()
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_LOGI(WIFI_MAMANGER_TAG, "Beginning setup"); ESP_LOGI(WIFI_MANAGER_TAG, "Beginning setup");
bool hasHardcodedCredentials = strlen(CONFIG_WIFI_SSID) > 0; const auto hasHardcodedCredentials = strlen(CONFIG_WIFI_SSID) > 0;
if (hasHardcodedCredentials) if (hasHardcodedCredentials)
{ {
ESP_LOGI(WIFI_MAMANGER_TAG, "Detected hardcoded credentials, trying them out"); ESP_LOGI(WIFI_MANAGER_TAG, "Detected hardcoded credentials, trying them out");
this->ConnectWithHardcodedCredentials(); this->ConnectWithHardcodedCredentials();
} }
if (this->stateManager->GetWifiState() != WiFiState_e::WiFiState_Connected || !hasHardcodedCredentials) if (this->stateManager->GetWifiState() != WiFiState_e::WiFiState_Connected || !hasHardcodedCredentials)
{ {
ESP_LOGI(WIFI_MAMANGER_TAG, "Hardcoded credentials failed or missing, trying stored credentials"); ESP_LOGI(WIFI_MANAGER_TAG, "Hardcoded credentials failed or missing, trying stored credentials");
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT); xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT);
this->ConnectWithStoredCredentials(); this->ConnectWithStoredCredentials();
} }
if (this->stateManager->GetWifiState() != WiFiState_e::WiFiState_Connected) if (this->stateManager->GetWifiState() != WiFiState_e::WiFiState_Connected)
{ {
ESP_LOGI(WIFI_MAMANGER_TAG, "Stored netoworks failed or hardcoded credentials missing, starting AP"); ESP_LOGI(WIFI_MANAGER_TAG, "Stored netoworks failed or hardcoded credentials missing, starting AP");
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT); xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT);
esp_netif_destroy(netif); esp_netif_destroy(netif);
this->SetupAccessPoint(); this->SetupAccessPoint();

View File

@@ -18,7 +18,6 @@
static int s_retry_num = 0; static int s_retry_num = 0;
static EventGroupHandle_t s_wifi_event_group; static EventGroupHandle_t s_wifi_event_group;
static const char *WIFI_MAMANGER_TAG = "[WIFI_MANAGER]";
namespace WiFiManagerHelpers namespace WiFiManagerHelpers
{ {

View File

@@ -1,4 +1,4 @@
#include <stdio.h> #include <cstdio>
#include <string> #include <string>
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
@@ -6,9 +6,7 @@
#include "driver/gpio.h" #include "driver/gpio.h"
#include "esp_log.h" #include "esp_log.h"
#include "sdkconfig.h" #include "sdkconfig.h"
#include "esp_camera.h"
#include "nvs_flash.h" #include "nvs_flash.h"
#include "esp_psram.h"
#include <openiris_logo.hpp> #include <openiris_logo.hpp>
#include <wifiManager.hpp> #include <wifiManager.hpp>
@@ -23,8 +21,6 @@
#include <SerialManager.hpp> #include <SerialManager.hpp>
#include <RestAPI.hpp> #include <RestAPI.hpp>
#include <stdarg.h>
#ifdef CONFIG_WIRED_MODE #ifdef CONFIG_WIRED_MODE
#include <UVCStream.hpp> #include <UVCStream.hpp>
#endif #endif
@@ -32,34 +28,31 @@
#define BLINK_GPIO (gpio_num_t) CONFIG_BLINK_GPIO #define BLINK_GPIO (gpio_num_t) CONFIG_BLINK_GPIO
#define CONFIG_LED_C_PIN_GPIO (gpio_num_t) CONFIG_LED_C_PIN #define CONFIG_LED_C_PIN_GPIO (gpio_num_t) CONFIG_LED_C_PIN
static const char *TAG = "[MAIN]";
QueueHandle_t eventQueue = xQueueCreate(10, sizeof(SystemEvent)); QueueHandle_t eventQueue = xQueueCreate(10, sizeof(SystemEvent));
QueueHandle_t ledStateQueue = xQueueCreate(10, sizeof(uint32_t)); QueueHandle_t ledStateQueue = xQueueCreate(10, sizeof(uint32_t));
StateManager *stateManager = new StateManager(eventQueue, ledStateQueue); auto *stateManager = new StateManager(eventQueue, ledStateQueue);
std::shared_ptr<DependencyRegistry> dependencyRegistry = std::make_shared<DependencyRegistry>(); auto dependencyRegistry = std::make_shared<DependencyRegistry>();
std::shared_ptr<CommandManager> commandManager = std::make_shared<CommandManager>(dependencyRegistry); auto commandManager = std::make_shared<CommandManager>(dependencyRegistry);
WebSocketLogger webSocketLogger; WebSocketLogger webSocketLogger;
Preferences preferences; Preferences preferences;
std::shared_ptr<ProjectConfig> deviceConfig = std::make_shared<ProjectConfig>(&preferences); auto deviceConfig = std::make_shared<ProjectConfig>(&preferences);
WiFiManager wifiManager(deviceConfig, eventQueue, stateManager); WiFiManager wifiManager(deviceConfig, eventQueue, stateManager);
MDNSManager mdnsManager(deviceConfig, eventQueue); MDNSManager mdnsManager(deviceConfig, eventQueue);
std::shared_ptr<CameraManager> cameraHandler = std::make_shared<CameraManager>(deviceConfig, eventQueue); std::shared_ptr<CameraManager> cameraHandler = std::make_shared<CameraManager>(deviceConfig, eventQueue);
StreamServer streamServer(80, stateManager); StreamServer streamServer(80, stateManager);
RestAPI *restAPI = new RestAPI("http://0.0.0.0:81", commandManager); auto *restAPI = new RestAPI("http://0.0.0.0:81", commandManager);
#ifdef CONFIG_WIRED_MODE #ifdef CONFIG_WIRED_MODE
UVCStreamManager uvcStream; UVCStreamManager uvcStream;
#endif #endif
LEDManager *ledManager = new LEDManager(BLINK_GPIO, CONFIG_LED_C_PIN_GPIO, ledStateQueue); auto *ledManager = new LEDManager(BLINK_GPIO, CONFIG_LED_C_PIN_GPIO, ledStateQueue);
auto *serialManager = new SerialManager(commandManager);
SerialManager *serialManager = new SerialManager(commandManager);
static void initNVSStorage() static void initNVSStorage()
{ {
@@ -140,7 +133,7 @@ extern "C" void app_main(void)
1024 * 2, 1024 * 2,
stateManager, stateManager,
3, 3,
NULL // it's fine for us not get a handle back, we don't need it nullptr // it's fine for us not get a handle back, we don't need it
); );
xTaskCreate( xTaskCreate(
@@ -149,7 +142,7 @@ extern "C" void app_main(void)
1024 * 2, 1024 * 2,
ledManager, ledManager,
3, 3,
NULL); nullptr);
deviceConfig->load(); deviceConfig->load();
serialManager->setup(); serialManager->setup();
@@ -160,7 +153,7 @@ extern "C" void app_main(void)
1024 * 6, 1024 * 6,
serialManager, serialManager,
1, // we only rely on the serial manager during provisioning, we can run it slower 1, // we only rely on the serial manager during provisioning, we can run it slower
NULL); nullptr);
wifiManager.Begin(); wifiManager.Begin();
mdnsManager.start(); mdnsManager.start();
@@ -175,7 +168,7 @@ extern "C" void app_main(void)
1024 * 2, 1024 * 2,
restAPI, restAPI,
1, // it's the rest API, we only serve commands over it so we don't really need a higher priority 1, // it's the rest API, we only serve commands over it so we don't really need a higher priority
NULL); nullptr);
#ifdef CONFIG_WIRED_MODE #ifdef CONFIG_WIRED_MODE
uvcStream.setup(); uvcStream.setup();