Reformat project using clang-format

This commit is contained in:
Lorow
2026-01-06 22:51:24 +01:00
parent 567d3ebd75
commit 555e290d71
70 changed files with 3282 additions and 3428 deletions

12
.clang-format Normal file
View File

@@ -0,0 +1,12 @@
BasedOnStyle: Google
IndentWidth: 4
TabWidth: 4
UseTab: Never
BreakBeforeBraces: Allman
ColumnLimit: 160
IncludeBlocks: Preserve
IndentCaseLabels: false
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortBlocksOnASingleLine: Never

View File

@@ -1,4 +1,5 @@
// source: https://github.com/espressif/esp-iot-solution/blob/4730d91db70df7e6e0a3191d725ab1c5f98ff9ce/examples/usb/device/usb_webcam/bootloader_components/boot_hooks/boot_hooks.c // source:
// https://github.com/espressif/esp-iot-solution/blob/4730d91db70df7e6e0a3191d725ab1c5f98ff9ce/examples/usb/device/usb_webcam/bootloader_components/boot_hooks/boot_hooks.c
#ifdef CONFIG_GENERAL_INCLUDE_UVC_MODE #ifdef CONFIG_GENERAL_INCLUDE_UVC_MODE
#include "esp_log.h" #include "esp_log.h"
@@ -9,13 +10,10 @@
* with all its symbols. * with all its symbols.
*/ */
void bootloader_hooks_include(void) void bootloader_hooks_include(void) {}
{
}
void bootloader_before_init(void) void bootloader_before_init(void)
{ {
// Disable D+ pullup, to prevent the USB host from retrieving USB-Serial-JTAG's descriptor. // Disable D+ pullup, to prevent the USB host from retrieving USB-Serial-JTAG's descriptor.
SET_PERI_REG_MASK(USB_SERIAL_JTAG_CONF0_REG, USB_SERIAL_JTAG_PAD_PULL_OVERRIDE); SET_PERI_REG_MASK(USB_SERIAL_JTAG_CONF0_REG, USB_SERIAL_JTAG_PAD_PULL_OVERRIDE);
CLEAR_PERI_REG_MASK(USB_SERIAL_JTAG_CONF0_REG, USB_SERIAL_JTAG_DP_PULLUP); CLEAR_PERI_REG_MASK(USB_SERIAL_JTAG_CONF0_REG, USB_SERIAL_JTAG_DP_PULLUP);

View File

@@ -2,8 +2,7 @@
const char* CAMERA_MANAGER_TAG = "[CAMERA_MANAGER]"; const char* CAMERA_MANAGER_TAG = "[CAMERA_MANAGER]";
CameraManager::CameraManager(std::shared_ptr<ProjectConfig> projectConfig, QueueHandle_t eventQueue) CameraManager::CameraManager(std::shared_ptr<ProjectConfig> projectConfig, QueueHandle_t eventQueue) : projectConfig(projectConfig), eventQueue(eventQueue) {}
: projectConfig(projectConfig), eventQueue(eventQueue) {}
void CameraManager::setupCameraPinout() void CameraManager::setupCameraPinout()
{ {
@@ -76,7 +75,8 @@ void CameraManager::setupCameraPinout()
.ledc_channel = LEDC_CHANNEL_0, .ledc_channel = LEDC_CHANNEL_0,
.pixel_format = PIXFORMAT_JPEG, // YUV422,GRAYSCALE,RGB565,JPEG .pixel_format = PIXFORMAT_JPEG, // YUV422,GRAYSCALE,RGB565,JPEG
.frame_size = FRAMESIZE_240X240, // QQVGA-UXGA, For ESP32, do not use sizes above QVGA when not JPEG. The performance of the ESP32-S series has improved a lot, but JPEG mode always gives better frame rates. .frame_size = FRAMESIZE_240X240, // QQVGA-UXGA, For ESP32, do not use sizes above QVGA when not JPEG. The performance of the ESP32-S series has
// improved a lot, but JPEG mode always gives better frame rates.
.jpeg_quality = 8, // 0-63, for OV series camera sensors, lower number means higher quality // Below 6 stability problems .jpeg_quality = 8, // 0-63, for OV series camera sensors, lower number means higher quality // Below 6 stability problems
.fb_count = 2, // When jpeg mode is used, if fb_count more than one, the driver will work in continuous mode. .fb_count = 2, // When jpeg mode is used, if fb_count more than one, the driver will work in continuous mode.
@@ -92,8 +92,7 @@ void CameraManager::setupCameraSensor()
camera_sensor = esp_camera_sensor_get(); camera_sensor = esp_camera_sensor_get();
// fixes corrupted jpegs, https://github.com/espressif/esp32-camera/issues/203 // fixes corrupted jpegs, https://github.com/espressif/esp32-camera/issues/203
// documentation https://www.uctronics.com/download/cam_module/OV2640DS.pdf // documentation https://www.uctronics.com/download/cam_module/OV2640DS.pdf
camera_sensor->set_reg( camera_sensor->set_reg(camera_sensor, 0xff, 0xff,
camera_sensor, 0xff, 0xff,
0x00); // banksel, here we're directly writing to the registers. 0x00); // banksel, here we're directly writing to the registers.
// 0xFF==0x00 is the first bank, there's also 0xFF==0x01 // 0xFF==0x00 is the first bank, there's also 0xFF==0x01
camera_sensor->set_reg(camera_sensor, 0xd3, 0xff, 5); // clock camera_sensor->set_reg(camera_sensor, 0xd3, 0xff, 5); // clock
@@ -130,8 +129,7 @@ void CameraManager::setupCameraSensor()
camera_sensor->set_dcw(camera_sensor, 0); // 0 = disable , 1 = enable camera_sensor->set_dcw(camera_sensor, 0); // 0 = disable , 1 = enable
// gamma correction // gamma correction
camera_sensor->set_raw_gma( camera_sensor->set_raw_gma(camera_sensor,
camera_sensor,
1); // 0 = disable , 1 = enable (makes much lighter and noisy) 1); // 0 = disable , 1 = enable (makes much lighter and noisy)
camera_sensor->set_lenc(camera_sensor, 0); // 0 = disable , 1 = enable // 0 = camera_sensor->set_lenc(camera_sensor, 0); // 0 = disable , 1 = enable // 0 =
@@ -139,8 +137,7 @@ void CameraManager::setupCameraSensor()
camera_sensor->set_colorbar(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->set_special_effect(camera_sensor,
camera_sensor,
2); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 2); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint,
// 4 - Green Tint, 5 - Blue Tint, 6 - Sepia) // 4 - Green Tint, 5 - Blue Tint, 6 - Sepia)
@@ -157,17 +154,16 @@ bool CameraManager::setupCamera()
if (auto const hasCameraBeenInitialized = esp_camera_init(&config); 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));
constexpr auto event = SystemEvent{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
{ {
ESP_LOGE(CAMERA_MANAGER_TAG, "Camera initialization failed with error: %s \r\n", ESP_LOGE(CAMERA_MANAGER_TAG, "Camera initialization failed with error: %s \r\n", esp_err_to_name(hasCameraBeenInitialized));
esp_err_to_name(hasCameraBeenInitialized)); ESP_LOGE(CAMERA_MANAGER_TAG,
ESP_LOGE(CAMERA_MANAGER_TAG, "Camera most likely not seated properly in the socket. " "Camera most likely not seated properly in the socket. "
"Please " "Please "
"fix the " "fix the "
"camera and reboot the device.\r\n"); "camera and reboot the device.\r\n");
@@ -226,12 +222,8 @@ int CameraManager::setHFlip(const int direction)
return camera_sensor->set_hmirror(camera_sensor, direction); return camera_sensor->set_hmirror(camera_sensor, direction);
} }
int CameraManager::setVieWindow(int offsetX, int CameraManager::setVieWindow(int offsetX, int offsetY, int outputX, int outputY)
int offsetY,
int outputX,
int outputY)
{ {
// todo safariMonkey made a PoC, implement it here // todo safariMonkey made a PoC, implement it here
return 0; return 0;
} }

View File

@@ -2,17 +2,17 @@
#ifndef CAMERAMANAGER_HPP #ifndef CAMERAMANAGER_HPP
#define CAMERAMANAGER_HPP #define CAMERAMANAGER_HPP
#include "esp_log.h"
#include "esp_camera.h"
#include "driver/gpio.h" #include "driver/gpio.h"
#include "esp_camera.h"
#include "esp_log.h"
#include "esp_psram.h" #include "esp_psram.h"
#include "sdkconfig.h" #include "sdkconfig.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/queue.h" #include "freertos/queue.h"
#include <StateManager.hpp>
#include <ProjectConfig.hpp> #include <ProjectConfig.hpp>
#include <StateManager.hpp>
#define OV5640_XCLK_FREQ_HZ CONFIG_CAMERA_WIFI_XCLK_FREQ #define OV5640_XCLK_FREQ_HZ CONFIG_CAMERA_WIFI_XCLK_FREQ

View File

@@ -37,78 +37,55 @@ std::function<CommandResult()> CommandManager::createCommand(const CommandType t
case CommandType::PING: case CommandType::PING:
return {PingCommand}; return {PingCommand};
case CommandType::PAUSE: case CommandType::PAUSE:
return [json] return [json] { return PauseCommand(json); };
{ return PauseCommand(json); };
case CommandType::UPDATE_OTA_CREDENTIALS: case CommandType::UPDATE_OTA_CREDENTIALS:
return [this, json] return [this, json] { return updateOTACredentialsCommand(this->registry, json); };
{ return updateOTACredentialsCommand(this->registry, json); };
case CommandType::SET_WIFI: case CommandType::SET_WIFI:
return [this, json] return [this, json] { return setWiFiCommand(this->registry, json); };
{ return setWiFiCommand(this->registry, json); };
case CommandType::UPDATE_WIFI: case CommandType::UPDATE_WIFI:
return [this, json] return [this, json] { return updateWiFiCommand(this->registry, json); };
{ return updateWiFiCommand(this->registry, json); };
case CommandType::UPDATE_AP_WIFI: case CommandType::UPDATE_AP_WIFI:
return [this, json] return [this, json] { return updateAPWiFiCommand(this->registry, json); };
{ return updateAPWiFiCommand(this->registry, json); };
case CommandType::DELETE_NETWORK: case CommandType::DELETE_NETWORK:
return [this, json] return [this, json] { return deleteWiFiCommand(this->registry, json); };
{ return deleteWiFiCommand(this->registry, json); };
case CommandType::SET_MDNS: case CommandType::SET_MDNS:
return [this, json] return [this, json] { return setMDNSCommand(this->registry, json); };
{ return setMDNSCommand(this->registry, json); };
case CommandType::GET_MDNS_NAME: case CommandType::GET_MDNS_NAME:
return [this] return [this] { return getMDNSNameCommand(this->registry); };
{ return getMDNSNameCommand(this->registry); };
case CommandType::UPDATE_CAMERA: case CommandType::UPDATE_CAMERA:
return [this, json] return [this, json] { return updateCameraCommand(this->registry, json); };
{ return updateCameraCommand(this->registry, json); };
case CommandType::GET_CONFIG: case CommandType::GET_CONFIG:
return [this] return [this] { return getConfigCommand(this->registry); };
{ return getConfigCommand(this->registry); };
case CommandType::SAVE_CONFIG: case CommandType::SAVE_CONFIG:
return [this] return [this] { return saveConfigCommand(this->registry); };
{ return saveConfigCommand(this->registry); };
case CommandType::RESET_CONFIG: case CommandType::RESET_CONFIG:
return [this, json] return [this, json] { return resetConfigCommand(this->registry, json); };
{ return resetConfigCommand(this->registry, json); };
case CommandType::RESTART_DEVICE: case CommandType::RESTART_DEVICE:
return restartDeviceCommand; return restartDeviceCommand;
case CommandType::SCAN_NETWORKS: case CommandType::SCAN_NETWORKS:
return [this, json] return [this, json] { return scanNetworksCommand(this->registry, json); };
{ return scanNetworksCommand(this->registry, json); };
case CommandType::START_STREAMING: case CommandType::START_STREAMING:
return startStreamingCommand; return startStreamingCommand;
case CommandType::GET_WIFI_STATUS: case CommandType::GET_WIFI_STATUS:
return [this] return [this] { return getWiFiStatusCommand(this->registry); };
{ return getWiFiStatusCommand(this->registry); };
case CommandType::CONNECT_WIFI: case CommandType::CONNECT_WIFI:
return [this] return [this] { return connectWiFiCommand(this->registry); };
{ return connectWiFiCommand(this->registry); };
case CommandType::SWITCH_MODE: case CommandType::SWITCH_MODE:
return [this, json] return [this, json] { return switchModeCommand(this->registry, json); };
{ return switchModeCommand(this->registry, json); };
case CommandType::GET_DEVICE_MODE: case CommandType::GET_DEVICE_MODE:
return [this] return [this] { return getDeviceModeCommand(this->registry); };
{ return getDeviceModeCommand(this->registry); };
case CommandType::SET_LED_DUTY_CYCLE: case CommandType::SET_LED_DUTY_CYCLE:
return [this, json] return [this, json] { return updateLEDDutyCycleCommand(this->registry, json); };
{ return updateLEDDutyCycleCommand(this->registry, json); };
case CommandType::GET_LED_DUTY_CYCLE: case CommandType::GET_LED_DUTY_CYCLE:
return [this] return [this] { return getLEDDutyCycleCommand(this->registry); };
{ return getLEDDutyCycleCommand(this->registry); };
case CommandType::GET_SERIAL: case CommandType::GET_SERIAL:
return [this] return [this] { return getSerialNumberCommand(this->registry); };
{ return getSerialNumberCommand(this->registry); };
case CommandType::GET_LED_CURRENT: case CommandType::GET_LED_CURRENT:
return [this] return [this] { return getLEDCurrentCommand(this->registry); };
{ return getLEDCurrentCommand(this->registry); };
case CommandType::GET_BATTERY_STATUS: case CommandType::GET_BATTERY_STATUS:
return [this] return [this] { return getBatteryStatusCommand(this->registry); };
{ return getBatteryStatusCommand(this->registry); };
case CommandType::GET_WHO_AM_I: case CommandType::GET_WHO_AM_I:
return [this] return [this] { return getInfoCommand(this->registry); };
{ return getInfoCommand(this->registry); };
default: default:
return nullptr; return nullptr;
} }

View File

@@ -1,24 +1,24 @@
#ifndef COMMANDMANAGER_HPP #ifndef COMMANDMANAGER_HPP
#define COMMANDMANAGER_HPP #define COMMANDMANAGER_HPP
#include <ProjectConfig.hpp>
#include <CameraManager.hpp> #include <CameraManager.hpp>
#include <memory> #include <ProjectConfig.hpp>
#include <string>
#include <optional>
#include <unordered_map>
#include <functional> #include <functional>
#include <memory>
#include <nlohmann-json.hpp>
#include <optional>
#include <string>
#include <unordered_map>
#include "CommandResult.hpp" #include "CommandResult.hpp"
#include "CommandSchema.hpp" #include "CommandSchema.hpp"
#include "DependencyRegistry.hpp" #include "DependencyRegistry.hpp"
#include "commands/simple_commands.hpp"
#include "commands/camera_commands.hpp" #include "commands/camera_commands.hpp"
#include "commands/config_commands.hpp" #include "commands/config_commands.hpp"
#include "commands/mdns_commands.hpp"
#include "commands/wifi_commands.hpp"
#include "commands/device_commands.hpp" #include "commands/device_commands.hpp"
#include "commands/mdns_commands.hpp"
#include "commands/scan_commands.hpp" #include "commands/scan_commands.hpp"
#include <nlohmann-json.hpp> #include "commands/simple_commands.hpp"
#include "commands/wifi_commands.hpp"
enum class CommandType enum class CommandType
{ {

View File

@@ -2,10 +2,10 @@
#ifndef COMMAND_RESULT #ifndef COMMAND_RESULT
#define COMMAND_RESULT #define COMMAND_RESULT
#include <format>
#include <string>
#include <algorithm> #include <algorithm>
#include <format>
#include <nlohmann-json.hpp> #include <nlohmann-json.hpp>
#include <string>
using json = nlohmann::json; using json = nlohmann::json;
@@ -25,7 +25,10 @@ private:
public: public:
CommandResult(nlohmann::json data, const Status status) : data(data), status(status) {} CommandResult(nlohmann::json data, const Status status) : data(data), status(status) {}
bool isSuccess() const { return status == Status::SUCCESS; } bool isSuccess() const
{
return status == Status::SUCCESS;
}
static CommandResult getSuccessResult(nlohmann::json message) static CommandResult getSuccessResult(nlohmann::json message)
{ {
@@ -37,7 +40,10 @@ public:
return CommandResult(message, Status::FAILURE); return CommandResult(message, Status::FAILURE);
} }
nlohmann::json getData() const { return this->data; } nlohmann::json getData() const
{
return this->data;
}
}; };
void to_json(nlohmann::json& j, const CommandResult& result); void to_json(nlohmann::json& j, const CommandResult& result);
@@ -50,7 +56,10 @@ private:
public: public:
CommandManagerResponse(nlohmann::json data) : data(data) {} CommandManagerResponse(nlohmann::json data) : data(data) {}
nlohmann::json getData() const { return this->data; } nlohmann::json getData() const
{
return this->data;
}
}; };
void to_json(nlohmann::json& j, const CommandManagerResponse& result); void to_json(nlohmann::json& j, const CommandManagerResponse& result);

View File

@@ -53,7 +53,8 @@ void from_json(const nlohmann::json &j, UpdateAPWiFiPayload &payload)
void to_json(nlohmann::json& j, const UpdateCameraConfigPayload& payload) void to_json(nlohmann::json& j, const UpdateCameraConfigPayload& payload)
{ {
j = nlohmann::json{{"vflip", payload.vflip}, {"href", payload.href}, {"framesize", payload.framesize}, {"quality", payload.quality}, {"brightness", payload.brightness}}; j = nlohmann::json{
{"vflip", payload.vflip}, {"href", payload.href}, {"framesize", payload.framesize}, {"quality", payload.quality}, {"brightness", payload.brightness}};
} }
void from_json(const nlohmann::json& j, UpdateCameraConfigPayload& payload) void from_json(const nlohmann::json& j, UpdateCameraConfigPayload& payload)

View File

@@ -7,10 +7,8 @@ CommandResult updateCameraCommand(std::shared_ptr<DependencyRegistry> registry,
std::shared_ptr<ProjectConfig> projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config); std::shared_ptr<ProjectConfig> projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config);
auto oldConfig = projectConfig->getCameraConfig(); auto oldConfig = projectConfig->getCameraConfig();
projectConfig->setCameraConfig( projectConfig->setCameraConfig(
payload.vflip.has_value() ? payload.vflip.value() : oldConfig.vflip, payload.vflip.has_value() ? payload.vflip.value() : oldConfig.vflip, payload.framesize.has_value() ? payload.framesize.value() : oldConfig.framesize,
payload.framesize.has_value() ? payload.framesize.value() : oldConfig.framesize, payload.href.has_value() ? payload.href.value() : oldConfig.href, payload.quality.has_value() ? payload.quality.value() : oldConfig.quality,
payload.href.has_value() ? payload.href.value() : oldConfig.href,
payload.quality.has_value() ? payload.quality.value() : oldConfig.quality,
payload.brightness.has_value() ? payload.brightness.value() : oldConfig.brightness); payload.brightness.has_value() ? payload.brightness.value() : oldConfig.brightness);
return CommandResult::getSuccessResult("Config updated"); return CommandResult::getSuccessResult("Config updated");

View File

@@ -1,14 +1,14 @@
#ifndef CAMERA_COMMANDS_HPP #ifndef CAMERA_COMMANDS_HPP
#define CAMERA_COMMANDS_HPP #define CAMERA_COMMANDS_HPP
#include <CameraManager.hpp>
#include <ProjectConfig.hpp> #include <ProjectConfig.hpp>
#include <memory> #include <memory>
#include <string> #include <nlohmann-json.hpp>
#include <optional> #include <optional>
#include <string>
#include "CommandResult.hpp" #include "CommandResult.hpp"
#include "CommandSchema.hpp" #include "CommandSchema.hpp"
#include "DependencyRegistry.hpp" #include "DependencyRegistry.hpp"
#include <CameraManager.hpp>
#include <nlohmann-json.hpp>
CommandResult updateCameraCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json); CommandResult updateCameraCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);

View File

@@ -1,11 +1,11 @@
#include <ProjectConfig.hpp> #include <ProjectConfig.hpp>
#include <memory> #include <memory>
#include <string> #include <nlohmann-json.hpp>
#include <optional> #include <optional>
#include <string>
#include "CommandResult.hpp" #include "CommandResult.hpp"
#include "CommandSchema.hpp" #include "CommandSchema.hpp"
#include "DependencyRegistry.hpp" #include "DependencyRegistry.hpp"
#include <nlohmann-json.hpp>
CommandResult saveConfigCommand(std::shared_ptr<DependencyRegistry> registry); CommandResult saveConfigCommand(std::shared_ptr<DependencyRegistry> registry);
CommandResult getConfigCommand(std::shared_ptr<DependencyRegistry> registry); CommandResult getConfigCommand(std::shared_ptr<DependencyRegistry> registry);

View File

@@ -1,8 +1,8 @@
#include "device_commands.hpp" #include "device_commands.hpp"
#include <cstdio>
#include "LEDManager.hpp" #include "LEDManager.hpp"
#include "MonitoringManager.hpp" #include "MonitoringManager.hpp"
#include "esp_mac.h" #include "esp_mac.h"
#include <cstdio>
CommandResult setDeviceModeCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json) CommandResult setDeviceModeCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
@@ -25,7 +25,6 @@ CommandResult setDeviceModeCommand(std::shared_ptr<DependencyRegistry> registry,
CommandResult updateOTACredentialsCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json) CommandResult updateOTACredentialsCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
const auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config); const auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config);
const auto oldDeviceConfig = projectConfig->getDeviceConfig(); const auto oldDeviceConfig = projectConfig->getDeviceConfig();
auto OTALogin = oldDeviceConfig.OTALogin; auto OTALogin = oldDeviceConfig.OTALogin;
@@ -105,10 +104,7 @@ CommandResult startStreamingCommand()
// from *inside* the serial handler, we'd deadlock. // from *inside* the serial handler, we'd deadlock.
// we can just pass nullptr to the vtaskdelete(), // we can just pass nullptr to the vtaskdelete(),
// but then we won't get any response, so we schedule a timer instead // but then we won't get any response, so we schedule a timer instead
esp_timer_create_args_t args{ esp_timer_create_args_t args{.callback = activateStreaming, .arg = nullptr, .name = "activateStreaming"};
.callback = activateStreaming,
.arg = nullptr,
.name = "activateStreaming"};
esp_timer_handle_t activateStreamingTimer; esp_timer_handle_t activateStreamingTimer;
esp_timer_create(&args, &activateStreamingTimer); esp_timer_create(&args, &activateStreamingTimer);
@@ -119,7 +115,6 @@ CommandResult startStreamingCommand()
CommandResult switchModeCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json) CommandResult switchModeCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
if (!json.contains("mode") || !json["mode"].is_string()) if (!json.contains("mode") || !json["mode"].is_string())
{ {
return CommandResult::getErrorResult("Invalid payload - missing mode"); return CommandResult::getErrorResult("Invalid payload - missing mode");
@@ -188,13 +183,11 @@ CommandResult getSerialNumberCommand(std::shared_ptr<DependencyRegistry> /*regis
char serial_no_sep[13]; char serial_no_sep[13];
// Serial without separators (12 hex chars) // Serial without separators (12 hex chars)
std::snprintf(serial_no_sep, sizeof(serial_no_sep), "%02X%02X%02X%02X%02X%02X", std::snprintf(serial_no_sep, sizeof(serial_no_sep), "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
char mac_colon[18]; char mac_colon[18];
// MAC with colons // MAC with colons
std::snprintf(mac_colon, sizeof(mac_colon), "%02X:%02X:%02X:%02X:%02X:%02X", std::snprintf(mac_colon, sizeof(mac_colon), "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
const auto json = nlohmann::json{ const auto json = nlohmann::json{
{"serial", serial_no_sep}, {"serial", serial_no_sep},

View File

@@ -1,13 +1,13 @@
#include "CommandResult.hpp" #include "CommandResult.hpp"
#include "ProjectConfig.hpp"
#include "OpenIrisTasks.hpp"
#include "DependencyRegistry.hpp" #include "DependencyRegistry.hpp"
#include "OpenIrisTasks.hpp"
#include "ProjectConfig.hpp"
#include "esp_timer.h" #include "esp_timer.h"
#include "main_globals.hpp" #include "main_globals.hpp"
#include <format> #include <format>
#include <string>
#include <nlohmann-json.hpp> #include <nlohmann-json.hpp>
#include <string>
CommandResult updateOTACredentialsCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json); CommandResult updateOTACredentialsCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);

View File

@@ -1,11 +1,11 @@
#include <ProjectConfig.hpp> #include <ProjectConfig.hpp>
#include <memory> #include <memory>
#include <string> #include <nlohmann-json.hpp>
#include <optional> #include <optional>
#include <string>
#include "CommandResult.hpp" #include "CommandResult.hpp"
#include "CommandSchema.hpp" #include "CommandSchema.hpp"
#include "DependencyRegistry.hpp" #include "DependencyRegistry.hpp"
#include <nlohmann-json.hpp>
CommandResult setMDNSCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json); CommandResult setMDNSCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);
CommandResult getMDNSNameCommand(std::shared_ptr<DependencyRegistry> registry); CommandResult getMDNSNameCommand(std::shared_ptr<DependencyRegistry> registry);

View File

@@ -31,9 +31,7 @@ CommandResult scanNetworksCommand(std::shared_ptr<DependencyRegistry> registry,
networkItem["channel"] = network.channel; networkItem["channel"] = network.channel;
networkItem["rssi"] = network.rssi; networkItem["rssi"] = network.rssi;
char mac_str[18]; char mac_str[18];
sprintf(mac_str, "%02x:%02x:%02x:%02x:%02x:%02x", sprintf(mac_str, "%02x:%02x:%02x:%02x:%02x:%02x", network.mac[0], network.mac[1], network.mac[2], network.mac[3], network.mac[4], network.mac[5]);
network.mac[0], network.mac[1], network.mac[2],
network.mac[3], network.mac[4], network.mac[5]);
networkItem["mac_address"] = mac_str; networkItem["mac_address"] = mac_str;
networkItem["auth_mode"] = network.auth_mode; networkItem["auth_mode"] = network.auth_mode;
networksJson.push_back(networkItem); networksJson.push_back(networkItem);

View File

@@ -1,12 +1,12 @@
#ifndef SCAN_COMMANDS_HPP #ifndef SCAN_COMMANDS_HPP
#define SCAN_COMMANDS_HPP #define SCAN_COMMANDS_HPP
#include <nlohmann-json.hpp>
#include <string>
#include <wifiManager.hpp>
#include "CommandResult.hpp" #include "CommandResult.hpp"
#include "DependencyRegistry.hpp" #include "DependencyRegistry.hpp"
#include "esp_log.h" #include "esp_log.h"
#include <wifiManager.hpp>
#include <string>
#include <nlohmann-json.hpp>
CommandResult scanNetworksCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json); CommandResult scanNetworksCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);

View File

@@ -1,11 +1,11 @@
#ifndef SIMPLE_COMMANDS #ifndef SIMPLE_COMMANDS
#define SIMPLE_COMMANDS #define SIMPLE_COMMANDS
#include <nlohmann-json.hpp>
#include <string> #include <string>
#include "CommandResult.hpp" #include "CommandResult.hpp"
#include "main_globals.hpp"
#include "esp_log.h" #include "esp_log.h"
#include <nlohmann-json.hpp> #include "main_globals.hpp"
CommandResult PingCommand(); CommandResult PingCommand();
CommandResult PauseCommand(const nlohmann::json& json); CommandResult PauseCommand(const nlohmann::json& json);

View File

@@ -20,12 +20,7 @@ CommandResult setWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const
} }
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(payload.name, payload.ssid, payload.password, payload.channel, payload.power);
payload.name,
payload.ssid,
payload.password,
payload.channel,
payload.power);
return CommandResult::getSuccessResult("Config updated"); return CommandResult::getSuccessResult("Config updated");
} }
@@ -60,15 +55,10 @@ CommandResult updateWiFiCommand(std::shared_ptr<DependencyRegistry> registry, co
auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config); auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config);
auto storedNetworks = projectConfig->getWifiConfigs(); auto storedNetworks = projectConfig->getWifiConfigs();
if (const auto networkToUpdate = std::ranges::find_if( if (const auto networkToUpdate = std::ranges::find_if(storedNetworks, [&](auto& network) { return network.name == payload.name; });
storedNetworks,
[&](auto &network)
{ return network.name == payload.name; });
networkToUpdate != storedNetworks.end()) networkToUpdate != storedNetworks.end())
{ {
projectConfig->setWifiConfig( projectConfig->setWifiConfig(payload.name, payload.ssid.has_value() ? payload.ssid.value() : networkToUpdate->ssid,
payload.name,
payload.ssid.has_value() ? payload.ssid.value() : networkToUpdate->ssid,
payload.password.has_value() ? payload.password.value() : networkToUpdate->password, payload.password.has_value() ? payload.password.value() : networkToUpdate->password,
payload.channel.has_value() ? payload.channel.value() : networkToUpdate->channel, payload.channel.has_value() ? payload.channel.value() : networkToUpdate->channel,
payload.power.has_value() ? payload.power.value() : networkToUpdate->power); payload.power.has_value() ? payload.power.value() : networkToUpdate->power);
@@ -90,8 +80,7 @@ CommandResult updateAPWiFiCommand(std::shared_ptr<DependencyRegistry> registry,
auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config); auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config);
const auto previousAPConfig = projectConfig->getAPWifiConfig(); const auto previousAPConfig = projectConfig->getAPWifiConfig();
projectConfig->setAPWifiConfig( projectConfig->setAPWifiConfig(payload.ssid.has_value() ? payload.ssid.value() : previousAPConfig.ssid,
payload.ssid.has_value() ? payload.ssid.value() : previousAPConfig.ssid,
payload.password.has_value() ? payload.password.value() : previousAPConfig.password, payload.password.has_value() ? payload.password.value() : previousAPConfig.password,
payload.channel.has_value() ? payload.channel.value() : previousAPConfig.channel); payload.channel.has_value() ? payload.channel.value() : previousAPConfig.channel);

View File

@@ -1,13 +1,13 @@
#include <ProjectConfig.hpp> #include <ProjectConfig.hpp>
#include <wifiManager.hpp>
#include <StateManager.hpp> #include <StateManager.hpp>
#include <memory> #include <memory>
#include <string> #include <nlohmann-json.hpp>
#include <optional> #include <optional>
#include <string>
#include <wifiManager.hpp>
#include "CommandResult.hpp" #include "CommandResult.hpp"
#include "CommandSchema.hpp" #include "CommandSchema.hpp"
#include "DependencyRegistry.hpp" #include "DependencyRegistry.hpp"
#include <nlohmann-json.hpp>
CommandResult setWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json); CommandResult setWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);

View File

@@ -1,12 +1,12 @@
#pragma once #pragma once
#ifndef HELPERS_HPP #ifndef HELPERS_HPP
#define HELPERS_HPP #define HELPERS_HPP
#include "esp_timer.h"
#include <string>
#include <sstream>
#include <vector>
#include <iostream> #include <iostream>
#include <memory> #include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "esp_timer.h"
namespace Helpers namespace Helpers
{ {
@@ -35,6 +35,6 @@ namespace Helpers
} }
int64_t getTimeInMillis(); int64_t getTimeInMillis();
} } // namespace Helpers
#endif // HELPERS_HPP #endif // HELPERS_HPP

View File

@@ -35,5 +35,11 @@ void activateStreaming(void *arg)
// USB handover state // USB handover state
static bool s_usbHandoverDone = false; static bool s_usbHandoverDone = false;
bool getUsbHandoverDone() { return s_usbHandoverDone; } bool getUsbHandoverDone()
void setUsbHandoverDone(bool done) { s_usbHandoverDone = done; } {
return s_usbHandoverDone;
}
void setUsbHandoverDone(bool done)
{
s_usbHandoverDone = done;
}

View File

@@ -21,8 +21,8 @@ ledStateMap_t LEDManager::ledStateMap = {
{LEDStates_e::WiFiStateError, {true, true, {{{LED_ON, 200}, {LED_OFF, 100}, {LED_ON, 500}, {LED_OFF, 300}}}}}, {LEDStates_e::WiFiStateError, {true, true, {{{LED_ON, 200}, {LED_OFF, 100}, {LED_ON, 500}, {LED_OFF, 300}}}}},
}; };
LEDManager::LEDManager(gpio_num_t pin, gpio_num_t illumninator_led_pin, LEDManager::LEDManager(gpio_num_t pin, gpio_num_t illumninator_led_pin, QueueHandle_t ledStateQueue, std::shared_ptr<ProjectConfig> deviceConfig)
QueueHandle_t ledStateQueue, std::shared_ptr<ProjectConfig> deviceConfig) : blink_led_pin(pin), : blink_led_pin(pin),
illumninator_led_pin(illumninator_led_pin), illumninator_led_pin(illumninator_led_pin),
ledStateQueue(ledStateQueue), ledStateQueue(ledStateQueue),
currentState(LEDStates_e::LedStateNone), currentState(LEDStates_e::LedStateNone),
@@ -52,16 +52,11 @@ void LEDManager::setup()
ESP_LOGI(LED_MANAGER_TAG, "Setting dutyCycle to: %lu ", dutyCycle); ESP_LOGI(LED_MANAGER_TAG, "Setting dutyCycle to: %lu ", dutyCycle);
ledc_timer_config_t ledc_timer = { ledc_timer_config_t ledc_timer = {
.speed_mode = LEDC_LOW_SPEED_MODE, .speed_mode = LEDC_LOW_SPEED_MODE, .duty_resolution = resolution, .timer_num = LEDC_TIMER_0, .freq_hz = freq, .clk_cfg = LEDC_AUTO_CLK};
.duty_resolution = resolution,
.timer_num = LEDC_TIMER_0,
.freq_hz = freq,
.clk_cfg = LEDC_AUTO_CLK};
ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer)); ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
ledc_channel_config_t ledc_channel = { ledc_channel_config_t ledc_channel = {.gpio_num = this->illumninator_led_pin,
.gpio_num = this->illumninator_led_pin,
.speed_mode = LEDC_LOW_SPEED_MODE, .speed_mode = LEDC_LOW_SPEED_MODE,
.channel = LEDC_CHANNEL_0, .channel = LEDC_CHANNEL_0,
.intr_type = LEDC_INTR_DISABLE, .intr_type = LEDC_INTR_DISABLE,

View File

@@ -11,13 +11,13 @@
#endif #endif
#include <esp_log.h> #include <esp_log.h>
#include <ProjectConfig.hpp>
#include <StateManager.hpp>
#include <algorithm> #include <algorithm>
#include <cstdint> #include <cstdint>
#include <helpers.hpp>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <StateManager.hpp>
#include <ProjectConfig.hpp>
#include <helpers.hpp>
// it kinda looks like different boards have these states swapped // it kinda looks like different boards have these states swapped
#define LED_OFF 1 #define LED_OFF 1
@@ -36,8 +36,7 @@ struct LEDStage
std::vector<BlinkPatterns_t> patterns; std::vector<BlinkPatterns_t> patterns;
}; };
typedef std::unordered_map<LEDStates_e, LEDStage> typedef std::unordered_map<LEDStates_e, LEDStage> ledStateMap_t;
ledStateMap_t;
class LEDManager class LEDManager
{ {
@@ -46,11 +45,17 @@ public:
void setup(); void setup();
void handleLED(); void handleLED();
size_t getTimeToDelayFor() const { return timeToDelayFor; } size_t getTimeToDelayFor() const
{
return timeToDelayFor;
}
// Apply new external LED PWM duty cycle immediately (0-100) // Apply new external LED PWM duty cycle immediately (0-100)
void setExternalLEDDutyCycle(uint8_t dutyPercent); void setExternalLEDDutyCycle(uint8_t dutyPercent);
uint8_t getExternalLEDDutyCycle() const { return deviceConfig ? deviceConfig->getDeviceConfig().led_external_pwm_duty_cycle : 0; } uint8_t getExternalLEDDutyCycle() const
{
return deviceConfig ? deviceConfig->getDeviceConfig().led_external_pwm_duty_cycle : 0;
}
private: private:
void toggleLED(bool state) const; void toggleLED(bool state) const;

View File

@@ -1,9 +1,9 @@
#pragma once #pragma once
#ifndef MDNSMANAGER_HPP #ifndef MDNSMANAGER_HPP
#define MDNSMANAGER_HPP #define MDNSMANAGER_HPP
#include <string>
#include <ProjectConfig.hpp> #include <ProjectConfig.hpp>
#include <StateManager.hpp> #include <StateManager.hpp>
#include <string>
#include "esp_log.h" #include "esp_log.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/queue.h" #include "freertos/queue.h"

View File

@@ -187,8 +187,7 @@ bool AdcSampler::configure_channel(int gpio, adc_atten_t atten, adc_bitwidth_t b
esp_err_t err = adc_oneshot_config_channel(shared_unit_, channel_, &chan_cfg); esp_err_t err = adc_oneshot_config_channel(shared_unit_, channel_, &chan_cfg);
if (err != ESP_OK) if (err != ESP_OK)
{ {
ESP_LOGE(TAG, "adc_oneshot_config_channel failed (GPIO %d, CH %d): %s", ESP_LOGE(TAG, "adc_oneshot_config_channel failed (GPIO %d, CH %d): %s", gpio, static_cast<int>(channel_), esp_err_to_name(err));
gpio, static_cast<int>(channel_), esp_err_to_name(err));
return false; return false;
} }
return true; return true;

View File

@@ -21,10 +21,10 @@
#include "sdkconfig.h" #include "sdkconfig.h"
#if defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32) #if defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32)
#include "esp_adc/adc_oneshot.h" #include <vector>
#include "esp_adc/adc_cali.h" #include "esp_adc/adc_cali.h"
#include "esp_adc/adc_cali_scheme.h" #include "esp_adc/adc_cali_scheme.h"
#include <vector> #include "esp_adc/adc_oneshot.h"
/** /**
* @class AdcSampler * @class AdcSampler
@@ -53,10 +53,7 @@ public:
* @param window_size Moving average window size (>=1) * @param window_size Moving average window size (>=1)
* @return true on success, false on failure * @return true on success, false on failure
*/ */
bool init(int gpio, bool init(int gpio, adc_atten_t atten = ADC_ATTEN_DB_12, adc_bitwidth_t bitwidth = ADC_BITWIDTH_DEFAULT, size_t window_size = 1);
adc_atten_t atten = ADC_ATTEN_DB_12,
adc_bitwidth_t bitwidth = ADC_BITWIDTH_DEFAULT,
size_t window_size = 1);
/** /**
* @brief Perform one ADC conversion and update filtered value * @brief Perform one ADC conversion and update filtered value
@@ -68,13 +65,19 @@ public:
* @brief Get the filtered ADC reading in millivolts * @brief Get the filtered ADC reading in millivolts
* @return Filtered voltage in mV * @return Filtered voltage in mV
*/ */
int getFilteredMilliVolts() const { return filtered_mv_; } int getFilteredMilliVolts() const
{
return filtered_mv_;
}
/** /**
* @brief Check if ADC sampling is supported on current platform * @brief Check if ADC sampling is supported on current platform
* @return true if supported * @return true if supported
*/ */
static constexpr bool isSupported() { return true; } static constexpr bool isSupported()
{
return true;
}
private: private:
// Hardware initialization helpers // Hardware initialization helpers
@@ -111,9 +114,21 @@ private:
class AdcSampler class AdcSampler
{ {
public: public:
bool init(int /*gpio*/, int /*atten*/ = 0, int /*bitwidth*/ = 0, size_t /*window_size*/ = 1) { return false; } bool init(int /*gpio*/, int /*atten*/ = 0, int /*bitwidth*/ = 0, size_t /*window_size*/ = 1)
bool sampleOnce() { return false; } {
int getFilteredMilliVolts() const { return 0; } return false;
static constexpr bool isSupported() { return false; } }
bool sampleOnce()
{
return false;
}
int getFilteredMilliVolts() const
{
return 0;
}
static constexpr bool isSupported()
{
return false;
}
}; };
#endif #endif

View File

@@ -20,7 +20,6 @@
#include "AdcSampler.hpp" #include "AdcSampler.hpp"
#include "sdkconfig.h" #include "sdkconfig.h"
/** /**
* @struct BatteryStatus * @struct BatteryStatus
* @brief Battery status information * @brief Battery status information

View File

@@ -17,8 +17,8 @@
*/ */
#include <cstdint> #include <cstdint>
#include "sdkconfig.h"
#include "AdcSampler.hpp" #include "AdcSampler.hpp"
#include "sdkconfig.h"
/** /**
* @class CurrentMonitor * @class CurrentMonitor

View File

@@ -18,11 +18,8 @@ void MonitoringManager::setup()
if (CurrentMonitor::isEnabled()) if (CurrentMonitor::isEnabled())
{ {
cm_.setup(); cm_.setup();
ESP_LOGI(TAG, "LED current monitoring enabled. Interval=%dms, Samples=%d, Gain=%d, R=%dmΩ", ESP_LOGI(TAG, "LED current monitoring enabled. Interval=%dms, Samples=%d, Gain=%d, R=%dmΩ", CONFIG_MONITORING_LED_INTERVAL_MS,
CONFIG_MONITORING_LED_INTERVAL_MS, CONFIG_MONITORING_LED_SAMPLES, CONFIG_MONITORING_LED_GAIN, CONFIG_MONITORING_LED_SHUNT_MILLIOHM);
CONFIG_MONITORING_LED_SAMPLES,
CONFIG_MONITORING_LED_GAIN,
CONFIG_MONITORING_LED_SHUNT_MILLIOHM);
} }
else else
{ {
@@ -36,11 +33,8 @@ void MonitoringManager::setup()
if (BatteryMonitor::isEnabled()) if (BatteryMonitor::isEnabled())
{ {
bm_.setup(); bm_.setup();
ESP_LOGI(TAG, "Battery monitoring enabled. Interval=%dms, Samples=%d, R-Top=%dΩ, R-Bottom=%dΩ", ESP_LOGI(TAG, "Battery monitoring enabled. Interval=%dms, Samples=%d, R-Top=%dΩ, R-Bottom=%dΩ", CONFIG_MONITORING_BATTERY_INTERVAL_MS,
CONFIG_MONITORING_BATTERY_INTERVAL_MS, CONFIG_MONITORING_BATTERY_SAMPLES, CONFIG_MONITORING_BATTERY_DIVIDER_R_TOP_OHM, CONFIG_MONITORING_BATTERY_DIVIDER_R_BOTTOM_OHM);
CONFIG_MONITORING_BATTERY_SAMPLES,
CONFIG_MONITORING_BATTERY_DIVIDER_R_TOP_OHM,
CONFIG_MONITORING_BATTERY_DIVIDER_R_BOTTOM_OHM);
} }
else else
{ {

View File

@@ -1,16 +1,14 @@
#include "OpenIrisTasks.hpp" #include "OpenIrisTasks.hpp"
void restart_the_board(void *arg) { void restart_the_board(void* arg)
{
esp_restart(); esp_restart();
} }
void OpenIrisTasks::ScheduleRestart(const int milliseconds) void OpenIrisTasks::ScheduleRestart(const int milliseconds)
{ {
esp_timer_handle_t timerHandle; esp_timer_handle_t timerHandle;
constexpr esp_timer_create_args_t args = { constexpr esp_timer_create_args_t args = {.callback = &restart_the_board, .arg = nullptr, .name = "restartBoard"};
.callback = &restart_the_board,
.arg = nullptr,
.name = "restartBoard"};
if (const auto result = esp_timer_create(&args, &timerHandle); result == ESP_OK) if (const auto result = esp_timer_create(&args, &timerHandle); result == ESP_OK)
{ {

View File

@@ -2,10 +2,10 @@
#ifndef OPENIRISTASKS_HPP #ifndef OPENIRISTASKS_HPP
#define OPENIRISTASKS_HPP #define OPENIRISTASKS_HPP
#include "helpers.hpp" #include "esp_system.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
#include "esp_system.h" #include "helpers.hpp"
namespace OpenIrisTasks namespace OpenIrisTasks
{ {

View File

@@ -5,13 +5,13 @@
#ifndef PREFERENCES_HPP #ifndef PREFERENCES_HPP
#define PREFERENCES_HPP #define PREFERENCES_HPP
#include <cstdint>
#include <string>
#include <cstring>
#include <cmath> #include <cmath>
#include <cstdint>
#include <cstring>
#include <string>
#include "esp_log.h" #include "esp_log.h"
#include "nvs_flash.h"
#include "nvs.h" #include "nvs.h"
#include "nvs_flash.h"
typedef enum typedef enum
{ {

View File

@@ -2,13 +2,13 @@
#ifndef PROJECT_CONFIG_MODELS_HPP #ifndef PROJECT_CONFIG_MODELS_HPP
#define PROJECT_CONFIG_MODELS_HPP #define PROJECT_CONFIG_MODELS_HPP
#include <Preferences.hpp>
#include <helpers.hpp>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include <helpers.hpp>
#include "sdkconfig.h"
#include <Preferences.hpp>
#include "esp_log.h" #include "esp_log.h"
#include "sdkconfig.h"
struct BaseConfigModel struct BaseConfigModel
{ {
@@ -120,9 +120,7 @@ struct MDNSConfig_t : BaseConfigModel
std::string toRepresentation() std::string toRepresentation()
{ {
return Helpers::format_string( return Helpers::format_string("\"mdns_config\": {\"hostname\": \"%s\"}", this->hostname.c_str());
"\"mdns_config\": {\"hostname\": \"%s\"}",
this->hostname.c_str());
}; };
}; };
@@ -159,8 +157,7 @@ struct CameraConfig_t : BaseConfigModel
return Helpers::format_string( return Helpers::format_string(
"\"camera_config\": {\"vflip\": %d,\"framesize\": %d,\"href\": " "\"camera_config\": {\"vflip\": %d,\"framesize\": %d,\"href\": "
"%d,\"quality\": %d,\"brightness\": %d}", "%d,\"quality\": %d,\"brightness\": %d}",
this->vflip, this->framesize, this->href, this->quality, this->vflip, this->framesize, this->href, this->quality, this->brightness);
this->brightness);
}; };
}; };
@@ -173,21 +170,10 @@ struct WiFiConfig_t : BaseConfigModel
// default constructor used for loading // default constructor used for loading
WiFiConfig_t(Preferences* pref) : BaseConfigModel(pref) {} WiFiConfig_t(Preferences* pref) : BaseConfigModel(pref) {}
WiFiConfig_t( WiFiConfig_t(Preferences* pref, const uint8_t index, std::string name, std::string ssid, std::string password, const uint8_t channel, const uint8_t power)
Preferences *pref, : BaseConfigModel(pref), index(index), name(std::move(name)), ssid(std::move(ssid)), password(std::move(password)), channel(channel), power(power)
const uint8_t index, {
std::string name, }
std::string ssid,
std::string password,
const uint8_t channel,
const uint8_t power)
: BaseConfigModel(pref),
index(index),
name(std::move(name)),
ssid(std::move(ssid)),
password(std::move(password)),
channel(channel),
power(power) {}
uint8_t index; uint8_t index;
std::string name; std::string name;
@@ -208,8 +194,7 @@ struct WiFiConfig_t : BaseConfigModel
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());
ESP_LOGI("WiFiConfig", "Loaded network %d: name=%s, ssid=%s, channel=%d", ESP_LOGI("WiFiConfig", "Loaded network %d: name=%s, ssid=%s, channel=%d", index, this->name.c_str(), this->ssid.c_str(), this->channel);
index, this->name.c_str(), this->ssid.c_str(), this->channel);
}; };
void save() const void save() const
@@ -223,16 +208,13 @@ struct WiFiConfig_t : BaseConfigModel
this->pref->putUInt(("channel" + iter_str).c_str(), this->channel); this->pref->putUInt(("channel" + iter_str).c_str(), this->channel);
this->pref->putUInt(("power" + iter_str).c_str(), this->power); this->pref->putUInt(("power" + iter_str).c_str(), this->power);
ESP_LOGI("WiFiConfig", "Saved network %d: name=%s, ssid=%s, channel=%d", ESP_LOGI("WiFiConfig", "Saved network %d: name=%s, ssid=%s, channel=%d", this->index, this->name.c_str(), this->ssid.c_str(), this->channel);
this->index, this->name.c_str(), this->ssid.c_str(), this->channel);
}; };
std::string toRepresentation() std::string toRepresentation()
{ {
return Helpers::format_string( return Helpers::format_string("{\"name\": \"%s\", \"ssid\": \"%s\", \"password\": \"%s\", \"channel\": %u, \"power\": %u}", this->name.c_str(),
"{\"name\": \"%s\", \"ssid\": \"%s\", \"password\": \"%s\", \"channel\": %u, \"power\": %u}", this->ssid.c_str(), this->password.c_str(), this->channel, this->power);
this->name.c_str(), this->ssid.c_str(), this->password.c_str(),
this->channel, this->power);
}; };
}; };
@@ -299,20 +281,17 @@ public:
MDNSConfig_t mdns; MDNSConfig_t mdns;
WiFiTxPower_t txpower; WiFiTxPower_t txpower;
TrackerConfig_t( TrackerConfig_t(DeviceConfig_t device, DeviceMode_t device_mode, CameraConfig_t camera, std::vector<WiFiConfig_t> networks, AP_WiFiConfig_t ap_network,
DeviceConfig_t device, MDNSConfig_t mdns, WiFiTxPower_t txpower)
DeviceMode_t device_mode, : device(std::move(device)),
CameraConfig_t camera,
std::vector<WiFiConfig_t> networks,
AP_WiFiConfig_t ap_network,
MDNSConfig_t mdns,
WiFiTxPower_t txpower) : device(std::move(device)),
device_mode(std::move(device_mode)), device_mode(std::move(device_mode)),
camera(std::move(camera)), camera(std::move(camera)),
networks(std::move(networks)), networks(std::move(networks)),
ap_network(std::move(ap_network)), ap_network(std::move(ap_network)),
mdns(std::move(mdns)), mdns(std::move(mdns)),
txpower(std::move(txpower)) {} txpower(std::move(txpower))
{
}
std::string toRepresentation() std::string toRepresentation()
{ {
@@ -332,14 +311,9 @@ public:
WifiConfigRepresentation += Helpers::format_string("%s", this->networks[networks.size() - 1].toRepresentation().c_str()); WifiConfigRepresentation += Helpers::format_string("%s", this->networks[networks.size() - 1].toRepresentation().c_str());
} }
return Helpers::format_string( return Helpers::format_string("{%s, %s, %s, \"networks\": [%s], %s, %s}", this->device.toRepresentation().c_str(),
"{%s, %s, %s, \"networks\": [%s], %s, %s}", this->mdns.toRepresentation().c_str(), this->camera.toRepresentation().c_str(), WifiConfigRepresentation.c_str(),
this->device.toRepresentation().c_str(), this->ap_network.toRepresentation().c_str(), this->txpower.toRepresentation().c_str());
this->mdns.toRepresentation().c_str(),
this->camera.toRepresentation().c_str(),
WifiConfigRepresentation.c_str(),
this->ap_network.toRepresentation().c_str(),
this->txpower.toRepresentation().c_str());
} }
}; };

View File

@@ -12,15 +12,13 @@ void saveNetworkCount(Preferences *pref, const int count)
pref->putInt("networkcount", count); pref->putInt("networkcount", count);
} }
ProjectConfig::ProjectConfig(Preferences *pref) : pref(pref), ProjectConfig::ProjectConfig(Preferences* pref)
: pref(pref),
_already_loaded(false), _already_loaded(false),
config(DeviceConfig_t(pref), config(DeviceConfig_t(pref), DeviceMode_t(pref), CameraConfig_t(pref), std::vector<WiFiConfig_t>{}, AP_WiFiConfig_t(pref), MDNSConfig_t(pref),
DeviceMode_t(pref), WiFiTxPower_t(pref))
CameraConfig_t(pref), {
std::vector<WiFiConfig_t>{}, }
AP_WiFiConfig_t(pref),
MDNSConfig_t(pref),
WiFiTxPower_t(pref)) {}
ProjectConfig::~ProjectConfig() = default; ProjectConfig::~ProjectConfig() = default;
@@ -93,9 +91,7 @@ bool ProjectConfig::reset()
//! DeviceConfig //! DeviceConfig
//* //*
//********************************************************************************************************************** //**********************************************************************************************************************
void ProjectConfig::setOTAConfig(const std::string &OTALogin, void ProjectConfig::setOTAConfig(const std::string& OTALogin, const std::string& OTAPassword, const int OTAPort)
const std::string &OTAPassword,
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);
@@ -118,11 +114,7 @@ void ProjectConfig::setMDNSConfig(const std::string &hostname)
this->config.mdns.save(); this->config.mdns.save();
} }
void ProjectConfig::setCameraConfig(const uint8_t vflip, void ProjectConfig::setCameraConfig(const uint8_t vflip, const uint8_t framesize, const uint8_t href, const uint8_t quality, const uint8_t brightness)
const uint8_t framesize,
const uint8_t href,
const uint8_t quality,
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;
@@ -135,23 +127,15 @@ void ProjectConfig::setCameraConfig(const uint8_t vflip,
ESP_LOGD(CONFIGURATION_TAG, "Updating Camera config"); ESP_LOGD(CONFIGURATION_TAG, "Updating Camera config");
} }
void ProjectConfig::setWifiConfig(const std::string &networkName, void ProjectConfig::setWifiConfig(const std::string& networkName, const std::string& ssid, const std::string& password, uint8_t channel, uint8_t power)
const std::string &ssid,
const std::string &password,
uint8_t channel,
uint8_t power)
{ {
const auto size = this->config.networks.size(); const auto size = this->config.networks.size();
const auto it = std::ranges::find_if(this->config.networks, const auto it = std::ranges::find_if(this->config.networks, [&](const WiFiConfig_t& network) { return network.name == networkName; });
[&](const WiFiConfig_t &network)
{ return network.name == networkName; });
if (it != this->config.networks.end()) if (it != this->config.networks.end())
{ {
ESP_LOGI(CONFIGURATION_TAG, "Found network %s, updating it ...", it->name.c_str());
ESP_LOGI(CONFIGURATION_TAG, "Found network %s, updating it ...",
it->name.c_str());
it->name = networkName; it->name = networkName;
it->ssid = ssid; it->ssid = ssid;
@@ -166,8 +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, static_cast<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);
// Save the new network immediately // Save the new network immediately
this->config.networks.back().save(); this->config.networks.back().save();
saveNetworkCount(this->pref, 1); saveNetworkCount(this->pref, 1);
@@ -182,8 +165,7 @@ void ProjectConfig::setWifiConfig(const std::string &networkName,
// space we're using emplace_back as push_back will create a copy of it, // space we're using emplace_back as push_back will create a copy of it,
// we want to avoid that // we want to avoid that
uint8_t last_index = getNetworkCount(this->pref); uint8_t last_index = getNetworkCount(this->pref);
this->config.networks.emplace_back(this->pref, last_index, networkName, ssid, password, channel, this->config.networks.emplace_back(this->pref, last_index, networkName, ssid, password, channel, power);
power);
// Save the new network immediately // Save the new network immediately
this->config.networks.back().save(); this->config.networks.back().save();
saveNetworkCount(this->pref, static_cast<int>(this->config.networks.size())); saveNetworkCount(this->pref, static_cast<int>(this->config.networks.size()));
@@ -201,9 +183,7 @@ void ProjectConfig::deleteWifiConfig(const std::string &networkName)
ESP_LOGI(CONFIGURATION_TAG, "No networks, nothing to delete"); ESP_LOGI(CONFIGURATION_TAG, "No networks, nothing to delete");
} }
const auto it = std::ranges::find_if(this->config.networks, const auto it = std::ranges::find_if(this->config.networks, [&](const WiFiConfig_t& network) { return network.name == networkName; });
[&](const WiFiConfig_t &network)
{ return network.name == networkName; });
if (it != this->config.networks.end()) if (it != this->config.networks.end())
{ {
@@ -220,9 +200,7 @@ void ProjectConfig::setWiFiTxPower(uint8_t power)
ESP_LOGD(CONFIGURATION_TAG, "Updating wifi tx power"); ESP_LOGD(CONFIGURATION_TAG, "Updating wifi tx power");
} }
void ProjectConfig::setAPWifiConfig(const std::string &ssid, void ProjectConfig::setAPWifiConfig(const std::string& ssid, const std::string& password, const uint8_t channel)
const std::string &password,
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,13 +1,13 @@
#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 <algorithm>
#include <vector>
#include <string>
#include <helpers.hpp>
#include "Models.hpp"
#include <Preferences.hpp> #include <Preferences.hpp>
#include <algorithm>
#include <helpers.hpp>
#include <string>
#include <vector>
#include "Models.hpp"
#include "esp_log.h"
int getNetworkCount(Preferences* pref); int getNetworkCount(Preferences* pref);
@@ -33,27 +33,15 @@ public:
WiFiTxPower_t& getWiFiTxPowerConfig(); WiFiTxPower_t& getWiFiTxPowerConfig();
TrackerConfig_t& getTrackerConfig(); TrackerConfig_t& getTrackerConfig();
void setOTAConfig(const std::string &OTALogin, void setOTAConfig(const std::string& OTALogin, const std::string& OTAPassword, int OTAPort);
const std::string &OTAPassword,
int OTAPort);
void setLEDDUtyCycleConfig(int led_external_pwm_duty_cycle); void setLEDDUtyCycleConfig(int led_external_pwm_duty_cycle);
void setMDNSConfig(const std::string& hostname); void setMDNSConfig(const std::string& hostname);
void setCameraConfig(uint8_t vflip, void setCameraConfig(uint8_t vflip, uint8_t framesize, uint8_t href, uint8_t quality, uint8_t brightness);
uint8_t framesize, void setWifiConfig(const std::string& networkName, const std::string& ssid, const std::string& password, uint8_t channel, uint8_t power);
uint8_t href,
uint8_t quality,
uint8_t brightness);
void setWifiConfig(const std::string &networkName,
const std::string &ssid,
const std::string &password,
uint8_t channel,
uint8_t power);
void deleteWifiConfig(const std::string& networkName); void deleteWifiConfig(const std::string& networkName);
void setAPWifiConfig(const std::string &ssid, void setAPWifiConfig(const std::string& ssid, const std::string& password, uint8_t channel);
const std::string &password,
uint8_t channel);
void setWiFiTxPower(uint8_t power); void setWiFiTxPower(uint8_t power);
void setDeviceMode(StreamingMode deviceMode); void setDeviceMode(StreamingMode deviceMode);
StreamingMode getDeviceMode(); StreamingMode getDeviceMode();

View File

@@ -102,10 +102,7 @@ void RestAPI::handle_request(struct mg_connection *connection, int event, void *
.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),
}; };
this->handle_endpoint_command(context, this->handle_endpoint_command(context, base_request_params.allowed_method, base_request_params.command_type, base_request_params.success_code,
base_request_params.allowed_method,
base_request_params.command_type,
base_request_params.success_code,
base_request_params.error_code); base_request_params.error_code);
} }
} }
@@ -133,7 +130,6 @@ void HandleRestAPIPollTask(void *pvParameter)
void RestAPI::handle_endpoint_command(RequestContext* context, std::string allowed_method, CommandType command_type, int success_code, int error_code) void RestAPI::handle_endpoint_command(RequestContext* context, std::string allowed_method, CommandType command_type, int success_code, int error_code)
{ {
if (context->method != allowed_method) if (context->method != allowed_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");

View File

@@ -1,11 +1,11 @@
#pragma once #pragma once
#ifndef RESTAPI_HPP #ifndef RESTAPI_HPP
#define RESTAPI_HPP #define RESTAPI_HPP
#include <string>
#include <memory>
#include <unordered_map>
#include <mongoose.h> #include <mongoose.h>
#include <CommandManager.hpp> #include <CommandManager.hpp>
#include <memory>
#include <string>
#include <unordered_map>
#include "esp_log.h" #include "esp_log.h"
@@ -24,7 +24,8 @@ struct RequestBaseData
CommandType command_type; CommandType command_type;
int success_code; int success_code;
int error_code; int error_code;
RequestBaseData(std::string allowed_method, CommandType command_type, int success_code, int error_code) : allowed_method(allowed_method), command_type(command_type), success_code(success_code), error_code(error_code) {}; RequestBaseData(std::string allowed_method, CommandType command_type, int success_code, int error_code)
: allowed_method(allowed_method), command_type(command_type), success_code(success_code), error_code(error_code) {};
}; };
class RestAPI class RestAPI

View File

@@ -3,18 +3,18 @@
#define SERIALMANAGER_HPP #define SERIALMANAGER_HPP
#include <stdio.h> #include <stdio.h>
#include <string>
#include <memory>
#include <CommandManager.hpp> #include <CommandManager.hpp>
#include <ProjectConfig.hpp> #include <ProjectConfig.hpp>
#include "freertos/FreeRTOS.h" #include <memory>
#include "freertos/task.h" #include <string>
#include "freertos/queue.h"
#include "sdkconfig.h"
#include "esp_log.h"
#include "driver/gpio.h" #include "driver/gpio.h"
#include "esp_vfs_dev.h" #include "esp_log.h"
#include "esp_mac.h" #include "esp_mac.h"
#include "esp_vfs_dev.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#include "sdkconfig.h"
#ifndef BUF_SIZE #ifndef BUF_SIZE
#define BUF_SIZE (1024) #define BUF_SIZE (1024)

View File

@@ -1,7 +1,7 @@
#include "SerialManager.hpp" #include "SerialManager.hpp"
#include "driver/uart.h"
#include "esp_log.h" #include "esp_log.h"
#include "main_globals.hpp" #include "main_globals.hpp"
#include "driver/uart.h"
void SerialManager::setup() void SerialManager::setup()
{ {
@@ -18,11 +18,7 @@ void SerialManager::setup()
uart_driver_install(uart_num, BUF_SIZE, BUF_SIZE, 0, NULL, 0); uart_driver_install(uart_num, BUF_SIZE, BUF_SIZE, 0, NULL, 0);
uart_param_config(uart_num, &uart_config); uart_param_config(uart_num, &uart_config);
uart_set_pin(uart_num, uart_set_pin(uart_num, CONFIG_UART_TX_PIN, CONFIG_UART_RX_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
CONFIG_UART_TX_PIN,
CONFIG_UART_RX_PIN,
UART_PIN_NO_CHANGE,
UART_PIN_NO_CHANGE);
gpio_set_pull_mode(static_cast<gpio_num_t>(CONFIG_UART_RX_PIN), GPIO_PULLDOWN_ONLY); gpio_set_pull_mode(static_cast<gpio_num_t>(CONFIG_UART_RX_PIN), GPIO_PULLDOWN_ONLY);

View File

@@ -1,8 +1,8 @@
#include "SerialManager.hpp" #include "SerialManager.hpp"
#include "esp_log.h"
#include "main_globals.hpp"
#include "driver/usb_serial_jtag.h" #include "driver/usb_serial_jtag.h"
#include "esp_log.h"
#include "esp_vfs_usb_serial_jtag.h" #include "esp_vfs_usb_serial_jtag.h"
#include "main_globals.hpp"
#include "tusb.h" #include "tusb.h"
@@ -146,7 +146,6 @@ extern "C" void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts)
void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding) void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding)
{ {
(void)itf; (void)itf;
ESP_LOGI("[SERIAL]", "CDC line coding: %" PRIu32 " bps, %d stop bits, %d parity, %d data bits", ESP_LOGI("[SERIAL]", "CDC line coding: %" PRIu32 " bps, %d stop bits, %d parity, %d data bits", p_line_coding->bit_rate, p_line_coding->stop_bits,
p_line_coding->bit_rate, p_line_coding->stop_bits,
p_line_coding->parity, p_line_coding->data_bits); p_line_coding->parity, p_line_coding->data_bits);
} }

View File

@@ -11,7 +11,6 @@ void StateManager::HandleUpdateState()
{ {
switch (eventBuffer.source) switch (eventBuffer.source)
{ {
case EventSource::WIFI: case EventSource::WIFI:
{ {
this->wifi_state = std::get<WiFiState_e>(eventBuffer.value); this->wifi_state = std::get<WiFiState_e>(eventBuffer.value);

View File

@@ -11,11 +11,11 @@
enum class LEDStates_e enum class LEDStates_e
{ {
LedStateNone, // Idle / no indication (LED off) LedStateNone, // Idle / no indication (LED off)
LedStateStreaming, // Active streaming (UVC or WiFi) steady ON LedStateStreaming, // Active streaming (UVC or WiFi) - steady ON
LedStateStoppedStreaming, // Streaming stopped intentionally steady OFF (could differentiate later) LedStateStoppedStreaming, // Streaming stopped intentionally - steady OFF (could differentiate later)
CameraError, // Camera init / runtime failure double blink pattern CameraError, // Camera init / runtime failure - double blink pattern
WiFiStateError, // WiFi connection error distinctive blink sequence WiFiStateError, // WiFi connection error - distinctive blink sequence
WiFiStateConnecting, // WiFi association / DHCP pending slow blink WiFiStateConnecting, // WiFi association / DHCP pending - slow blink
WiFiStateConnected // WiFi connected (momentary confirmation burst) WiFiStateConnected // WiFi connected (momentary confirmation burst)
}; };

View File

@@ -6,9 +6,7 @@ constexpr static const char *STREAM_PART = "Content-Type: image/jpeg\r\nContent-
static const char* STREAM_SERVER_TAG = "[STREAM_SERVER]"; static const char* STREAM_SERVER_TAG = "[STREAM_SERVER]";
StreamServer::StreamServer(const int STREAM_PORT, StateManager *stateManager) : STREAM_SERVER_PORT(STREAM_PORT), stateManager(stateManager) StreamServer::StreamServer(const int STREAM_PORT, StateManager* stateManager) : STREAM_SERVER_PORT(STREAM_PORT), stateManager(stateManager) {}
{
}
esp_err_t StreamHelpers::stream(httpd_req_t* req) esp_err_t StreamHelpers::stream(httpd_req_t* req)
{ {
@@ -19,7 +17,7 @@ esp_err_t StreamHelpers::stream(httpd_req_t *req)
size_t _jpg_buf_len = 0; size_t _jpg_buf_len = 0;
uint8_t* _jpg_buf = nullptr; uint8_t* _jpg_buf = nullptr;
// Buffer for multipart header; was mistakenly declared as array of pointers // Buffer for multipart header
char part_buf[256]; char part_buf[256];
static int64_t last_frame = 0; static int64_t last_frame = 0;
if (!last_frame) if (!last_frame)

View File

@@ -4,13 +4,13 @@
#define PART_BOUNDARY "123456789000000000000987654321" #define PART_BOUNDARY "123456789000000000000987654321"
#include "esp_log.h"
#include "esp_camera.h"
#include "esp_http_server.h"
#include "esp_timer.h"
#include <StateManager.hpp> #include <StateManager.hpp>
#include <WebSocketLogger.hpp> #include <WebSocketLogger.hpp>
#include <helpers.hpp> #include <helpers.hpp>
#include "esp_camera.h"
#include "esp_http_server.h"
#include "esp_log.h"
#include "esp_timer.h"
extern WebSocketLogger webSocketLogger; extern WebSocketLogger webSocketLogger;
@@ -18,7 +18,7 @@ namespace StreamHelpers
{ {
esp_err_t stream(httpd_req_t* req); esp_err_t stream(httpd_req_t* req);
esp_err_t ws_logs_handle(httpd_req_t* req); esp_err_t ws_logs_handle(httpd_req_t* req);
} } // namespace StreamHelpers
class StreamServer class StreamServer
{ {

View File

@@ -33,8 +33,8 @@ extern "C"
} }
// 12 hex chars without separators // 12 hex chars without separators
snprintf(serial_number_str, sizeof(serial_number_str), "%02X%02X%02X%02X%02X%02X", snprintf(serial_number_str, sizeof(serial_number_str), "%02X%02X%02X%02X%02X%02X", mac_address[0], mac_address[1], mac_address[2], mac_address[3],
mac_address[0], mac_address[1], mac_address[2], mac_address[3], mac_address[4], mac_address[5]); mac_address[4], mac_address[5]);
} }
return serial_number_str; return serial_number_str;
} }

View File

@@ -5,15 +5,15 @@
#include "sdkconfig.h" #include "sdkconfig.h"
#ifdef CONFIG_GENERAL_INCLUDE_UVC_MODE #ifdef CONFIG_GENERAL_INCLUDE_UVC_MODE
#include "esp_timer.h"
#include "esp_mac.h"
#include "esp_camera.h"
#include <CameraManager.hpp> #include <CameraManager.hpp>
#include <StateManager.hpp> #include <StateManager.hpp>
#include "esp_camera.h"
#include "esp_log.h" #include "esp_log.h"
#include "usb_device_uvc.h" #include "esp_mac.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/queue.h" #include "freertos/queue.h"
#include "usb_device_uvc.h"
// we need access to the camera manager // we need access to the camera manager
// in order to update the frame settings // in order to update the frame settings
@@ -50,7 +50,7 @@ namespace UVCStreamHelpers
static void camera_stop_cb(void* cb_ctx); static void camera_stop_cb(void* cb_ctx);
static uvc_fb_t* camera_fb_get_cb(void* cb_ctx); static uvc_fb_t* camera_fb_get_cb(void* cb_ctx);
static void camera_fb_return_cb(uvc_fb_t* fb, void* cb_ctx); static void camera_fb_return_cb(uvc_fb_t* fb, void* cb_ctx);
} } // namespace UVCStreamHelpers
class UVCStreamManager class UVCStreamManager
{ {
@@ -62,7 +62,10 @@ public:
static constexpr uint32_t UVC_MAX_FRAMESIZE_SIZE = 75 * 1024; static constexpr uint32_t UVC_MAX_FRAMESIZE_SIZE = 75 * 1024;
esp_err_t setup(); esp_err_t setup();
esp_err_t start(); esp_err_t start();
uint32_t getUvcBufferSize() const { return uvc_buffer_size; } uint32_t getUvcBufferSize() const
{
return uvc_buffer_size;
}
}; };
#endif // UVCSTREAM_HPP #endif // UVCSTREAM_HPP

View File

@@ -71,6 +71,6 @@ namespace Logo
ESP_LOGI(LOGO_TAG, " "); ESP_LOGI(LOGO_TAG, " ");
ESP_LOGI(LOGO_TAG, " <============================================================================================================================> "); ESP_LOGI(LOGO_TAG, " <============================================================================================================================> ");
} }
}; }; // namespace Logo
#endif #endif

View File

@@ -6,8 +6,7 @@ static const char *TAG = "WiFiScanner";
WiFiScanner::WiFiScanner() {} WiFiScanner::WiFiScanner() {}
void WiFiScanner::scanResultCallback(void *arg, esp_event_base_t event_base, void WiFiScanner::scanResultCallback(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
int32_t event_id, void *event_data)
{ {
auto* scanner = static_cast<WiFiScanner*>(arg); auto* scanner = static_cast<WiFiScanner*>(arg);
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE)
@@ -74,8 +73,8 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
.channel = 0, // 0 means scan all channels .channel = 0, // 0 means scan all channels
.show_hidden = true, .show_hidden = true,
.scan_type = WIFI_SCAN_TYPE_ACTIVE, // Active scan .scan_type = WIFI_SCAN_TYPE_ACTIVE, // Active scan
.scan_time = { .scan_time = {.active =
.active = { {
.min = 120, // Min per channel .min = 120, // Min per channel
.max = 300 // Max per channel .max = 300 // Max per channel
}, },
@@ -109,17 +108,12 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
break; break;
} }
wifi_scan_config_t scan_config = { wifi_scan_config_t scan_config = {.ssid = nullptr,
.ssid = nullptr,
.bssid = nullptr, .bssid = nullptr,
.channel = ch, .channel = ch,
.show_hidden = true, .show_hidden = true,
.scan_type = WIFI_SCAN_TYPE_ACTIVE, .scan_type = WIFI_SCAN_TYPE_ACTIVE,
.scan_time = { .scan_time = {.active = {.min = 100, .max = 200}, .passive = 300},
.active = {
.min = 100,
.max = 200},
.passive = 300},
.home_chan_dwell_time = 0, .home_chan_dwell_time = 0,
.channel_bitmap = 0}; .channel_bitmap = 0};

View File

@@ -2,10 +2,10 @@
#ifndef WIFI_SCANNER_HPP #ifndef WIFI_SCANNER_HPP
#define WIFI_SCANNER_HPP #define WIFI_SCANNER_HPP
#include <vector>
#include <string> #include <string>
#include "esp_wifi.h" #include <vector>
#include "esp_log.h" #include "esp_log.h"
#include "esp_wifi.h"
struct WiFiNetwork struct WiFiNetwork
{ {

View File

@@ -5,8 +5,7 @@ static auto WIFI_MANAGER_TAG = "[WIFI_MANAGER]";
int s_retry_num = 0; int s_retry_num = 0;
EventGroupHandle_t s_wifi_event_group; EventGroupHandle_t s_wifi_event_group;
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_MANAGER_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)
@@ -44,7 +43,9 @@ void WiFiManagerHelpers::event_handler(void *arg, esp_event_base_t event_base,
} }
WiFiManager::WiFiManager(std::shared_ptr<ProjectConfig> deviceConfig, QueueHandle_t eventQueue, StateManager* stateManager) WiFiManager::WiFiManager(std::shared_ptr<ProjectConfig> deviceConfig, QueueHandle_t eventQueue, StateManager* stateManager)
: deviceConfig(deviceConfig), eventQueue(eventQueue), stateManager(stateManager), wifiScanner(std::make_unique<WiFiScanner>()) {} : deviceConfig(deviceConfig), eventQueue(eventQueue), stateManager(stateManager), wifiScanner(std::make_unique<WiFiScanner>())
{
}
void WiFiManager::SetCredentials(const char* ssid, const char* password) void WiFiManager::SetCredentials(const char* ssid, const char* password)
{ {
@@ -94,8 +95,7 @@ void WiFiManager::SetCredentials(const char *ssid, const char *password)
// Log what we're trying to connect to with detailed debugging // Log what we're trying to connect to with detailed debugging
ESP_LOGI(WIFI_MANAGER_TAG, "Setting credentials for SSID: '%s' (length: %d)", ssid, (int)strlen(ssid)); ESP_LOGI(WIFI_MANAGER_TAG, "Setting credentials for SSID: '%s' (length: %d)", ssid, (int)strlen(ssid));
ESP_LOGI(WIFI_MANAGER_TAG, "Password: '%s' (length: %d)", password, (int)strlen(password)); ESP_LOGI(WIFI_MANAGER_TAG, "Password: '%s' (length: %d)", password, (int)strlen(password));
ESP_LOGI(WIFI_MANAGER_TAG, "Auth mode: %d, PMF capable: %d", ESP_LOGI(WIFI_MANAGER_TAG, "Auth mode: %d, PMF capable: %d", _wifi_cfg.sta.threshold.authmode, _wifi_cfg.sta.pmf_cfg.capable);
_wifi_cfg.sta.threshold.authmode, _wifi_cfg.sta.pmf_cfg.capable);
} }
void WiFiManager::ConnectWithHardcodedCredentials() void WiFiManager::ConnectWithHardcodedCredentials()
@@ -104,7 +104,8 @@ void WiFiManager::ConnectWithHardcodedCredentials()
this->SetCredentials(CONFIG_WIFI_SSID, CONFIG_WIFI_PASSWORD); this->SetCredentials(CONFIG_WIFI_SSID, CONFIG_WIFI_PASSWORD);
wifi_mode_t mode; wifi_mode_t mode;
if (esp_wifi_get_mode(&mode) == ESP_OK) { if (esp_wifi_get_mode(&mode) == ESP_OK)
{
esp_wifi_stop(); esp_wifi_stop();
} }
@@ -118,18 +119,13 @@ void WiFiManager::ConnectWithHardcodedCredentials()
xQueueSend(this->eventQueue, &event, 10); xQueueSend(this->eventQueue, &event, 10);
// Use shorter timeout for faster startup - 8 seconds should be enough for most networks // Use shorter timeout for faster startup - 8 seconds should be enough for most networks
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, pdFALSE, pdFALSE, pdMS_TO_TICKS(8000));
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE,
pdFALSE,
pdMS_TO_TICKS(8000));
/* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
* happened. */ * happened. */
if (bits & WIFI_CONNECTED_BIT) if (bits & WIFI_CONNECTED_BIT)
{ {
ESP_LOGI(WIFI_MANAGER_TAG, "connected to ap SSID:%p password:%p", 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;
xQueueSend(this->eventQueue, &event, 10); xQueueSend(this->eventQueue, &event, 10);
@@ -137,8 +133,7 @@ void WiFiManager::ConnectWithHardcodedCredentials()
else if (bits & WIFI_FAIL_BIT) else if (bits & WIFI_FAIL_BIT)
{ {
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to SSID:%p, password:%p", 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;
xQueueSend(this->eventQueue, &event, 10); xQueueSend(this->eventQueue, &event, 10);
@@ -194,23 +189,18 @@ void WiFiManager::ConnectWithStoredCredentials()
event.value = WiFiState_e::WiFiState_Connecting; event.value = WiFiState_e::WiFiState_Connecting;
xQueueSend(this->eventQueue, &event, 10); xQueueSend(this->eventQueue, &event, 10);
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, pdFALSE, pdFALSE,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE,
pdFALSE,
pdMS_TO_TICKS(10000)); // 10 second timeout for faster failover pdMS_TO_TICKS(10000)); // 10 second timeout for faster failover
if (bits & WIFI_CONNECTED_BIT) if (bits & WIFI_CONNECTED_BIT)
{ {
ESP_LOGI(WIFI_MANAGER_TAG, "connected to ap SSID:%s", ESP_LOGI(WIFI_MANAGER_TAG, "connected to ap SSID:%s", network.ssid.c_str());
network.ssid.c_str());
event.value = WiFiState_e::WiFiState_Connected; event.value = WiFiState_e::WiFiState_Connected;
xQueueSend(this->eventQueue, &event, 10); xQueueSend(this->eventQueue, &event, 10);
return; return;
} }
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to SSID:%s, trying next stored network", ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to SSID:%s, trying next stored network", network.ssid.c_str());
network.ssid.c_str());
// Disconnect before trying next network // Disconnect before trying next network
esp_wifi_disconnect(); esp_wifi_disconnect();
@@ -232,7 +222,8 @@ void WiFiManager::SetupAccessPoint()
ESP_ERROR_CHECK(esp_wifi_init(&esp_wifi_ap_init_config)); ESP_ERROR_CHECK(esp_wifi_init(&esp_wifi_ap_init_config));
wifi_config_t ap_wifi_config = { wifi_config_t ap_wifi_config = {
.ap = { .ap =
{
.ssid = CONFIG_WIFI_AP_SSID, .ssid = CONFIG_WIFI_AP_SSID,
.password = CONFIG_WIFI_AP_PASSWORD, .password = CONFIG_WIFI_AP_PASSWORD,
.max_connection = 1, .max_connection = 1,
@@ -370,16 +361,8 @@ void WiFiManager::Begin()
wifi_init_config_t esp_wifi_init_config = WIFI_INIT_CONFIG_DEFAULT(); wifi_init_config_t esp_wifi_init_config = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&esp_wifi_init_config)); ESP_ERROR_CHECK(esp_wifi_init(&esp_wifi_init_config));
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &WiFiManagerHelpers::event_handler, nullptr, &instance_any_id));
ESP_EVENT_ANY_ID, ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &WiFiManagerHelpers::event_handler, nullptr, &instance_got_ip));
&WiFiManagerHelpers::event_handler,
nullptr,
&instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
IP_EVENT_STA_GOT_IP,
&WiFiManagerHelpers::event_handler,
nullptr,
&instance_got_ip));
_wifi_cfg = {}; _wifi_cfg = {};
_wifi_cfg.sta.threshold.authmode = WIFI_AUTH_OPEN; // Start with open, will be set properly by SetCredentials _wifi_cfg.sta.threshold.authmode = WIFI_AUTH_OPEN; // Start with open, will be set properly by SetCredentials

View File

@@ -2,16 +2,16 @@
#ifndef WIFIHANDLER_HPP #ifndef WIFIHANDLER_HPP
#define WIFIHANDLER_HPP #define WIFIHANDLER_HPP
#include <string>
#include <cstring>
#include <algorithm>
#include <StateManager.hpp>
#include <ProjectConfig.hpp> #include <ProjectConfig.hpp>
#include <StateManager.hpp>
#include <algorithm>
#include <cstring>
#include <string>
#include "WiFiScanner.hpp" #include "WiFiScanner.hpp"
#include "esp_event.h" #include "esp_event.h"
#include "esp_wifi.h"
#include "esp_log.h" #include "esp_log.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
@@ -21,8 +21,7 @@
namespace WiFiManagerHelpers namespace WiFiManagerHelpers
{ {
void event_handler(void *arg, esp_event_base_t event_base, void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data);
int32_t event_id, void *event_data);
} }
class WiFiManager class WiFiManager

View File

@@ -1,27 +1,27 @@
#include <cstdio> #include <cstdio>
#include <string> #include <string>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h" #include "driver/gpio.h"
#include "esp_log.h" #include "esp_log.h"
#include "esp_timer.h" #include "esp_timer.h"
#include "sdkconfig.h" #include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#include "nvs_flash.h" #include "nvs_flash.h"
#include "sdkconfig.h"
#include <openiris_logo.hpp> #include <CameraManager.hpp>
#include <wifiManager.hpp> #include <CommandManager.hpp>
#include <ProjectConfig.hpp>
#include <StateManager.hpp>
#include <LEDManager.hpp> #include <LEDManager.hpp>
#include <MDNSManager.hpp> #include <MDNSManager.hpp>
#include <CameraManager.hpp> #include <ProjectConfig.hpp>
#include <WebSocketLogger.hpp>
#include <StreamServer.hpp>
#include <CommandManager.hpp>
#include <SerialManager.hpp>
#include <RestAPI.hpp> #include <RestAPI.hpp>
#include <SerialManager.hpp>
#include <StateManager.hpp>
#include <StreamServer.hpp>
#include <WebSocketLogger.hpp>
#include <main_globals.hpp> #include <main_globals.hpp>
#include <openiris_logo.hpp>
#include <wifiManager.hpp>
#if CONFIG_MONITORING_LED_CURRENT || CONFIG_MONITORING_BATTERY_ENABLE #if CONFIG_MONITORING_LED_CURRENT || CONFIG_MONITORING_BATTERY_ENABLE
#include <MonitoringManager.hpp> #include <MonitoringManager.hpp>
@@ -131,8 +131,7 @@ void launch_streaming()
// Callback for automatic startup after delay // Callback for automatic startup after delay
void startup_timer_callback(void* arg) void startup_timer_callback(void* arg)
{ {
ESP_LOGI("[MAIN]", "Startup timer fired, startupCommandReceived=%s, startupPaused=%s", ESP_LOGI("[MAIN]", "Startup timer fired, startupCommandReceived=%s, startupPaused=%s", getStartupCommandReceived() ? "true" : "false",
getStartupCommandReceived() ? "true" : "false",
getStartupPaused() ? "true" : "false"); getStartupPaused() ? "true" : "false");
if (!getStartupCommandReceived() && !getStartupPaused()) if (!getStartupCommandReceived() && !getStartupPaused())
@@ -199,13 +198,7 @@ void startWiredMode(bool shouldCloseSerialManager)
} }
ESP_LOGI("[MAIN]", "Starting CDC Serial Manager Task"); ESP_LOGI("[MAIN]", "Starting CDC Serial Manager Task");
xTaskCreate( xTaskCreate(HandleCDCSerialManagerTask, "HandleCDCSerialManagerTask", 1024 * 6, commandManager.get(), 1, nullptr);
HandleCDCSerialManagerTask,
"HandleCDCSerialManagerTask",
1024 * 6,
commandManager.get(),
1,
nullptr);
ESP_LOGI("[MAIN]", "Starting UVC streaming"); ESP_LOGI("[MAIN]", "Starting UVC streaming");
@@ -227,11 +220,7 @@ void startWiFiMode()
{ {
streamServer.startStreamServer(); streamServer.startStreamServer();
} }
xTaskCreate( xTaskCreate(HandleRestAPIPollTask, "HandleRestAPIPollTask", 2024 * 2, restAPI.get(),
HandleRestAPIPollTask,
"HandleRestAPIPollTask",
2024 * 2,
restAPI.get(),
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
nullptr); nullptr);
#else #else
@@ -251,11 +240,7 @@ void startSetupMode()
// Create a one-shot timer for 20 seconds // Create a one-shot timer for 20 seconds
const esp_timer_create_args_t startup_timer_args = { const esp_timer_create_args_t startup_timer_args = {
.callback = &startup_timer_callback, .callback = &startup_timer_callback, .arg = nullptr, .dispatch_method = ESP_TIMER_TASK, .name = "startup_timer", .skip_unhandled_events = false};
.arg = nullptr,
.dispatch_method = ESP_TIMER_TASK,
.name = "startup_timer",
.skip_unhandled_events = false};
ESP_ERROR_CHECK(esp_timer_create(&startup_timer_args, &timerHandle)); ESP_ERROR_CHECK(esp_timer_create(&startup_timer_args, &timerHandle));
ESP_ERROR_CHECK(esp_timer_start_once(timerHandle, startup_delay_s * 1000000)); ESP_ERROR_CHECK(esp_timer_start_once(timerHandle, startup_delay_s * 1000000));
@@ -290,35 +275,18 @@ extern "C" void app_main(void)
monitoringManager->start(); monitoringManager->start();
#endif #endif
xTaskCreate( xTaskCreate(HandleStateManagerTask, "HandleStateManagerTask", 1024 * 2, stateManager, 3,
HandleStateManagerTask,
"HandleStateManagerTask",
1024 * 2,
stateManager,
3,
nullptr // 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(HandleLEDDisplayTask, "HandleLEDDisplayTask", 1024 * 2, ledManager.get(), 3, nullptr);
HandleLEDDisplayTask,
"HandleLEDDisplayTask",
1024 * 2,
ledManager.get(),
3,
nullptr);
cameraHandler->setupCamera(); cameraHandler->setupCamera();
// let's keep the serial manager running for the duration of the setup // let's keep the serial manager running for the duration of the setup
// we'll clean it up later if need be // we'll clean it up later if need be
serialManager->setup(); serialManager->setup();
xTaskCreate( xTaskCreate(HandleSerialManagerTask, "HandleSerialManagerTask", 1024 * 6, serialManager, 1, &serialManagerHandle);
HandleSerialManagerTask,
"HandleSerialManagerTask",
1024 * 6,
serialManager,
1,
&serialManagerHandle);
StreamingMode mode = deviceConfig->getDeviceMode(); StreamingMode mode = deviceConfig->getDeviceMode();
if (mode == StreamingMode::UVC) if (mode == StreamingMode::UVC)