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

@@ -1,9 +1,8 @@
#include "CameraManager.hpp" #include "CameraManager.hpp"
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,29 +2,29 @@
#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
class CameraManager class CameraManager
{ {
private: private:
sensor_t *camera_sensor; sensor_t* camera_sensor;
std::shared_ptr<ProjectConfig> projectConfig; std::shared_ptr<ProjectConfig> projectConfig;
QueueHandle_t eventQueue; QueueHandle_t eventQueue;
camera_config_t config; camera_config_t config;
public: public:
CameraManager(std::shared_ptr<ProjectConfig> projectConfig, QueueHandle_t eventQueue); CameraManager(std::shared_ptr<ProjectConfig> projectConfig, QueueHandle_t eventQueue);
int setCameraResolution(framesize_t frameSize); int setCameraResolution(framesize_t frameSize);
bool setupCamera(); bool setupCamera();
@@ -32,7 +32,7 @@ public:
int setHFlip(int direction); int setHFlip(int direction);
int setVieWindow(int offsetX, int offsetY, int outputX, int outputY); int setVieWindow(int offsetX, int offsetY, int outputX, int outputY);
private: private:
void loadConfigData(); void loadConfigData();
void setupCameraPinout(); void setupCameraPinout();
void setupCameraSensor(); void setupCameraSensor();

View File

@@ -30,85 +30,62 @@ std::unordered_map<std::string, CommandType> commandTypeMap = {
{"get_who_am_i", CommandType::GET_WHO_AM_I}, {"get_who_am_i", CommandType::GET_WHO_AM_I},
}; };
std::function<CommandResult()> CommandManager::createCommand(const CommandType type, const nlohmann::json &json) const std::function<CommandResult()> CommandManager::createCommand(const CommandType type, const nlohmann::json& json) const
{ {
switch (type) switch (type)
{ {
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;
} }
@@ -129,7 +106,7 @@ CommandManagerResponse CommandManager::executeFromJson(const std::string_view js
nlohmann::json results = nlohmann::json::array(); nlohmann::json results = nlohmann::json::array();
for (auto &commandObject : parsedJson["commands"].items()) for (auto& commandObject : parsedJson["commands"].items())
{ {
auto commandData = commandObject.value(); auto commandData = commandObject.value();
if (!commandData.contains("command")) if (!commandData.contains("command"))

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
{ {
@@ -55,9 +55,9 @@ class CommandManager
{ {
std::shared_ptr<DependencyRegistry> registry; std::shared_ptr<DependencyRegistry> registry;
public: public:
explicit CommandManager(const std::shared_ptr<DependencyRegistry> &DependencyRegistry) : registry(DependencyRegistry) {}; explicit CommandManager(const std::shared_ptr<DependencyRegistry>& DependencyRegistry) : registry(DependencyRegistry) {};
std::function<CommandResult()> createCommand(const CommandType type, const nlohmann::json &json) const; std::function<CommandResult()> createCommand(const CommandType type, const nlohmann::json& json) const;
CommandManagerResponse executeFromJson(std::string_view json) const; CommandManagerResponse executeFromJson(std::string_view json) const;
CommandManagerResponse executeFromType(CommandType type, std::string_view json) const; CommandManagerResponse executeFromType(CommandType type, std::string_view json) const;

View File

@@ -1,24 +1,24 @@
#include "CommandResult.hpp" #include "CommandResult.hpp"
void to_json(nlohmann::json &j, const CommandResult &result) void to_json(nlohmann::json& j, const CommandResult& result)
{ {
j = nlohmann::json{{"status", result.isSuccess() ? "success" : "error"}, {"data", result.getData()}}; j = nlohmann::json{{"status", result.isSuccess() ? "success" : "error"}, {"data", result.getData()}};
} }
// defined only for interface compatibility, should not be used directly // defined only for interface compatibility, should not be used directly
void from_json(const nlohmann::json &j, CommandResult &result) void from_json(const nlohmann::json& j, CommandResult& result)
{ {
auto message = j.at("message"); auto message = j.at("message");
j.at("status") == "success" ? result = CommandResult::getSuccessResult(message) : result = CommandResult::getErrorResult(message); j.at("status") == "success" ? result = CommandResult::getSuccessResult(message) : result = CommandResult::getErrorResult(message);
} }
void to_json(nlohmann::json &j, const CommandManagerResponse &result) void to_json(nlohmann::json& j, const CommandManagerResponse& result)
{ {
j = result.getData(); j = result.getData();
} }
// defined only for interface compatibility, should not be used directly // defined only for interface compatibility, should not be used directly
void from_json(const nlohmann::json &j, CommandManagerResponse &result) void from_json(const nlohmann::json& j, CommandManagerResponse& result)
{ {
result = CommandManagerResponse(j.at("result")); result = CommandManagerResponse(j.at("result"));
} }

View File

@@ -2,30 +2,33 @@
#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;
class CommandResult class CommandResult
{ {
public: public:
enum class Status enum class Status
{ {
SUCCESS, SUCCESS,
FAILURE, FAILURE,
}; };
private: private:
nlohmann::json data; nlohmann::json data;
Status status; Status status;
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,23 +40,29 @@ 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);
void from_json(const nlohmann::json &j, CommandResult &result); void from_json(const nlohmann::json& j, CommandResult& result);
class CommandManagerResponse class CommandManagerResponse
{ {
private: private:
nlohmann::json data; nlohmann::json data;
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);
void from_json(const nlohmann::json &j, CommandManagerResponse &result); void from_json(const nlohmann::json& j, CommandManagerResponse& result);
#endif #endif

View File

@@ -1,11 +1,11 @@
#include "CommandSchema.hpp" #include "CommandSchema.hpp"
void to_json(nlohmann::json &j, const UpdateWifiPayload &payload) void to_json(nlohmann::json& j, const UpdateWifiPayload& payload)
{ {
j = nlohmann::json{{"name", payload.name}, {"ssid", payload.ssid}, {"password", payload.password}, {"channel", payload.channel}, {"power", payload.power}}; j = nlohmann::json{{"name", payload.name}, {"ssid", payload.ssid}, {"password", payload.password}, {"channel", payload.channel}, {"power", payload.power}};
} }
void from_json(const nlohmann::json &j, UpdateWifiPayload &payload) void from_json(const nlohmann::json& j, UpdateWifiPayload& payload)
{ {
payload.name = j.at("name").get<std::string>(); payload.name = j.at("name").get<std::string>();
if (j.contains("ssid")) if (j.contains("ssid"))
@@ -29,12 +29,12 @@ void from_json(const nlohmann::json &j, UpdateWifiPayload &payload)
} }
} }
void to_json(nlohmann::json &j, const UpdateAPWiFiPayload &payload) void to_json(nlohmann::json& j, const UpdateAPWiFiPayload& payload)
{ {
j = nlohmann::json{{"ssid", payload.ssid}, {"password", payload.password}, {"channel", payload.channel}}; j = nlohmann::json{{"ssid", payload.ssid}, {"password", payload.password}, {"channel", payload.channel}};
} }
void from_json(const nlohmann::json &j, UpdateAPWiFiPayload &payload) void from_json(const nlohmann::json& j, UpdateAPWiFiPayload& payload)
{ {
if (j.contains("ssid")) if (j.contains("ssid"))
{ {
@@ -51,12 +51,13 @@ 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)
{ {
if (j.contains("vflip")) if (j.contains("vflip"))
{ {

View File

@@ -26,8 +26,8 @@ struct UpdateWifiPayload : BasePayload
std::optional<uint8_t> power; std::optional<uint8_t> power;
}; };
void to_json(nlohmann::json &j, const UpdateWifiPayload &payload); void to_json(nlohmann::json& j, const UpdateWifiPayload& payload);
void from_json(const nlohmann::json &j, UpdateWifiPayload &payload); void from_json(const nlohmann::json& j, UpdateWifiPayload& payload);
struct deleteNetworkPayload : BasePayload struct deleteNetworkPayload : BasePayload
{ {
std::string name; std::string name;
@@ -42,8 +42,8 @@ struct UpdateAPWiFiPayload : BasePayload
std::optional<uint8_t> channel; std::optional<uint8_t> channel;
}; };
void to_json(nlohmann::json &j, const UpdateAPWiFiPayload &payload); void to_json(nlohmann::json& j, const UpdateAPWiFiPayload& payload);
void from_json(const nlohmann::json &j, UpdateAPWiFiPayload &payload); void from_json(const nlohmann::json& j, UpdateAPWiFiPayload& payload);
struct MDNSPayload : BasePayload struct MDNSPayload : BasePayload
{ {
std::string hostname; std::string hostname;
@@ -61,6 +61,6 @@ struct UpdateCameraConfigPayload : BasePayload
// TODO add more options here // TODO add more options here
}; };
void to_json(nlohmann::json &j, const UpdateCameraConfigPayload &payload); void to_json(nlohmann::json& j, const UpdateCameraConfigPayload& payload);
void from_json(const nlohmann::json &j, UpdateCameraConfigPayload &payload); void from_json(const nlohmann::json& j, UpdateCameraConfigPayload& payload);
#endif #endif

View File

@@ -17,7 +17,7 @@ class DependencyRegistry
{ {
std::unordered_map<DependencyType, std::shared_ptr<void>> services; std::unordered_map<DependencyType, std::shared_ptr<void>> services;
public: public:
template <typename ServiceType> template <typename ServiceType>
void registerService(DependencyType dependencyType, std::shared_ptr<ServiceType> service) void registerService(DependencyType dependencyType, std::shared_ptr<ServiceType> service)
{ {

View File

@@ -1,16 +1,14 @@
#include "camera_commands.hpp" #include "camera_commands.hpp"
CommandResult updateCameraCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json) CommandResult updateCameraCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
auto payload = json.get<UpdateCameraConfigPayload>(); auto payload = json.get<UpdateCameraConfigPayload>();
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,16 +1,16 @@
#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);
#endif #endif

View File

@@ -16,7 +16,7 @@ CommandResult getConfigCommand(std::shared_ptr<DependencyRegistry> registry)
return CommandResult::getSuccessResult(configRepresentation); return CommandResult::getSuccessResult(configRepresentation);
} }
CommandResult resetConfigCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json) CommandResult resetConfigCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
std::array<std::string, 4> supported_sections = { std::array<std::string, 4> supported_sections = {
"all", "all",

View File

@@ -1,13 +1,13 @@
#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);
CommandResult resetConfigCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json); CommandResult resetConfigCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);

View File

@@ -1,10 +1,10 @@
#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)
{ {
if (!json.contains("mode") || !json["mode"].is_number_integer()) if (!json.contains("mode") || !json["mode"].is_number_integer())
{ {
@@ -23,9 +23,8 @@ CommandResult setDeviceModeCommand(std::shared_ptr<DependencyRegistry> registry,
return CommandResult::getSuccessResult("Device mode set"); return CommandResult::getSuccessResult("Device mode set");
} }
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;
@@ -57,7 +56,7 @@ CommandResult updateOTACredentialsCommand(std::shared_ptr<DependencyRegistry> re
return CommandResult::getSuccessResult("OTA Config set"); return CommandResult::getSuccessResult("OTA Config set");
} }
CommandResult updateLEDDutyCycleCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json) CommandResult updateLEDDutyCycleCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
if (!json.contains("dutyCycle") || !json["dutyCycle"].is_number_integer()) if (!json.contains("dutyCycle") || !json["dutyCycle"].is_number_integer())
{ {
@@ -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);
@@ -117,9 +113,8 @@ CommandResult startStreamingCommand()
return CommandResult::getSuccessResult("Streaming starting"); return CommandResult::getSuccessResult("Streaming starting");
} }
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");
@@ -159,7 +154,7 @@ CommandResult getDeviceModeCommand(std::shared_ptr<DependencyRegistry> registry)
const auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config); const auto projectConfig = registry->resolve<ProjectConfig>(DependencyType::project_config);
StreamingMode currentMode = projectConfig->getDeviceMode(); StreamingMode currentMode = projectConfig->getDeviceMode();
const char *modeStr = "unknown"; const char* modeStr = "unknown";
switch (currentMode) switch (currentMode)
{ {
case StreamingMode::UVC: case StreamingMode::UVC:
@@ -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},
@@ -246,8 +239,8 @@ CommandResult getBatteryStatusCommand(std::shared_ptr<DependencyRegistry> regist
CommandResult getInfoCommand(std::shared_ptr<DependencyRegistry> /*registry*/) CommandResult getInfoCommand(std::shared_ptr<DependencyRegistry> /*registry*/)
{ {
const char *who = CONFIG_GENERAL_BOARD; const char* who = CONFIG_GENERAL_BOARD;
const char *ver = CONFIG_GENERAL_VERSION; const char* ver = CONFIG_GENERAL_VERSION;
// Ensure non-null strings // Ensure non-null strings
if (!who) if (!who)
who = ""; who = "";

View File

@@ -1,24 +1,24 @@
#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);
CommandResult updateLEDDutyCycleCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json); CommandResult updateLEDDutyCycleCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);
CommandResult getLEDDutyCycleCommand(std::shared_ptr<DependencyRegistry> registry); CommandResult getLEDDutyCycleCommand(std::shared_ptr<DependencyRegistry> registry);
CommandResult restartDeviceCommand(); CommandResult restartDeviceCommand();
CommandResult startStreamingCommand(); CommandResult startStreamingCommand();
CommandResult switchModeCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json); CommandResult switchModeCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);
CommandResult getDeviceModeCommand(std::shared_ptr<DependencyRegistry> registry); CommandResult getDeviceModeCommand(std::shared_ptr<DependencyRegistry> registry);

View File

@@ -1,6 +1,6 @@
#include "mdns_commands.hpp" #include "mdns_commands.hpp"
CommandResult setMDNSCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json) CommandResult setMDNSCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
const auto payload = json.get<MDNSPayload>(); const auto payload = json.get<MDNSPayload>();
if (payload.hostname.empty()) if (payload.hostname.empty())

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

@@ -1,7 +1,7 @@
#include "scan_commands.hpp" #include "scan_commands.hpp"
#include "sdkconfig.h" #include "sdkconfig.h"
CommandResult scanNetworksCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json) CommandResult scanNetworksCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
#if !CONFIG_GENERAL_ENABLE_WIRELESS #if !CONFIG_GENERAL_ENABLE_WIRELESS
return CommandResult::getErrorResult("Not supported by current firmware"); return CommandResult::getErrorResult("Not supported by current firmware");
@@ -24,16 +24,14 @@ CommandResult scanNetworksCommand(std::shared_ptr<DependencyRegistry> registry,
nlohmann::json result; nlohmann::json result;
std::vector<nlohmann::json> networksJson; std::vector<nlohmann::json> networksJson;
for (const auto &network : networks) for (const auto& network : networks)
{ {
nlohmann::json networkItem; nlohmann::json networkItem;
networkItem["ssid"] = network.ssid; networkItem["ssid"] = network.ssid;
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,13 +1,13 @@
#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);
#endif #endif

View File

@@ -1,13 +1,13 @@
#include "simple_commands.hpp" #include "simple_commands.hpp"
static const char *TAG = "SimpleCommands"; static const char* TAG = "SimpleCommands";
CommandResult PingCommand() CommandResult PingCommand()
{ {
return CommandResult::getSuccessResult("pong"); return CommandResult::getSuccessResult("pong");
}; };
CommandResult PauseCommand(const nlohmann::json &json) CommandResult PauseCommand(const nlohmann::json& json)
{ {
auto pause = true; auto pause = true;

View File

@@ -1,13 +1,13 @@
#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);
#endif #endif

View File

@@ -2,7 +2,7 @@
#include "esp_netif.h" #include "esp_netif.h"
#include "sdkconfig.h" #include "sdkconfig.h"
CommandResult setWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json) CommandResult setWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
#if !CONFIG_GENERAL_ENABLE_WIRELESS #if !CONFIG_GENERAL_ENABLE_WIRELESS
return CommandResult::getErrorResult("Not supported by current firmware"); return CommandResult::getErrorResult("Not supported by current firmware");
@@ -20,17 +20,12 @@ 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");
} }
CommandResult deleteWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json) CommandResult deleteWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
#if !CONFIG_GENERAL_ENABLE_WIRELESS #if !CONFIG_GENERAL_ENABLE_WIRELESS
return CommandResult::getErrorResult("Not supported by current firmware"); return CommandResult::getErrorResult("Not supported by current firmware");
@@ -46,7 +41,7 @@ CommandResult deleteWiFiCommand(std::shared_ptr<DependencyRegistry> registry, co
return CommandResult::getSuccessResult("Config updated"); return CommandResult::getSuccessResult("Config updated");
} }
CommandResult updateWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json) CommandResult updateWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
#if !CONFIG_GENERAL_ENABLE_WIRELESS #if !CONFIG_GENERAL_ENABLE_WIRELESS
return CommandResult::getErrorResult("Not supported by current firmware"); return CommandResult::getErrorResult("Not supported by current firmware");
@@ -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);
@@ -79,7 +69,7 @@ CommandResult updateWiFiCommand(std::shared_ptr<DependencyRegistry> registry, co
return CommandResult::getErrorResult("Requested network does not exist"); return CommandResult::getErrorResult("Requested network does not exist");
} }
CommandResult updateAPWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json) CommandResult updateAPWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json)
{ {
#if !CONFIG_GENERAL_ENABLE_WIRELESS #if !CONFIG_GENERAL_ENABLE_WIRELESS
return CommandResult::getErrorResult("Not supported by current firmware"); return CommandResult::getErrorResult("Not supported by current firmware");
@@ -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);
@@ -143,7 +132,7 @@ CommandResult getWiFiStatusCommand(std::shared_ptr<DependencyRegistry> registry)
{ {
// Get IP address from ESP32 // Get IP address from ESP32
esp_netif_ip_info_t ip_info; esp_netif_ip_info_t ip_info;
esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); esp_netif_t* netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
if (netif && esp_netif_get_ip_info(netif, &ip_info) == ESP_OK) if (netif && esp_netif_get_ip_info(netif, &ip_info) == ESP_OK)
{ {
char ip_str[16]; char ip_str[16];

View File

@@ -1,21 +1,21 @@
#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);
CommandResult deleteWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json); CommandResult deleteWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);
CommandResult updateWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json); CommandResult updateWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);
CommandResult updateAPWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json &json); CommandResult updateAPWiFiCommand(std::shared_ptr<DependencyRegistry> registry, const nlohmann::json& json);
CommandResult getWiFiStatusCommand(std::shared_ptr<DependencyRegistry> registry); CommandResult getWiFiStatusCommand(std::shared_ptr<DependencyRegistry> registry);
CommandResult connectWiFiCommand(std::shared_ptr<DependencyRegistry> registry); CommandResult connectWiFiCommand(std::shared_ptr<DependencyRegistry> registry);

View File

@@ -1,6 +1,6 @@
#include "helpers.hpp" #include "helpers.hpp"
char *Helpers::itoa(int value, char *result, int base) char* Helpers::itoa(int value, char* result, int base)
{ {
// check that the base if valid // check that the base if valid
if (base < 2 || base > 36) if (base < 2 || base > 36)
@@ -32,7 +32,7 @@ char *Helpers::itoa(int value, char *result, int base)
return result; return result;
} }
void split(const std::string &str, const std::string &splitBy, std::vector<std::string> &tokens) void split(const std::string& str, const std::string& splitBy, std::vector<std::string>& tokens)
{ {
/* Store the original string in the array, so we can loop the rest /* Store the original string in the array, so we can loop the rest
* of the algorithm. */ * of the algorithm. */
@@ -67,7 +67,7 @@ void split(const std::string &str, const std::string &splitBy, std::vector<std::
} }
} }
std::vector<std::string> Helpers::split(const std::string &s, char delimiter) std::vector<std::string> Helpers::split(const std::string& s, char delimiter)
{ {
std::vector<std::string> parts; std::vector<std::string> parts;
std::string part; std::string part;

View File

@@ -1,27 +1,27 @@
#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
{ {
char *itoa(int value, char *result, int base); char* itoa(int value, char* result, int base);
void split(std::string str, std::string splitBy, std::vector<std::string> &tokens); void split(std::string str, std::string splitBy, std::vector<std::string>& tokens);
std::vector<std::string> split(const std::string &s, char delimiter); std::vector<std::string> split(const std::string& s, char delimiter);
/// @brief /// @brief
/// @tparam ...Args /// @tparam ...Args
/// @param format /// @param format
/// @param ...args /// @param ...args
/// @return /// @return
template <typename... Args> template <typename... Args>
std::string format_string(const std::string &format, Args... args) std::string format_string(const std::string& format, Args... args)
{ {
int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0' int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0'
if (size_s <= 0) if (size_s <= 0)
{ {
@@ -32,9 +32,9 @@ namespace Helpers
std::unique_ptr<char[]> buf(new char[size]); std::unique_ptr<char[]> buf(new char[size]);
std::snprintf(buf.get(), size, format.c_str(), args...); std::snprintf(buf.get(), size, format.c_str(), args...);
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
}
int64_t getTimeInMillis();
} }
int64_t getTimeInMillis();
} // namespace Helpers
#endif // HELPERS_HPP #endif // HELPERS_HPP

View File

@@ -28,12 +28,18 @@ void setStartupPaused(bool startupPaused)
} }
// Function to manually activate streaming // Function to manually activate streaming
void activateStreaming(void *arg) void activateStreaming(void* arg)
{ {
force_activate_streaming(); force_activate_streaming();
} }
// 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

@@ -9,7 +9,7 @@
// Function to manually activate streaming // Function to manually activate streaming
// designed to be scheduled as a task // designed to be scheduled as a task
// so that the serial manager has time to return the response // so that the serial manager has time to return the response
void activateStreaming(void *arg); void activateStreaming(void* arg);
bool getStartupCommandReceived(); bool getStartupCommandReceived();
void setStartupCommandReceived(bool startupCommandReceived); void setStartupCommandReceived(bool startupCommandReceived);

View File

@@ -1,6 +1,6 @@
#include "LEDManager.hpp" #include "LEDManager.hpp"
const char *LED_MANAGER_TAG = "[LED_MANAGER]"; const char* LED_MANAGER_TAG = "[LED_MANAGER]";
// Pattern design rules: // Pattern design rules:
// - Error states: isError=true, repeat indefinitely, easily distinguishable (avoid overlap). // - Error states: isError=true, repeat indefinitely, easily distinguishable (avoid overlap).
@@ -8,21 +8,21 @@ const char *LED_MANAGER_TAG = "[LED_MANAGER]";
// - Non-repeating notification (e.g. Connected) gives user a brief confirmation burst then turns off. // - Non-repeating notification (e.g. Connected) gives user a brief confirmation burst then turns off.
// Durations in ms. // Durations in ms.
ledStateMap_t LEDManager::ledStateMap = { ledStateMap_t LEDManager::ledStateMap = {
{ LEDStates_e::LedStateNone, { /*isError*/false, /*repeat*/false, {{LED_OFF, 1000}} } }, {LEDStates_e::LedStateNone, {/*isError*/ false, /*repeat*/ false, {{LED_OFF, 1000}}}},
{ LEDStates_e::LedStateStreaming, { false, /*repeat steady*/true, {{LED_ON, 1000}} } }, {LEDStates_e::LedStateStreaming, {false, /*repeat steady*/ true, {{LED_ON, 1000}}}},
{ LEDStates_e::LedStateStoppedStreaming, { false, true, {{LED_OFF, 1000}} } }, {LEDStates_e::LedStateStoppedStreaming, {false, true, {{LED_OFF, 1000}}}},
// CameraError: double blink pattern repeating // CameraError: double blink pattern repeating
{ LEDStates_e::CameraError, { true, true, {{ {LED_ON,300}, {LED_OFF,300}, {LED_ON,300}, {LED_OFF,700} }} } }, {LEDStates_e::CameraError, {true, true, {{{LED_ON, 300}, {LED_OFF, 300}, {LED_ON, 300}, {LED_OFF, 700}}}}},
// WiFiStateConnecting: balanced slow blink 400/400 // WiFiStateConnecting: balanced slow blink 400/400
{ LEDStates_e::WiFiStateConnecting, { false, true, {{ {LED_ON,400}, {LED_OFF,400} }} } }, {LEDStates_e::WiFiStateConnecting, {false, true, {{{LED_ON, 400}, {LED_OFF, 400}}}}},
// WiFiStateConnected: short 3 quick flashes then done (was long noisy burst before) // WiFiStateConnected: short 3 quick flashes then done (was long noisy burst before)
{ LEDStates_e::WiFiStateConnected, { false, false, {{ {LED_ON,150}, {LED_OFF,150}, {LED_ON,150}, {LED_OFF,150}, {LED_ON,150}, {LED_OFF,600} }} } }, {LEDStates_e::WiFiStateConnected, {false, false, {{{LED_ON, 150}, {LED_OFF, 150}, {LED_ON, 150}, {LED_OFF, 150}, {LED_ON, 150}, {LED_OFF, 600}}}}},
// WiFiStateError: asymmetric attention pattern (fast, pause, long, pause, fast) // WiFiStateError: asymmetric attention pattern (fast, pause, long, pause, fast)
{ 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,
@@ -195,9 +190,9 @@ void LEDManager::setExternalLEDDutyCycle(uint8_t dutyPercent)
#endif #endif
} }
void HandleLEDDisplayTask(void *pvParameter) void HandleLEDDisplayTask(void* pvParameter)
{ {
auto *ledManager = static_cast<LEDManager *>(pvParameter); auto* ledManager = static_cast<LEDManager*>(pvParameter);
TickType_t lastWakeTime = xTaskGetTickCount(); TickType_t lastWakeTime = xTaskGetTickCount();
while (true) while (true)

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,23 +36,28 @@ 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
{ {
public: public:
LEDManager(gpio_num_t blink_led_pin, gpio_num_t illumninator_led_pin, QueueHandle_t ledStateQueue, std::shared_ptr<ProjectConfig> deviceConfig); LEDManager(gpio_num_t blink_led_pin, gpio_num_t illumninator_led_pin, QueueHandle_t ledStateQueue, std::shared_ptr<ProjectConfig> deviceConfig);
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;
void displayCurrentPattern(); void displayCurrentPattern();
void updateState(LEDStates_e newState); void updateState(LEDStates_e newState);
@@ -77,5 +82,5 @@ private:
#endif #endif
}; };
void HandleLEDDisplayTask(void *pvParameter); void HandleLEDDisplayTask(void* pvParameter);
#endif #endif

View File

@@ -1,12 +1,12 @@
#include "MDNSManager.hpp" #include "MDNSManager.hpp"
static const char *MDNS_MANAGER_TAG = "[MDNS MANAGER]"; static const char* MDNS_MANAGER_TAG = "[MDNS MANAGER]";
MDNSManager::MDNSManager(std::shared_ptr<ProjectConfig> projectConfig, QueueHandle_t eventQueue) : projectConfig(projectConfig), eventQueue(eventQueue) {} MDNSManager::MDNSManager(std::shared_ptr<ProjectConfig> projectConfig, QueueHandle_t eventQueue) : projectConfig(projectConfig), eventQueue(eventQueue) {}
esp_err_t MDNSManager::start() esp_err_t MDNSManager::start()
{ {
const std::string &mdnsName = "_openiristracker"; const std::string& mdnsName = "_openiristracker";
{ {
SystemEvent event = {EventSource::MDNS, MDNSState_e::MDNSState_Starting}; SystemEvent event = {EventSource::MDNS, MDNSState_e::MDNSState_Starting};

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"
@@ -11,11 +11,11 @@
class MDNSManager class MDNSManager
{ {
private: private:
std::shared_ptr<ProjectConfig> projectConfig; std::shared_ptr<ProjectConfig> projectConfig;
QueueHandle_t eventQueue; QueueHandle_t eventQueue;
public: public:
MDNSManager(std::shared_ptr<ProjectConfig> projectConfig, QueueHandle_t eventQueue); MDNSManager(std::shared_ptr<ProjectConfig> projectConfig, QueueHandle_t eventQueue);
esp_err_t start(); esp_err_t start();
}; };

View File

@@ -13,7 +13,7 @@
#if defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32) #if defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32)
#include <esp_log.h> #include <esp_log.h>
static const char *TAG = "[AdcSampler]"; static const char* TAG = "[AdcSampler]";
// Static member initialization // Static member initialization
adc_oneshot_unit_handle_t AdcSampler::shared_unit_ = nullptr; adc_oneshot_unit_handle_t AdcSampler::shared_unit_ = nullptr;
@@ -22,11 +22,11 @@ AdcSampler::~AdcSampler()
{ {
if (cali_handle_) if (cali_handle_)
{ {
#if defined(CONFIG_IDF_TARGET_ESP32S3) #if defined(CONFIG_IDF_TARGET_ESP32S3)
adc_cali_delete_scheme_curve_fitting(cali_handle_); adc_cali_delete_scheme_curve_fitting(cali_handle_);
#elif defined(CONFIG_IDF_TARGET_ESP32) #elif defined(CONFIG_IDF_TARGET_ESP32)
adc_cali_delete_scheme_line_fitting(cali_handle_); adc_cali_delete_scheme_line_fitting(cali_handle_);
#endif #endif
cali_handle_ = nullptr; cali_handle_ = nullptr;
} }
} }
@@ -69,7 +69,7 @@ bool AdcSampler::init(int gpio, adc_atten_t atten, adc_bitwidth_t bitwidth, size
// ESP32-S3 uses curve-fitting, ESP32 uses line-fitting // ESP32-S3 uses curve-fitting, ESP32 uses line-fitting
esp_err_t cal_err = ESP_FAIL; esp_err_t cal_err = ESP_FAIL;
#if defined(CONFIG_IDF_TARGET_ESP32S3) #if defined(CONFIG_IDF_TARGET_ESP32S3)
// ESP32-S3 curve fitting calibration // ESP32-S3 curve fitting calibration
adc_cali_curve_fitting_config_t cal_cfg = { adc_cali_curve_fitting_config_t cal_cfg = {
.unit_id = unit_, .unit_id = unit_,
@@ -78,7 +78,7 @@ bool AdcSampler::init(int gpio, adc_atten_t atten, adc_bitwidth_t bitwidth, size
.bitwidth = bitwidth_, .bitwidth = bitwidth_,
}; };
cal_err = adc_cali_create_scheme_curve_fitting(&cal_cfg, &cali_handle_); cal_err = adc_cali_create_scheme_curve_fitting(&cal_cfg, &cali_handle_);
#elif defined(CONFIG_IDF_TARGET_ESP32) #elif defined(CONFIG_IDF_TARGET_ESP32)
// ESP32 line-fitting calibration is per-unit, not per-channel // ESP32 line-fitting calibration is per-unit, not per-channel
adc_cali_line_fitting_config_t cal_cfg = { adc_cali_line_fitting_config_t cal_cfg = {
.unit_id = unit_, .unit_id = unit_,
@@ -86,7 +86,7 @@ bool AdcSampler::init(int gpio, adc_atten_t atten, adc_bitwidth_t bitwidth, size
.bitwidth = bitwidth_, .bitwidth = bitwidth_,
}; };
cal_err = adc_cali_create_scheme_line_fitting(&cal_cfg, &cali_handle_); cal_err = adc_cali_create_scheme_line_fitting(&cal_cfg, &cali_handle_);
#endif #endif
if (cal_err == ESP_OK) if (cal_err == ESP_OK)
{ {
@@ -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
@@ -35,15 +35,15 @@
*/ */
class AdcSampler class AdcSampler
{ {
public: public:
AdcSampler() = default; AdcSampler() = default;
~AdcSampler(); ~AdcSampler();
// Non-copyable, non-movable (owns hardware resources) // Non-copyable, non-movable (owns hardware resources)
AdcSampler(const AdcSampler &) = delete; AdcSampler(const AdcSampler&) = delete;
AdcSampler &operator=(const AdcSampler &) = delete; AdcSampler& operator=(const AdcSampler&) = delete;
AdcSampler(AdcSampler &&) = delete; AdcSampler(AdcSampler&&) = delete;
AdcSampler &operator=(AdcSampler &&) = delete; AdcSampler& operator=(AdcSampler&&) = delete;
/** /**
* @brief Initialize the ADC channel on the shared ADC1 oneshot unit * @brief Initialize the ADC channel on the shared ADC1 oneshot unit
@@ -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,15 +65,21 @@ 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
bool ensure_unit(); bool ensure_unit();
bool configure_channel(int gpio, adc_atten_t atten, adc_bitwidth_t bitwidth); bool configure_channel(int gpio, adc_atten_t atten, adc_bitwidth_t bitwidth);
@@ -85,7 +88,7 @@ private:
* @brief Platform-specific GPIO to ADC channel mapping * @brief Platform-specific GPIO to ADC channel mapping
* @note Implemented separately in AdcSampler_esp32.cpp and AdcSampler_esp32s3.cpp * @note Implemented separately in AdcSampler_esp32.cpp and AdcSampler_esp32s3.cpp
*/ */
static bool map_gpio_to_channel(int gpio, adc_unit_t &unit, adc_channel_t &channel); static bool map_gpio_to_channel(int gpio, adc_unit_t& unit, adc_channel_t& channel);
// Shared ADC1 oneshot handle (single instance for all AdcSampler objects) // Shared ADC1 oneshot handle (single instance for all AdcSampler objects)
static adc_oneshot_unit_handle_t shared_unit_; static adc_oneshot_unit_handle_t shared_unit_;
@@ -110,10 +113,22 @@ private:
// Stub for unsupported targets to keep interfaces consistent // Stub for unsupported targets to keep interfaces consistent
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

@@ -19,7 +19,7 @@
#if defined(CONFIG_IDF_TARGET_ESP32) #if defined(CONFIG_IDF_TARGET_ESP32)
bool AdcSampler::map_gpio_to_channel(int gpio, adc_unit_t &unit, adc_channel_t &channel) bool AdcSampler::map_gpio_to_channel(int gpio, adc_unit_t& unit, adc_channel_t& channel)
{ {
unit = ADC_UNIT_1; // Only use ADC1 to avoid Wi-Fi conflict unit = ADC_UNIT_1; // Only use ADC1 to avoid Wi-Fi conflict

View File

@@ -21,7 +21,7 @@
#if defined(CONFIG_IDF_TARGET_ESP32S3) #if defined(CONFIG_IDF_TARGET_ESP32S3)
bool AdcSampler::map_gpio_to_channel(int gpio, adc_unit_t &unit, adc_channel_t &channel) bool AdcSampler::map_gpio_to_channel(int gpio, adc_unit_t& unit, adc_channel_t& channel)
{ {
unit = ADC_UNIT_1; // Only use ADC1 to avoid Wi-Fi conflict unit = ADC_UNIT_1; // Only use ADC1 to avoid Wi-Fi conflict

View File

@@ -9,7 +9,7 @@
#include "BatteryMonitor.hpp" #include "BatteryMonitor.hpp"
#include <esp_log.h> #include <esp_log.h>
static const char *TAG = "[BatteryMonitor]"; static const char* TAG = "[BatteryMonitor]";
bool BatteryMonitor::setup() bool BatteryMonitor::setup()
{ {
@@ -86,8 +86,8 @@ float BatteryMonitor::voltageToPercentage(int voltage_mv)
// Linear interpolation between lookup table points // Linear interpolation between lookup table points
for (size_t i = 0; i < soc_lookup_.size() - 1; ++i) for (size_t i = 0; i < soc_lookup_.size() - 1; ++i)
{ {
const auto &high = soc_lookup_[i]; const auto& high = soc_lookup_[i];
const auto &low = soc_lookup_[i + 1]; const auto& low = soc_lookup_[i + 1];
if (volts <= high.voltage_mv && volts >= low.voltage_mv) if (volts <= high.voltage_mv && volts >= low.voltage_mv)
{ {

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
@@ -48,7 +47,7 @@ struct BatteryStatus
*/ */
class BatteryMonitor class BatteryMonitor
{ {
public: public:
BatteryMonitor() = default; BatteryMonitor() = default;
~BatteryMonitor() = default; ~BatteryMonitor() = default;
@@ -87,7 +86,7 @@ public:
#endif #endif
} }
private: private:
/** /**
* @brief Li-ion/Li-Po voltage to SOC lookup table entry * @brief Li-ion/Li-Po voltage to SOC lookup table entry
*/ */

View File

@@ -9,7 +9,7 @@
#include "CurrentMonitor.hpp" #include "CurrentMonitor.hpp"
#include <esp_log.h> #include <esp_log.h>
static const char *TAG = "[CurrentMonitor]"; static const char* TAG = "[CurrentMonitor]";
void CurrentMonitor::setup() void CurrentMonitor::setup()
{ {

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
@@ -34,7 +34,7 @@
*/ */
class CurrentMonitor class CurrentMonitor
{ {
public: public:
CurrentMonitor() = default; CurrentMonitor() = default;
~CurrentMonitor() = default; ~CurrentMonitor() = default;
@@ -54,7 +54,7 @@ public:
#endif #endif
} }
private: private:
mutable AdcSampler adc_; // ADC sampler instance (BSP layer) mutable AdcSampler adc_; // ADC sampler instance (BSP layer)
}; };

View File

@@ -10,7 +10,7 @@
#include <esp_log.h> #include <esp_log.h>
#include "sdkconfig.h" #include "sdkconfig.h"
static const char *TAG = "[MonitoringManager]"; static const char* TAG = "[MonitoringManager]";
void MonitoringManager::setup() void MonitoringManager::setup()
{ {
@@ -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
{ {
@@ -77,9 +71,9 @@ void MonitoringManager::stop()
} }
} }
void MonitoringManager::taskEntry(void *arg) void MonitoringManager::taskEntry(void* arg)
{ {
static_cast<MonitoringManager *>(arg)->run(); static_cast<MonitoringManager*>(arg)->run();
} }
void MonitoringManager::run() void MonitoringManager::run()

View File

@@ -35,7 +35,7 @@
*/ */
class MonitoringManager class MonitoringManager
{ {
public: public:
MonitoringManager() = default; MonitoringManager() = default;
~MonitoringManager() = default; ~MonitoringManager() = default;
@@ -57,8 +57,8 @@ public:
return CurrentMonitor::isEnabled() || BatteryMonitor::isEnabled(); return CurrentMonitor::isEnabled() || BatteryMonitor::isEnabled();
} }
private: private:
static void taskEntry(void *arg); static void taskEntry(void* arg);
void run(); void run();
TaskHandle_t task_{nullptr}; TaskHandle_t task_{nullptr};

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,14 +2,14 @@
#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
{ {
void ScheduleRestart(int milliseconds); void ScheduleRestart(int milliseconds);
}; };
#endif #endif

View File

@@ -3,13 +3,13 @@
#include "Preferences.hpp" #include "Preferences.hpp"
const char *PREFERENCES_TAG = "[PREFERENCES]"; const char* PREFERENCES_TAG = "[PREFERENCES]";
const char *nvs_errors[] = {"OTHER", "NOT_INITIALIZED", "NOT_FOUND", "TYPE_MISMATCH", "READ_ONLY", "NOT_ENOUGH_SPACE", "INVALID_NAME", const char* nvs_errors[] = {"OTHER", "NOT_INITIALIZED", "NOT_FOUND", "TYPE_MISMATCH", "READ_ONLY", "NOT_ENOUGH_SPACE", "INVALID_NAME",
"INVALID_HANDLE", "REMOVE_FAILED", "KEY_TOO_LONG", "PAGE_FULL", "INVALID_STATE", "INVALID_LENGTH"}; "INVALID_HANDLE", "REMOVE_FAILED", "KEY_TOO_LONG", "PAGE_FULL", "INVALID_STATE", "INVALID_LENGTH"};
#define nvs_error(e) (((e) > ESP_ERR_NVS_BASE) ? nvs_errors[(e) & ~(ESP_ERR_NVS_BASE)] : nvs_errors[0]) #define nvs_error(e) (((e) > ESP_ERR_NVS_BASE) ? nvs_errors[(e) & ~(ESP_ERR_NVS_BASE)] : nvs_errors[0])
Preferences::Preferences() : _handle(0), _started(false), _readOnly(false) {} Preferences::Preferences() : _handle(0), _started(false), _readOnly(false) {}
bool Preferences::begin(const char *name, bool readOnly, const char *partition_label) bool Preferences::begin(const char* name, bool readOnly, const char* partition_label)
{ {
if (_started) if (_started)
{ {
@@ -84,7 +84,7 @@ bool Preferences::clear()
* Remove a key * Remove a key
* */ * */
bool Preferences::remove(const char *key) bool Preferences::remove(const char* key)
{ {
if (!_started || !key || _readOnly) if (!_started || !key || _readOnly)
{ {
@@ -110,7 +110,7 @@ bool Preferences::remove(const char *key)
* Put a key value * Put a key value
* */ * */
size_t Preferences::putChar(const char *key, int8_t value) size_t Preferences::putChar(const char* key, int8_t value)
{ {
if (!_started || !key || _readOnly) if (!_started || !key || _readOnly)
{ {
@@ -131,7 +131,7 @@ size_t Preferences::putChar(const char *key, int8_t value)
return 1; return 1;
} }
size_t Preferences::putUChar(const char *key, uint8_t value) size_t Preferences::putUChar(const char* key, uint8_t value)
{ {
if (!_started || !key || _readOnly) if (!_started || !key || _readOnly)
{ {
@@ -152,7 +152,7 @@ size_t Preferences::putUChar(const char *key, uint8_t value)
return 1; return 1;
} }
size_t Preferences::putShort(const char *key, int16_t value) size_t Preferences::putShort(const char* key, int16_t value)
{ {
if (!_started || !key || _readOnly) if (!_started || !key || _readOnly)
{ {
@@ -173,7 +173,7 @@ size_t Preferences::putShort(const char *key, int16_t value)
return 2; return 2;
} }
size_t Preferences::putUShort(const char *key, uint16_t value) size_t Preferences::putUShort(const char* key, uint16_t value)
{ {
if (!_started || !key || _readOnly) if (!_started || !key || _readOnly)
{ {
@@ -194,7 +194,7 @@ size_t Preferences::putUShort(const char *key, uint16_t value)
return 2; return 2;
} }
size_t Preferences::putInt(const char *key, int32_t value) size_t Preferences::putInt(const char* key, int32_t value)
{ {
if (!_started || !key || _readOnly) if (!_started || !key || _readOnly)
{ {
@@ -215,7 +215,7 @@ size_t Preferences::putInt(const char *key, int32_t value)
return 4; return 4;
} }
size_t Preferences::putUInt(const char *key, uint32_t value) size_t Preferences::putUInt(const char* key, uint32_t value)
{ {
if (!_started || !key || _readOnly) if (!_started || !key || _readOnly)
{ {
@@ -236,17 +236,17 @@ size_t Preferences::putUInt(const char *key, uint32_t value)
return 4; return 4;
} }
size_t Preferences::putLong(const char *key, int32_t value) size_t Preferences::putLong(const char* key, int32_t value)
{ {
return putInt(key, value); return putInt(key, value);
} }
size_t Preferences::putULong(const char *key, uint32_t value) size_t Preferences::putULong(const char* key, uint32_t value)
{ {
return putUInt(key, value); return putUInt(key, value);
} }
size_t Preferences::putLong64(const char *key, int64_t value) size_t Preferences::putLong64(const char* key, int64_t value)
{ {
if (!_started || !key || _readOnly) if (!_started || !key || _readOnly)
{ {
@@ -267,7 +267,7 @@ size_t Preferences::putLong64(const char *key, int64_t value)
return 8; return 8;
} }
size_t Preferences::putULong64(const char *key, uint64_t value) size_t Preferences::putULong64(const char* key, uint64_t value)
{ {
if (!_started || !key || _readOnly) if (!_started || !key || _readOnly)
{ {
@@ -288,22 +288,22 @@ size_t Preferences::putULong64(const char *key, uint64_t value)
return 8; return 8;
} }
size_t Preferences::putFloat(const char *key, const float_t value) size_t Preferences::putFloat(const char* key, const float_t value)
{ {
return putBytes(key, (void *)&value, sizeof(float_t)); return putBytes(key, (void*)&value, sizeof(float_t));
} }
size_t Preferences::putDouble(const char *key, const double_t value) size_t Preferences::putDouble(const char* key, const double_t value)
{ {
return putBytes(key, (void *)&value, sizeof(double_t)); return putBytes(key, (void*)&value, sizeof(double_t));
} }
size_t Preferences::putBool(const char *key, const bool value) size_t Preferences::putBool(const char* key, const bool value)
{ {
return putUChar(key, (uint8_t)(value ? 1 : 0)); return putUChar(key, (uint8_t)(value ? 1 : 0));
} }
size_t Preferences::putString(const char *key, const char *value) size_t Preferences::putString(const char* key, const char* value)
{ {
if (!_started || !key || !value || _readOnly) if (!_started || !key || !value || _readOnly)
{ {
@@ -324,12 +324,12 @@ size_t Preferences::putString(const char *key, const char *value)
return strlen(value); return strlen(value);
} }
size_t Preferences::putString(const char *key, const std::string value) size_t Preferences::putString(const char* key, const std::string value)
{ {
return putString(key, value.c_str()); return putString(key, value.c_str());
} }
size_t Preferences::putBytes(const char *key, const void *value, size_t len) size_t Preferences::putBytes(const char* key, const void* value, size_t len)
{ {
if (!_started || !key || !value || !len || _readOnly) if (!_started || !key || !value || !len || _readOnly)
{ {
@@ -350,7 +350,7 @@ size_t Preferences::putBytes(const char *key, const void *value, size_t len)
return len; return len;
} }
PreferenceType Preferences::getType(const char *key) PreferenceType Preferences::getType(const char* key)
{ {
if (!_started || !key || strlen(key) > 15) if (!_started || !key || strlen(key) > 15)
{ {
@@ -408,7 +408,7 @@ PreferenceType Preferences::getType(const char *key)
return PT_INVALID; return PT_INVALID;
} }
bool Preferences::isKey(const char *key) bool Preferences::isKey(const char* key)
{ {
return getType(key) != PT_INVALID; return getType(key) != PT_INVALID;
} }
@@ -417,7 +417,7 @@ bool Preferences::isKey(const char *key)
* Get a key value * Get a key value
* */ * */
int8_t Preferences::getChar(const char *key, const int8_t defaultValue) int8_t Preferences::getChar(const char* key, const int8_t defaultValue)
{ {
int8_t value = defaultValue; int8_t value = defaultValue;
if (!_started || !key) if (!_started || !key)
@@ -432,7 +432,7 @@ int8_t Preferences::getChar(const char *key, const int8_t defaultValue)
return value; return value;
} }
uint8_t Preferences::getUChar(const char *key, const uint8_t defaultValue) uint8_t Preferences::getUChar(const char* key, const uint8_t defaultValue)
{ {
uint8_t value = defaultValue; uint8_t value = defaultValue;
if (!_started || !key) if (!_started || !key)
@@ -447,7 +447,7 @@ uint8_t Preferences::getUChar(const char *key, const uint8_t defaultValue)
return value; return value;
} }
int16_t Preferences::getShort(const char *key, const int16_t defaultValue) int16_t Preferences::getShort(const char* key, const int16_t defaultValue)
{ {
int16_t value = defaultValue; int16_t value = defaultValue;
if (!_started || !key) if (!_started || !key)
@@ -462,7 +462,7 @@ int16_t Preferences::getShort(const char *key, const int16_t defaultValue)
return value; return value;
} }
uint16_t Preferences::getUShort(const char *key, const uint16_t defaultValue) uint16_t Preferences::getUShort(const char* key, const uint16_t defaultValue)
{ {
uint16_t value = defaultValue; uint16_t value = defaultValue;
if (!_started || !key) if (!_started || !key)
@@ -477,7 +477,7 @@ uint16_t Preferences::getUShort(const char *key, const uint16_t defaultValue)
return value; return value;
} }
int32_t Preferences::getInt(const char *key, const int32_t defaultValue) int32_t Preferences::getInt(const char* key, const int32_t defaultValue)
{ {
int32_t value = defaultValue; int32_t value = defaultValue;
if (!_started || !key) if (!_started || !key)
@@ -492,7 +492,7 @@ int32_t Preferences::getInt(const char *key, const int32_t defaultValue)
return value; return value;
} }
uint32_t Preferences::getUInt(const char *key, const uint32_t defaultValue) uint32_t Preferences::getUInt(const char* key, const uint32_t defaultValue)
{ {
uint32_t value = defaultValue; uint32_t value = defaultValue;
if (!_started || !key) if (!_started || !key)
@@ -507,17 +507,17 @@ uint32_t Preferences::getUInt(const char *key, const uint32_t defaultValue)
return value; return value;
} }
int32_t Preferences::getLong(const char *key, const int32_t defaultValue) int32_t Preferences::getLong(const char* key, const int32_t defaultValue)
{ {
return getInt(key, defaultValue); return getInt(key, defaultValue);
} }
uint32_t Preferences::getULong(const char *key, const uint32_t defaultValue) uint32_t Preferences::getULong(const char* key, const uint32_t defaultValue)
{ {
return getUInt(key, defaultValue); return getUInt(key, defaultValue);
} }
int64_t Preferences::getLong64(const char *key, const int64_t defaultValue) int64_t Preferences::getLong64(const char* key, const int64_t defaultValue)
{ {
int64_t value = defaultValue; int64_t value = defaultValue;
if (!_started || !key) if (!_started || !key)
@@ -532,7 +532,7 @@ int64_t Preferences::getLong64(const char *key, const int64_t defaultValue)
return value; return value;
} }
uint64_t Preferences::getULong64(const char *key, const uint64_t defaultValue) uint64_t Preferences::getULong64(const char* key, const uint64_t defaultValue)
{ {
uint64_t value = defaultValue; uint64_t value = defaultValue;
if (!_started || !key) if (!_started || !key)
@@ -547,26 +547,26 @@ uint64_t Preferences::getULong64(const char *key, const uint64_t defaultValue)
return value; return value;
} }
float_t Preferences::getFloat(const char *key, const float_t defaultValue) float_t Preferences::getFloat(const char* key, const float_t defaultValue)
{ {
float_t value = defaultValue; float_t value = defaultValue;
getBytes(key, (void *)&value, sizeof(float_t)); getBytes(key, (void*)&value, sizeof(float_t));
return value; return value;
} }
double_t Preferences::getDouble(const char *key, const double_t defaultValue) double_t Preferences::getDouble(const char* key, const double_t defaultValue)
{ {
double_t value = defaultValue; double_t value = defaultValue;
getBytes(key, (void *)&value, sizeof(double_t)); getBytes(key, (void*)&value, sizeof(double_t));
return value; return value;
} }
bool Preferences::getBool(const char *key, const bool defaultValue) bool Preferences::getBool(const char* key, const bool defaultValue)
{ {
return getUChar(key, defaultValue ? 1 : 0) == 1; return getUChar(key, defaultValue ? 1 : 0) == 1;
} }
size_t Preferences::getString(const char *key, char *value, const size_t maxLen) size_t Preferences::getString(const char* key, char* value, const size_t maxLen)
{ {
size_t len = 0; size_t len = 0;
if (!_started || !key || !value || !maxLen) if (!_started || !key || !value || !maxLen)
@@ -593,9 +593,9 @@ size_t Preferences::getString(const char *key, char *value, const size_t maxLen)
return len; return len;
} }
std::string Preferences::getString(const char *key, const std::string defaultValue) std::string Preferences::getString(const char* key, const std::string defaultValue)
{ {
char *value = NULL; char* value = NULL;
size_t len = 0; size_t len = 0;
if (!_started || !key) if (!_started || !key)
{ {
@@ -618,7 +618,7 @@ std::string Preferences::getString(const char *key, const std::string defaultVal
return std::string(buf); return std::string(buf);
} }
size_t Preferences::getBytesLength(const char *key) size_t Preferences::getBytesLength(const char* key)
{ {
size_t len = 0; size_t len = 0;
if (!_started || !key) if (!_started || !key)
@@ -634,7 +634,7 @@ size_t Preferences::getBytesLength(const char *key)
return len; return len;
} }
size_t Preferences::getBytes(const char *key, void *buf, size_t maxLen) size_t Preferences::getBytes(const char* key, void* buf, size_t maxLen)
{ {
size_t len = getBytesLength(key); size_t len = getBytesLength(key);
if (!len || !buf || !maxLen) if (!len || !buf || !maxLen)

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
{ {
@@ -30,57 +30,57 @@ typedef enum
class Preferences class Preferences
{ {
protected: protected:
uint32_t _handle; uint32_t _handle;
bool _started; bool _started;
bool _readOnly; bool _readOnly;
public: public:
Preferences(); Preferences();
~Preferences(); ~Preferences();
bool begin(const char *name, bool readOnly = false, const char *partition_label = nullptr); bool begin(const char* name, bool readOnly = false, const char* partition_label = nullptr);
void end(); void end();
bool clear(); bool clear();
bool remove(const char *key); bool remove(const char* key);
size_t putChar(const char *key, int8_t value); size_t putChar(const char* key, int8_t value);
size_t putUChar(const char *key, uint8_t value); size_t putUChar(const char* key, uint8_t value);
size_t putShort(const char *key, int16_t value); size_t putShort(const char* key, int16_t value);
size_t putUShort(const char *key, uint16_t value); size_t putUShort(const char* key, uint16_t value);
size_t putInt(const char *key, int32_t value); size_t putInt(const char* key, int32_t value);
size_t putUInt(const char *key, uint32_t value); size_t putUInt(const char* key, uint32_t value);
size_t putLong(const char *key, int32_t value); size_t putLong(const char* key, int32_t value);
size_t putULong(const char *key, uint32_t value); size_t putULong(const char* key, uint32_t value);
size_t putLong64(const char *key, int64_t value); size_t putLong64(const char* key, int64_t value);
size_t putULong64(const char *key, uint64_t value); size_t putULong64(const char* key, uint64_t value);
size_t putFloat(const char *key, float_t value); size_t putFloat(const char* key, float_t value);
size_t putDouble(const char *key, double_t value); size_t putDouble(const char* key, double_t value);
size_t putBool(const char *key, bool value); size_t putBool(const char* key, bool value);
size_t putString(const char *key, const char *value); size_t putString(const char* key, const char* value);
size_t putString(const char *key, std::string value); size_t putString(const char* key, std::string value);
size_t putBytes(const char *key, const void *value, size_t len); size_t putBytes(const char* key, const void* value, size_t len);
bool isKey(const char *key); bool isKey(const char* key);
PreferenceType getType(const char *key); PreferenceType getType(const char* key);
int8_t getChar(const char *key, int8_t defaultValue = 0); int8_t getChar(const char* key, int8_t defaultValue = 0);
uint8_t getUChar(const char *key, uint8_t defaultValue = 0); uint8_t getUChar(const char* key, uint8_t defaultValue = 0);
int16_t getShort(const char *key, int16_t defaultValue = 0); int16_t getShort(const char* key, int16_t defaultValue = 0);
uint16_t getUShort(const char *key, uint16_t defaultValue = 0); uint16_t getUShort(const char* key, uint16_t defaultValue = 0);
int32_t getInt(const char *key, int32_t defaultValue = 0); int32_t getInt(const char* key, int32_t defaultValue = 0);
uint32_t getUInt(const char *key, uint32_t defaultValue = 0); uint32_t getUInt(const char* key, uint32_t defaultValue = 0);
int32_t getLong(const char *key, int32_t defaultValue = 0); int32_t getLong(const char* key, int32_t defaultValue = 0);
uint32_t getULong(const char *key, uint32_t defaultValue = 0); uint32_t getULong(const char* key, uint32_t defaultValue = 0);
int64_t getLong64(const char *key, int64_t defaultValue = 0); int64_t getLong64(const char* key, int64_t defaultValue = 0);
uint64_t getULong64(const char *key, uint64_t defaultValue = 0); uint64_t getULong64(const char* key, uint64_t defaultValue = 0);
float_t getFloat(const char *key, float_t defaultValue = NAN); float_t getFloat(const char* key, float_t defaultValue = NAN);
double_t getDouble(const char *key, double_t defaultValue = NAN); double_t getDouble(const char* key, double_t defaultValue = NAN);
bool getBool(const char *key, bool defaultValue = false); bool getBool(const char* key, bool defaultValue = false);
size_t getString(const char *key, char *value, size_t maxLen); size_t getString(const char* key, char* value, size_t maxLen);
std::string getString(const char *key, std::string defaultValue = std::string()); std::string getString(const char* key, std::string defaultValue = std::string());
size_t getBytesLength(const char *key); size_t getBytesLength(const char* key);
size_t getBytes(const char *key, void *buf, size_t maxLen); size_t getBytes(const char* key, void* buf, size_t maxLen);
size_t freeEntries(); size_t freeEntries();
}; };

View File

@@ -2,23 +2,23 @@
#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
{ {
BaseConfigModel(Preferences *pref) : pref(pref) {} BaseConfigModel(Preferences* pref) : pref(pref) {}
void load(); void load();
void save(); void save();
std::string toRepresentation(); std::string toRepresentation();
Preferences *pref; Preferences* pref;
}; };
enum class StreamingMode enum class StreamingMode
@@ -31,7 +31,7 @@ enum class StreamingMode
struct DeviceMode_t : BaseConfigModel struct DeviceMode_t : BaseConfigModel
{ {
StreamingMode mode; StreamingMode mode;
explicit DeviceMode_t(Preferences *pref) : BaseConfigModel(pref), mode(StreamingMode::SETUP) {} explicit DeviceMode_t(Preferences* pref) : BaseConfigModel(pref), mode(StreamingMode::SETUP) {}
void load() void load()
{ {
@@ -59,7 +59,7 @@ struct DeviceMode_t : BaseConfigModel
struct DeviceConfig_t : BaseConfigModel struct DeviceConfig_t : BaseConfigModel
{ {
DeviceConfig_t(Preferences *pref) : BaseConfigModel(pref) {} DeviceConfig_t(Preferences* pref) : BaseConfigModel(pref) {}
std::string OTALogin; std::string OTALogin;
std::string OTAPassword; std::string OTAPassword;
@@ -97,7 +97,7 @@ struct DeviceConfig_t : BaseConfigModel
struct MDNSConfig_t : BaseConfigModel struct MDNSConfig_t : BaseConfigModel
{ {
MDNSConfig_t(Preferences *pref) : BaseConfigModel(pref) {} MDNSConfig_t(Preferences* pref) : BaseConfigModel(pref) {}
std::string hostname; std::string hostname;
@@ -120,15 +120,13 @@ 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());
}; };
}; };
struct CameraConfig_t : BaseConfigModel struct CameraConfig_t : BaseConfigModel
{ {
CameraConfig_t(Preferences *pref) : BaseConfigModel(pref) {} CameraConfig_t(Preferences* pref) : BaseConfigModel(pref) {}
uint8_t vflip; uint8_t vflip;
uint8_t href; uint8_t href;
@@ -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);
}; };
}; };
@@ -171,23 +168,12 @@ struct CameraConfig_t : BaseConfigModel
struct WiFiConfig_t : BaseConfigModel 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,22 +208,19 @@ 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);
}; };
}; };
struct AP_WiFiConfig_t : BaseConfigModel struct AP_WiFiConfig_t : BaseConfigModel
{ {
AP_WiFiConfig_t(Preferences *pref) : BaseConfigModel(pref) {} AP_WiFiConfig_t(Preferences* pref) : BaseConfigModel(pref) {}
std::string ssid; std::string ssid;
std::string password; std::string password;
@@ -268,7 +250,7 @@ struct AP_WiFiConfig_t : BaseConfigModel
struct WiFiTxPower_t : BaseConfigModel struct WiFiTxPower_t : BaseConfigModel
{ {
WiFiTxPower_t(Preferences *pref) : BaseConfigModel(pref) {} WiFiTxPower_t(Preferences* pref) : BaseConfigModel(pref) {}
uint8_t power; uint8_t power;
@@ -290,7 +272,7 @@ struct WiFiTxPower_t : BaseConfigModel
class TrackerConfig_t class TrackerConfig_t
{ {
public: public:
DeviceConfig_t device; DeviceConfig_t device;
DeviceMode_t device_mode; DeviceMode_t device_mode;
CameraConfig_t camera; CameraConfig_t camera;
@@ -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

@@ -2,25 +2,23 @@
static auto CONFIGURATION_TAG = "[CONFIGURATION]"; 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, const int count) 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);
@@ -111,18 +107,14 @@ void ProjectConfig::setLEDDUtyCycleConfig(int led_external_pwm_duty_cycle)
this->config.device.save(); this->config.device.save();
} }
void ProjectConfig::setMDNSConfig(const std::string &hostname) void ProjectConfig::setMDNSConfig(const std::string& hostname)
{ {
ESP_LOGD(CONFIGURATION_TAG, "Updating MDNS config"); ESP_LOGD(CONFIGURATION_TAG, "Updating MDNS config");
this->config.mdns.hostname.assign(hostname); this->config.mdns.hostname.assign(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()));
@@ -194,16 +176,14 @@ void ProjectConfig::setWifiConfig(const std::string &networkName,
} }
} }
void ProjectConfig::deleteWifiConfig(const std::string &networkName) void ProjectConfig::deleteWifiConfig(const std::string& networkName)
{ {
if (const auto size = this->config.networks.size(); size == 0) if (const auto size = this->config.networks.size(); size == 0)
{ {
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);
@@ -243,36 +221,36 @@ void ProjectConfig::setDeviceMode(const StreamingMode deviceMode)
//* //*
//********************************************************************************************************************** //**********************************************************************************************************************
DeviceConfig_t &ProjectConfig::getDeviceConfig() DeviceConfig_t& ProjectConfig::getDeviceConfig()
{ {
return this->config.device; return this->config.device;
} }
CameraConfig_t &ProjectConfig::getCameraConfig() CameraConfig_t& ProjectConfig::getCameraConfig()
{ {
return this->config.camera; return this->config.camera;
} }
std::vector<WiFiConfig_t> &ProjectConfig::getWifiConfigs() std::vector<WiFiConfig_t>& ProjectConfig::getWifiConfigs()
{ {
return this->config.networks; return this->config.networks;
} }
AP_WiFiConfig_t &ProjectConfig::getAPWifiConfig() AP_WiFiConfig_t& ProjectConfig::getAPWifiConfig()
{ {
return this->config.ap_network; return this->config.ap_network;
} }
MDNSConfig_t &ProjectConfig::getMDNSConfig() MDNSConfig_t& ProjectConfig::getMDNSConfig()
{ {
return this->config.mdns; return this->config.mdns;
} }
WiFiTxPower_t &ProjectConfig::getWiFiTxPowerConfig() WiFiTxPower_t& ProjectConfig::getWiFiTxPowerConfig()
{ {
return this->config.txpower; return this->config.txpower;
} }
TrackerConfig_t &ProjectConfig::getTrackerConfig() TrackerConfig_t& ProjectConfig::getTrackerConfig()
{ {
return this->config; return this->config;
} }
DeviceMode_t &ProjectConfig::getDeviceModeConfig() DeviceMode_t& ProjectConfig::getDeviceModeConfig()
{ {
return this->config.device_mode; return this->config.device_mode;
} }

View File

@@ -1,22 +1,22 @@
#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);
void saveNetworkCount(Preferences *pref, int count); void saveNetworkCount(Preferences* pref, int count);
class ProjectConfig class ProjectConfig
{ {
public: public:
explicit ProjectConfig(Preferences *pref); explicit ProjectConfig(Preferences* pref);
virtual ~ProjectConfig(); virtual ~ProjectConfig();
void load(); void load();
@@ -24,42 +24,30 @@ public:
bool reset(); bool reset();
DeviceConfig_t &getDeviceConfig(); DeviceConfig_t& getDeviceConfig();
DeviceMode_t &getDeviceModeConfig(); DeviceMode_t& getDeviceModeConfig();
CameraConfig_t &getCameraConfig(); CameraConfig_t& getCameraConfig();
std::vector<WiFiConfig_t> &getWifiConfigs(); std::vector<WiFiConfig_t>& getWifiConfigs();
AP_WiFiConfig_t &getAPWifiConfig(); AP_WiFiConfig_t& getAPWifiConfig();
MDNSConfig_t &getMDNSConfig(); MDNSConfig_t& getMDNSConfig();
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();
private: private:
Preferences *pref; Preferences* pref;
bool _already_loaded; bool _already_loaded;
TrackerConfig_t config; TrackerConfig_t config;
}; };

View File

@@ -7,7 +7,7 @@
#define GET_METHOD "GET" #define GET_METHOD "GET"
#define DELETE_METHOD "DELETE" #define DELETE_METHOD "DELETE"
bool getIsSuccess(const nlohmann::json &response) bool getIsSuccess(const nlohmann::json& response)
{ {
// since the commandManager will be returning CommandManagerResponse to simplify parsing on the clients end // since the commandManager will be returning CommandManagerResponse to simplify parsing on the clients end
// we can slightly its json representation, and extract the status from there // we can slightly its json representation, and extract the status from there
@@ -82,11 +82,11 @@ void RestAPI::begin()
mg_http_listen(&mgr, this->url.c_str(), (mg_event_handler_t)RestAPIHelpers::event_handler, this); mg_http_listen(&mgr, this->url.c_str(), (mg_event_handler_t)RestAPIHelpers::event_handler, this);
} }
void RestAPI::handle_request(struct mg_connection *connection, int event, void *event_data) void RestAPI::handle_request(struct mg_connection* connection, int event, void* event_data)
{ {
if (event == MG_EV_HTTP_MSG) if (event == MG_EV_HTTP_MSG)
{ {
auto const *message = static_cast<struct mg_http_message *>(event_data); auto const* message = static_cast<struct mg_http_message*>(event_data);
auto const uri = std::string(message->uri.buf, message->uri.len); auto const uri = std::string(message->uri.buf, message->uri.len);
if (this->routes.find(uri) == this->routes.end()) if (this->routes.find(uri) == this->routes.end())
@@ -97,22 +97,19 @@ void RestAPI::handle_request(struct mg_connection *connection, int event, void *
auto const base_request_params = this->routes.at(uri); auto const base_request_params = this->routes.at(uri);
auto *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),
}; };
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);
} }
} }
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)
{ {
auto *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);
} }
@@ -121,9 +118,9 @@ void RestAPI::poll()
mg_mgr_poll(&mgr, 100); mg_mgr_poll(&mgr, 100);
} }
void HandleRestAPIPollTask(void *pvParameter) void HandleRestAPIPollTask(void* pvParameter)
{ {
auto *rest_api_handler = static_cast<RestAPI *>(pvParameter); auto* rest_api_handler = static_cast<RestAPI*>(pvParameter);
while (true) while (true)
{ {
rest_api_handler->poll(); rest_api_handler->poll();
@@ -131,9 +128,8 @@ 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"
@@ -13,7 +13,7 @@
struct RequestContext struct RequestContext
{ {
mg_connection *connection; mg_connection* connection;
std::string method; std::string method;
std::string body; std::string body;
}; };
@@ -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
@@ -36,22 +37,22 @@ class RestAPI
mg_mgr mgr; mg_mgr mgr;
std::shared_ptr<CommandManager> command_manager; std::shared_ptr<CommandManager> command_manager;
private: private:
void handle_endpoint_command(RequestContext *context, std::string allowed_method, CommandType command_type, int success_code, int error_code); void handle_endpoint_command(RequestContext* context, std::string allowed_method, CommandType command_type, int success_code, int error_code);
public: public:
// this will also need command manager // this will also need command manager
RestAPI(std::string url, std::shared_ptr<CommandManager> command_manager); RestAPI(std::string url, std::shared_ptr<CommandManager> command_manager);
void begin(); void begin();
void handle_request(struct mg_connection *connection, int event, void *event_data); void handle_request(struct mg_connection* connection, int event, void* event_data);
void poll(); void poll();
}; };
namespace RestAPIHelpers namespace RestAPIHelpers
{ {
void event_handler(struct mg_connection *connection, int event, void *event_data); void event_handler(struct mg_connection* connection, int event, void* event_data);
}; };
void HandleRestAPIPollTask(void *pvParameter); void HandleRestAPIPollTask(void* pvParameter);
#endif #endif

View File

@@ -2,11 +2,11 @@
#include "esp_log.h" #include "esp_log.h"
#include "main_globals.hpp" #include "main_globals.hpp"
SerialManager::SerialManager(std::shared_ptr<CommandManager> commandManager, esp_timer_handle_t *timerHandle) SerialManager::SerialManager(std::shared_ptr<CommandManager> commandManager, esp_timer_handle_t* timerHandle)
: commandManager(commandManager), timerHandle(timerHandle) : commandManager(commandManager), timerHandle(timerHandle)
{ {
this->data = static_cast<uint8_t *>(malloc(BUF_SIZE)); this->data = static_cast<uint8_t*>(malloc(BUF_SIZE));
this->temp_data = static_cast<uint8_t *>(malloc(256)); this->temp_data = static_cast<uint8_t*>(malloc(256));
} }
// Function to notify that a command was received during startup // Function to notify that a command was received during startup
@@ -25,9 +25,9 @@ void SerialManager::notify_startup_command_received()
} }
// we can cancel this task once we're in cdc // we can cancel this task once we're in cdc
void HandleSerialManagerTask(void *pvParameters) void HandleSerialManagerTask(void* pvParameters)
{ {
auto const serialManager = static_cast<SerialManager *>(pvParameters); auto const serialManager = static_cast<SerialManager*>(pvParameters);
while (true) while (true)
{ {
serialManager->try_receive(); serialManager->try_receive();

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)
@@ -33,20 +33,20 @@ struct cdc_command_packet_t
class SerialManager class SerialManager
{ {
public: public:
explicit SerialManager(std::shared_ptr<CommandManager> commandManager, esp_timer_handle_t *timerHandle); explicit SerialManager(std::shared_ptr<CommandManager> commandManager, esp_timer_handle_t* timerHandle);
void setup(); void setup();
void try_receive(); void try_receive();
void notify_startup_command_received(); void notify_startup_command_received();
void shutdown(); void shutdown();
private: private:
std::shared_ptr<CommandManager> commandManager; std::shared_ptr<CommandManager> commandManager;
esp_timer_handle_t *timerHandle; esp_timer_handle_t* timerHandle;
uint8_t *data; uint8_t* data;
uint8_t *temp_data; uint8_t* temp_data;
}; };
void HandleSerialManagerTask(void *pvParameters); void HandleSerialManagerTask(void* pvParameters);
void HandleCDCSerialManagerTask(void *pvParameters); void HandleCDCSerialManagerTask(void* pvParameters);
#endif #endif

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);
@@ -36,7 +32,7 @@ void SerialManager::setup()
} }
} }
void uart_write_bytes_chunked(uart_port_t uart_num, const void *src, size_t size) void uart_write_bytes_chunked(uart_port_t uart_num, const void* src, size_t size)
{ {
while (size > 0) while (size > 0)
{ {
@@ -77,7 +73,7 @@ void SerialManager::try_receive()
data[current_position] = '\0'; data[current_position] = '\0';
current_position = 0; current_position = 0;
const nlohmann::json result = this->commandManager->executeFromJson(std::string_view(reinterpret_cast<const char *>(this->data))); const nlohmann::json result = this->commandManager->executeFromJson(std::string_view(reinterpret_cast<const char*>(this->data)));
const auto resultMessage = result.dump(); const auto resultMessage = result.dump();
// todo check if this works // todo check if this works
// uart_write_bytes_chunked(uart_num, resultMessage.c_str(), resultMessage.length())s // uart_write_bytes_chunked(uart_num, resultMessage.c_str(), resultMessage.length())s

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"
@@ -16,7 +16,7 @@ void SerialManager::setup()
#endif #endif
} }
void usb_serial_jtag_write_bytes_chunked(const char *data, size_t len, size_t timeout) void usb_serial_jtag_write_bytes_chunked(const char* data, size_t len, size_t timeout)
{ {
#ifndef CONFIG_USE_UART_FOR_COMMUNICATION #ifndef CONFIG_USE_UART_FOR_COMMUNICATION
while (len > 0) while (len > 0)
@@ -59,7 +59,7 @@ void SerialManager::try_receive()
data[current_position] = '\0'; data[current_position] = '\0';
current_position = 0; current_position = 0;
const nlohmann::json result = this->commandManager->executeFromJson(std::string_view(reinterpret_cast<const char *>(this->data))); const nlohmann::json result = this->commandManager->executeFromJson(std::string_view(reinterpret_cast<const char*>(this->data)));
const auto resultMessage = result.dump(); const auto resultMessage = result.dump();
usb_serial_jtag_write_bytes_chunked(resultMessage.c_str(), resultMessage.length(), 1000 / 20); usb_serial_jtag_write_bytes_chunked(resultMessage.c_str(), resultMessage.length(), 1000 / 20);
} }
@@ -80,10 +80,10 @@ void SerialManager::shutdown()
} }
} }
void HandleCDCSerialManagerTask(void *pvParameters) void HandleCDCSerialManagerTask(void* pvParameters)
{ {
#ifndef CONFIG_USE_UART_FOR_COMMUNICATION #ifndef CONFIG_USE_UART_FOR_COMMUNICATION
auto const commandManager = static_cast<CommandManager *>(pvParameters); auto const commandManager = static_cast<CommandManager*>(pvParameters);
static char buffer[BUF_SIZE]; static char buffer[BUF_SIZE];
auto idx = 0; auto idx = 0;
@@ -100,7 +100,7 @@ void HandleCDCSerialManagerTask(void *pvParameters)
if (idx >= BUF_SIZE || buffer[idx - 1] == '\n' || buffer[idx - 1] == '\r') if (idx >= BUF_SIZE || buffer[idx - 1] == '\n' || buffer[idx - 1] == '\r')
{ {
buffer[idx - 1] = '\0'; buffer[idx - 1] = '\0';
const nlohmann::json result = commandManager->executeFromJson(std::string_view(reinterpret_cast<const char *>(buffer))); const nlohmann::json result = commandManager->executeFromJson(std::string_view(reinterpret_cast<const char*>(buffer)));
const auto resultMessage = result.dump(); const auto resultMessage = result.dump();
tud_cdc_write(resultMessage.c_str(), resultMessage.length()); tud_cdc_write(resultMessage.c_str(), resultMessage.length());
tud_cdc_write_flush(); tud_cdc_write_flush();
@@ -143,10 +143,9 @@ extern "C" void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts)
ESP_LOGI("[SERIAL]", "CDC line state changed: DTR=%d, RTS=%d", dtr, rts); ESP_LOGI("[SERIAL]", "CDC line state changed: DTR=%d, RTS=%d", dtr, 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);
@@ -92,9 +91,9 @@ QueueHandle_t StateManager::GetEventQueue() const
return this->eventQueue; return this->eventQueue;
} }
void HandleStateManagerTask(void *pvParameters) void HandleStateManagerTask(void* pvParameters)
{ {
auto *stateManager = static_cast<StateManager *>(pvParameters); auto* stateManager = static_cast<StateManager*>(pvParameters);
while (true) while (true)
{ {

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)
}; };
@@ -71,14 +71,14 @@ struct SystemEvent
class StateManager class StateManager
{ {
public: public:
StateManager(QueueHandle_t eventQueue, QueueHandle_t ledStateQueue); StateManager(QueueHandle_t eventQueue, QueueHandle_t ledStateQueue);
void HandleUpdateState(); void HandleUpdateState();
WiFiState_e GetWifiState(); WiFiState_e GetWifiState();
CameraState_e GetCameraState(); CameraState_e GetCameraState();
QueueHandle_t GetEventQueue() const; QueueHandle_t GetEventQueue() const;
private: private:
QueueHandle_t eventQueue; QueueHandle_t eventQueue;
QueueHandle_t ledStateQueue; QueueHandle_t ledStateQueue;
@@ -97,6 +97,6 @@ static inline bool SendStreamEvent(QueueHandle_t queue, StreamState_e state)
return xQueueSend(queue, &evt, 0) == pdTRUE; return xQueueSend(queue, &evt, 0) == pdTRUE;
} }
void HandleStateManagerTask(void *pvParameters); void HandleStateManagerTask(void* pvParameters);
#endif // STATEMANAGER_HPP #endif // STATEMANAGER_HPP

View File

@@ -1,32 +1,30 @@
#include "StreamServer.hpp" #include "StreamServer.hpp"
constexpr static const char *STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY; constexpr static const char* STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY;
constexpr static const char *STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n"; constexpr static const char* STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
constexpr static const char *STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\nX-Timestamp: %lli.%06li\r\n\r\n"; constexpr static const char* STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\nX-Timestamp: %lli.%06li\r\n\r\n";
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)
{ {
} camera_fb_t* fb = nullptr;
esp_err_t StreamHelpers::stream(httpd_req_t *req)
{
camera_fb_t *fb = nullptr;
struct timeval _timestamp; struct timeval _timestamp;
esp_err_t response = ESP_OK; esp_err_t response = ESP_OK;
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)
last_frame = esp_timer_get_time(); last_frame = esp_timer_get_time();
// Pull event queue from user_ctx to send STREAM on/off notifications // Pull event queue from user_ctx to send STREAM on/off notifications
auto *stateManager = static_cast<StateManager *>(req->user_ctx); auto* stateManager = static_cast<StateManager*>(req->user_ctx);
QueueHandle_t eventQueue = stateManager ? stateManager->GetEventQueue() : nullptr; QueueHandle_t eventQueue = stateManager ? stateManager->GetEventQueue() : nullptr;
bool stream_on_sent = false; bool stream_on_sent = false;
@@ -63,11 +61,11 @@ esp_err_t StreamHelpers::stream(httpd_req_t *req)
response = httpd_resp_send_chunk(req, STREAM_BOUNDARY, strlen(STREAM_BOUNDARY)); response = httpd_resp_send_chunk(req, STREAM_BOUNDARY, strlen(STREAM_BOUNDARY));
if (response == ESP_OK) if (response == ESP_OK)
{ {
size_t hlen = snprintf((char *)part_buf, sizeof(part_buf), STREAM_PART, _jpg_buf_len, _timestamp.tv_sec, _timestamp.tv_usec); size_t hlen = snprintf((char*)part_buf, sizeof(part_buf), STREAM_PART, _jpg_buf_len, _timestamp.tv_sec, _timestamp.tv_usec);
response = httpd_resp_send_chunk(req, (const char *)part_buf, hlen); response = httpd_resp_send_chunk(req, (const char*)part_buf, hlen);
} }
if (response == ESP_OK) if (response == ESP_OK)
response = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len); response = httpd_resp_send_chunk(req, (const char*)_jpg_buf, _jpg_buf_len);
if (fb) if (fb)
{ {
esp_camera_fb_return(fb); esp_camera_fb_return(fb);
@@ -103,7 +101,7 @@ esp_err_t StreamHelpers::stream(httpd_req_t *req)
{ {
fps = (frame_window * 1000) / window_ms; fps = (frame_window * 1000) / window_ms;
} }
ESP_LOGI(STREAM_SERVER_TAG, "%i Frames Size: %uKB, Time: %lims (%lifps)",frame_window, _jpg_buf_len / 1024, window_ms, fps); ESP_LOGI(STREAM_SERVER_TAG, "%i Frames Size: %uKB, Time: %lims (%lifps)", frame_window, _jpg_buf_len / 1024, window_ms, fps);
} }
} }
} }
@@ -115,7 +113,7 @@ esp_err_t StreamHelpers::stream(httpd_req_t *req)
return response; return response;
} }
esp_err_t StreamHelpers::ws_logs_handle(httpd_req_t *req) esp_err_t StreamHelpers::ws_logs_handle(httpd_req_t* req)
{ {
auto ret = webSocketLogger.register_socket_client(req); auto ret = webSocketLogger.register_socket_client(req);
return ret; return ret;

View File

@@ -4,35 +4,35 @@
#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;
namespace StreamHelpers 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
{ {
private: private:
int STREAM_SERVER_PORT; int STREAM_SERVER_PORT;
StateManager *stateManager; StateManager* stateManager;
httpd_handle_t camera_stream = nullptr; httpd_handle_t camera_stream = nullptr;
public: public:
StreamServer(const int STREAM_PORT, StateManager *StateManager); StreamServer(const int STREAM_PORT, StateManager* StateManager);
esp_err_t startStreamServer(); esp_err_t startStreamServer();
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);
}; };
#endif #endif

View File

@@ -5,7 +5,7 @@
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
static const char *UVC_STREAM_TAG = "[UVC DEVICE]"; static const char* UVC_STREAM_TAG = "[UVC DEVICE]";
// Tracks whether a frame has been handed to TinyUSB and not yet returned. // Tracks whether a frame has been handed to TinyUSB and not yet returned.
// File scope so both get_cb and return_cb can access it safely. // File scope so both get_cb and return_cb can access it safely.
@@ -15,12 +15,12 @@ extern "C"
{ {
static char serial_number_str[13]; static char serial_number_str[13];
const char *get_uvc_device_name() const char* get_uvc_device_name()
{ {
return deviceConfig->getMDNSConfig().hostname.c_str(); return deviceConfig->getMDNSConfig().hostname.c_str();
} }
const char *get_serial_number(void) const char* get_serial_number(void)
{ {
if (serial_number_str[0] == '\0') if (serial_number_str[0] == '\0')
{ {
@@ -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;
} }
@@ -43,7 +43,7 @@ extern "C"
// single definition of shared framebuffer storage // single definition of shared framebuffer storage
UVCStreamHelpers::fb_t UVCStreamHelpers::s_fb = {}; UVCStreamHelpers::fb_t UVCStreamHelpers::s_fb = {};
static esp_err_t UVCStreamHelpers::camera_start_cb(uvc_format_t format, int width, int height, int rate, void *cb_ctx) static esp_err_t UVCStreamHelpers::camera_start_cb(uvc_format_t format, int width, int height, int rate, void* cb_ctx)
{ {
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);
@@ -72,7 +72,7 @@ static esp_err_t UVCStreamHelpers::camera_start_cb(uvc_format_t format, int widt
return ESP_OK; return ESP_OK;
} }
static void UVCStreamHelpers::camera_stop_cb(void *cb_ctx) static void UVCStreamHelpers::camera_stop_cb(void* cb_ctx)
{ {
(void)cb_ctx; (void)cb_ctx;
if (s_fb.cam_fb_p) if (s_fb.cam_fb_p)
@@ -84,9 +84,9 @@ static void UVCStreamHelpers::camera_stop_cb(void *cb_ctx)
SendStreamEvent(eventQueue, StreamState_e::Stream_OFF); SendStreamEvent(eventQueue, StreamState_e::Stream_OFF);
} }
static uvc_fb_t *UVCStreamHelpers::camera_fb_get_cb(void *cb_ctx) static uvc_fb_t* UVCStreamHelpers::camera_fb_get_cb(void* cb_ctx)
{ {
auto *mgr = static_cast<UVCStreamManager *>(cb_ctx); auto* mgr = static_cast<UVCStreamManager*>(cb_ctx);
// Guard against requesting a new frame while previous is still in flight. // Guard against requesting a new frame while previous is still in flight.
// This was causing intermittent corruption/glitches because the pointer // This was causing intermittent corruption/glitches because the pointer
@@ -114,7 +114,7 @@ static uvc_fb_t *UVCStreamHelpers::camera_fb_get_cb(void *cb_ctx)
} }
// Acquire a fresh frame only when allowed and no frame in flight // Acquire a fresh frame only when allowed and no frame in flight
camera_fb_t *cam_fb = esp_camera_fb_get(); camera_fb_t* cam_fb = esp_camera_fb_get();
if (!cam_fb) if (!cam_fb)
{ {
return nullptr; return nullptr;
@@ -152,7 +152,7 @@ static uvc_fb_t *UVCStreamHelpers::camera_fb_get_cb(void *cb_ctx)
return &s_fb.uvc_fb; return &s_fb.uvc_fb;
} }
static void UVCStreamHelpers::camera_fb_return_cb(uvc_fb_t *fb, void *cb_ctx) static void UVCStreamHelpers::camera_fb_return_cb(uvc_fb_t* fb, void* cb_ctx)
{ {
(void)cb_ctx; (void)cb_ctx;
assert(fb == &s_fb.uvc_fb); assert(fb == &s_fb.uvc_fb);
@@ -169,7 +169,7 @@ esp_err_t UVCStreamManager::setup()
ESP_LOGI(UVC_STREAM_TAG, "Setting up UVC Stream"); ESP_LOGI(UVC_STREAM_TAG, "Setting up UVC Stream");
// Allocate a fixed-size transfer buffer (compile-time constant) // Allocate a fixed-size transfer buffer (compile-time constant)
uvc_buffer_size = UVCStreamManager::UVC_MAX_FRAMESIZE_SIZE; uvc_buffer_size = UVCStreamManager::UVC_MAX_FRAMESIZE_SIZE;
uvc_buffer = static_cast<uint8_t *>(malloc(uvc_buffer_size)); uvc_buffer = static_cast<uint8_t*>(malloc(uvc_buffer_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");

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
@@ -25,8 +25,8 @@ extern "C"
{ {
#endif #endif
const char *get_uvc_device_name(); const char* get_uvc_device_name();
const char *get_serial_number(void); const char* get_serial_number(void);
#ifdef __cplusplus #ifdef __cplusplus
} }
@@ -37,32 +37,35 @@ extern QueueHandle_t eventQueue;
namespace UVCStreamHelpers namespace UVCStreamHelpers
{ {
typedef struct typedef struct
{ {
camera_fb_t *cam_fb_p; camera_fb_t* cam_fb_p;
uvc_fb_t uvc_fb; uvc_fb_t uvc_fb;
} fb_t; } fb_t;
// single storage is defined in UVCStream.cpp // single storage is defined in UVCStream.cpp
extern fb_t s_fb; extern fb_t s_fb;
static esp_err_t camera_start_cb(uvc_format_t format, int width, int height, int rate, void *cb_ctx); static esp_err_t camera_start_cb(uvc_format_t format, int width, int height, int rate, void* cb_ctx);
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
{ {
uint8_t *uvc_buffer = nullptr; uint8_t* uvc_buffer = nullptr;
uint32_t uvc_buffer_size = 0; uint32_t uvc_buffer_size = 0;
public: public:
// Compile-time buffer size; keep conservative headroom for MJPEG QVGA // Compile-time buffer size; keep conservative headroom for MJPEG QVGA
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

@@ -10,24 +10,24 @@ WebSocketLogger::WebSocketLogger()
this->ws_log_buffer[0] = '\0'; this->ws_log_buffer[0] = '\0';
} }
void LoggerHelpers::ws_async_send(void *arg) void LoggerHelpers::ws_async_send(void* arg)
{ {
char *log_buffer = webSocketLogger.get_websocket_log_buffer(); char* log_buffer = webSocketLogger.get_websocket_log_buffer();
const auto *resp_arg = static_cast<struct async_resp_arg *>(arg); const auto* resp_arg = static_cast<struct async_resp_arg*>(arg);
const auto hd = resp_arg->hd; const auto hd = resp_arg->hd;
const auto fd = resp_arg->fd; const auto fd = resp_arg->fd;
auto websocket_packet = httpd_ws_frame_t{}; auto websocket_packet = httpd_ws_frame_t{};
websocket_packet.payload = reinterpret_cast<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;
httpd_ws_send_frame_async(hd, fd, &websocket_packet); httpd_ws_send_frame_async(hd, fd, &websocket_packet);
} }
esp_err_t WebSocketLogger::log_message(const char *format, va_list args) esp_err_t WebSocketLogger::log_message(const char* format, va_list args)
{ {
vsnprintf(this->ws_log_buffer, 100, format, args); vsnprintf(this->ws_log_buffer, 100, format, args);
@@ -46,7 +46,7 @@ esp_err_t WebSocketLogger::log_message(const char *format, va_list args)
return ret; return ret;
} }
esp_err_t WebSocketLogger::register_socket_client(httpd_req_t *req) esp_err_t WebSocketLogger::register_socket_client(httpd_req_t* req)
{ {
if (connected_socket_client.fd != -1 && connected_socket_client.hd != nullptr) if (connected_socket_client.fd != -1 && connected_socket_client.hd != nullptr)
{ {
@@ -65,7 +65,7 @@ void WebSocketLogger::unregister_socket_client()
connected_socket_client.hd = nullptr; connected_socket_client.hd = nullptr;
} }
char *WebSocketLogger::get_websocket_log_buffer() char* WebSocketLogger::get_websocket_log_buffer()
{ {
return this->ws_log_buffer; return this->ws_log_buffer;
} }

View File

@@ -15,7 +15,7 @@ struct async_resp_arg
namespace LoggerHelpers namespace LoggerHelpers
{ {
void ws_async_send(void *arg); void ws_async_send(void* arg);
} }
class WebSocketLogger class WebSocketLogger
@@ -23,14 +23,14 @@ class WebSocketLogger
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();
esp_err_t log_message(const char *format, va_list args); esp_err_t log_message(const char* format, va_list args);
esp_err_t register_socket_client(httpd_req_t *req); esp_err_t register_socket_client(httpd_req_t* req);
void unregister_socket_client(); void unregister_socket_client();
bool is_client_connected(); bool is_client_connected();
char *get_websocket_log_buffer(); char* get_websocket_log_buffer();
}; };
extern WebSocketLogger webSocketLogger; extern WebSocketLogger webSocketLogger;

View File

@@ -6,10 +6,10 @@
namespace Logo namespace Logo
{ {
static const char *LOGO_TAG = "[LOGO]"; static const char* LOGO_TAG = "[LOGO]";
inline static void printASCII() inline static void printASCII()
{ {
ESP_LOGI(LOGO_TAG, " : === WELCOME === TO === : "); ESP_LOGI(LOGO_TAG, " : === WELCOME === TO === : ");
ESP_LOGI(LOGO_TAG, " <===========================================================================================================================> "); ESP_LOGI(LOGO_TAG, " <===========================================================================================================================> ");
ESP_LOGI(LOGO_TAG, " ██████╗ ██████╗ ███████╗███╗ ██╗██╗██████╗ ██╗███████╗ "); ESP_LOGI(LOGO_TAG, " ██████╗ ██████╗ ███████╗███╗ ██╗██╗██████╗ ██╗███████╗ ");
@@ -70,7 +70,7 @@ namespace Logo
ESP_LOGI(LOGO_TAG, " ████████ "); ESP_LOGI(LOGO_TAG, " ████████ ");
ESP_LOGI(LOGO_TAG, " "); ESP_LOGI(LOGO_TAG, " ");
ESP_LOGI(LOGO_TAG, " <============================================================================================================================> "); ESP_LOGI(LOGO_TAG, " <============================================================================================================================> ");
} }
}; }; // namespace Logo
#endif #endif

View File

@@ -2,14 +2,13 @@
#include <cstring> #include <cstring>
#include "esp_timer.h" #include "esp_timer.h"
static const char *TAG = "WiFiScanner"; 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)
{ {
uint16_t ap_count = 0; uint16_t ap_count = 0;
@@ -21,14 +20,14 @@ void WiFiScanner::scanResultCallback(void *arg, esp_event_base_t event_base,
return; return;
} }
wifi_ap_record_t *ap_records = new wifi_ap_record_t[ap_count]; wifi_ap_record_t* ap_records = new wifi_ap_record_t[ap_count];
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&ap_count, ap_records)); ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&ap_count, ap_records));
scanner->networks.clear(); scanner->networks.clear();
for (uint16_t i = 0; i < ap_count; i++) for (uint16_t i = 0; i < ap_count; i++)
{ {
WiFiNetwork network; WiFiNetwork network;
network.ssid = std::string(reinterpret_cast<char *>(ap_records[i].ssid)); network.ssid = std::string(reinterpret_cast<char*>(ap_records[i].ssid));
network.channel = ap_records[i].primary; network.channel = ap_records[i].primary;
network.rssi = ap_records[i].rssi; network.rssi = ap_records[i].rssi;
memcpy(network.mac, ap_records[i].bssid, 6); memcpy(network.mac, ap_records[i].bssid, 6);
@@ -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};
@@ -130,7 +124,7 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
esp_wifi_scan_get_ap_num(&ch_count); esp_wifi_scan_get_ap_num(&ch_count);
if (ch_count > 0) if (ch_count > 0)
{ {
wifi_ap_record_t *ch_records = new wifi_ap_record_t[ch_count]; wifi_ap_record_t* ch_records = new wifi_ap_record_t[ch_count];
if (esp_wifi_scan_get_ap_records(&ch_count, ch_records) == ESP_OK) if (esp_wifi_scan_get_ap_records(&ch_count, ch_records) == ESP_OK)
{ {
for (uint16_t i = 0; i < ch_count; i++) for (uint16_t i = 0; i < ch_count; i++)
@@ -145,10 +139,10 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
} }
// Process all collected records // Process all collected records
for (const auto &record : all_records) for (const auto& record : all_records)
{ {
WiFiNetwork network; WiFiNetwork network;
network.ssid = std::string(reinterpret_cast<const char *>(record.ssid)); network.ssid = std::string(reinterpret_cast<const char*>(record.ssid));
network.channel = record.primary; network.channel = record.primary;
network.rssi = record.rssi; network.rssi = record.rssi;
memcpy(network.mac, record.bssid, 6); memcpy(network.mac, record.bssid, 6);
@@ -206,7 +200,7 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
return scan_results; return scan_results;
} }
wifi_ap_record_t *ap_records = new wifi_ap_record_t[ap_count]; wifi_ap_record_t* ap_records = new wifi_ap_record_t[ap_count];
err = esp_wifi_scan_get_ap_records(&ap_count, ap_records); err = esp_wifi_scan_get_ap_records(&ap_count, ap_records);
if (err != ESP_OK) if (err != ESP_OK)
{ {
@@ -221,7 +215,7 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
for (uint16_t i = 0; i < ap_count; i++) for (uint16_t i = 0; i < ap_count; i++)
{ {
WiFiNetwork network; WiFiNetwork network;
network.ssid = std::string(reinterpret_cast<char *>(ap_records[i].ssid)); network.ssid = std::string(reinterpret_cast<char*>(ap_records[i].ssid));
network.channel = ap_records[i].primary; network.channel = ap_records[i].primary;
network.rssi = ap_records[i].rssi; network.rssi = ap_records[i].rssi;
memcpy(network.mac, ap_records[i].bssid, 6); memcpy(network.mac, ap_records[i].bssid, 6);

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
{ {
@@ -18,12 +18,12 @@ struct WiFiNetwork
class WiFiScanner class WiFiScanner
{ {
public: public:
WiFiScanner(); WiFiScanner();
std::vector<WiFiNetwork> scanNetworks(int timeout_ms = 15000); std::vector<WiFiNetwork> scanNetworks(int timeout_ms = 15000);
static void scanResultCallback(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data); static void scanResultCallback(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data);
private: private:
std::vector<WiFiNetwork> networks; std::vector<WiFiNetwork> networks;
}; };

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)
@@ -18,7 +17,7 @@ void WiFiManagerHelpers::event_handler(void *arg, esp_event_base_t event_base,
} }
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
{ {
const auto *disconnected = static_cast<wifi_event_sta_disconnected_t *>(event_data); const auto* disconnected = static_cast<wifi_event_sta_disconnected_t*>(event_data);
ESP_LOGI(WIFI_MANAGER_TAG, "Disconnect reason: %d", disconnected->reason); ESP_LOGI(WIFI_MANAGER_TAG, "Disconnect reason: %d", disconnected->reason);
if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY)
@@ -36,17 +35,19 @@ void WiFiManagerHelpers::event_handler(void *arg, esp_event_base_t event_base,
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)
{ {
const auto *event = static_cast<ip_event_got_ip_t *>(event_data); const auto* event = static_cast<ip_event_got_ip_t*>(event_data);
ESP_LOGI(WIFI_MANAGER_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);
} }
} }
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)
{ {
// Clear the config first // Clear the config first
memset(&_wifi_cfg, 0, sizeof(_wifi_cfg)); memset(&_wifi_cfg, 0, sizeof(_wifi_cfg));
@@ -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);
@@ -170,7 +165,7 @@ void WiFiManager::ConnectWithStoredCredentials()
// Ensure we're in STA mode // Ensure we're in STA mode
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
for (const auto &network : networks) for (const auto& network : networks)
{ {
// Reset retry counter for each network attempt // Reset retry counter for each network attempt
s_retry_num = 0; s_retry_num = 0;
@@ -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,
@@ -263,7 +254,7 @@ std::vector<WiFiNetwork> WiFiManager::ScanNetworks(int timeout_ms)
ESP_LOGI(WIFI_MANAGER_TAG, "AP mode detected, checking for STA interface"); ESP_LOGI(WIFI_MANAGER_TAG, "AP mode detected, checking for STA interface");
// Check if STA netif already exists // Check if STA netif already exists
esp_netif_t *sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); esp_netif_t* sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
bool sta_netif_exists = (sta_netif != nullptr); bool sta_netif_exists = (sta_netif != nullptr);
if (!sta_netif_exists) if (!sta_netif_exists)
@@ -341,7 +332,7 @@ void WiFiManager::TryConnectToStoredNetworks()
vTaskDelay(pdMS_TO_TICKS(100)); vTaskDelay(pdMS_TO_TICKS(100));
// Check if STA interface exists, create if needed // Check if STA interface exists, create if needed
esp_netif_t *sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); esp_netif_t* sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
if (sta_netif == nullptr) if (sta_netif == nullptr)
{ {
ESP_LOGI(WIFI_MANAGER_TAG, "Creating STA interface"); ESP_LOGI(WIFI_MANAGER_TAG, "Creating STA interface");
@@ -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,17 +21,16 @@
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
{ {
private: private:
uint8_t channel; uint8_t channel;
std::shared_ptr<ProjectConfig> deviceConfig; std::shared_ptr<ProjectConfig> deviceConfig;
QueueHandle_t eventQueue; QueueHandle_t eventQueue;
StateManager *stateManager; StateManager* stateManager;
wifi_init_config_t _wifi_init_cfg = WIFI_INIT_CONFIG_DEFAULT(); wifi_init_config_t _wifi_init_cfg = WIFI_INIT_CONFIG_DEFAULT();
wifi_config_t _wifi_cfg = {}; wifi_config_t _wifi_cfg = {};
std::unique_ptr<WiFiScanner> wifiScanner; std::unique_ptr<WiFiScanner> wifiScanner;
@@ -41,13 +40,13 @@ private:
int8_t power; int8_t power;
void SetCredentials(const char *ssid, const char *password); void SetCredentials(const char* ssid, const char* password);
void ConnectWithHardcodedCredentials(); void ConnectWithHardcodedCredentials();
void ConnectWithStoredCredentials(); void ConnectWithStoredCredentials();
void SetupAccessPoint(); void SetupAccessPoint();
public: public:
WiFiManager(std::shared_ptr<ProjectConfig> deviceConfig, QueueHandle_t eventQueue, StateManager *stateManager); WiFiManager(std::shared_ptr<ProjectConfig> deviceConfig, QueueHandle_t eventQueue, StateManager* stateManager);
void Begin(); void Begin();
std::vector<WiFiNetwork> ScanNetworks(int timeout_ms = 15000); std::vector<WiFiNetwork> ScanNetworks(int timeout_ms = 15000);
WiFiState_e GetCurrentWiFiState(); WiFiState_e GetCurrentWiFiState();

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>
@@ -50,7 +50,7 @@ QueueHandle_t eventQueue = xQueueCreate(10, sizeof(SystemEvent));
QueueHandle_t ledStateQueue = xQueueCreate(10, sizeof(uint32_t)); QueueHandle_t ledStateQueue = xQueueCreate(10, sizeof(uint32_t));
QueueHandle_t cdcMessageQueue = xQueueCreate(3, sizeof(cdc_command_packet_t)); QueueHandle_t cdcMessageQueue = xQueueCreate(3, sizeof(cdc_command_packet_t));
auto *stateManager = new StateManager(eventQueue, ledStateQueue); auto* stateManager = new StateManager(eventQueue, ledStateQueue);
auto dependencyRegistry = std::make_shared<DependencyRegistry>(); auto dependencyRegistry = std::make_shared<DependencyRegistry>();
auto commandManager = std::make_shared<CommandManager>(dependencyRegistry); auto commandManager = std::make_shared<CommandManager>(dependencyRegistry);
@@ -76,7 +76,7 @@ auto ledManager = std::make_shared<LEDManager>(BLINK_GPIO, CONFIG_LED_C_PIN_GPIO
std::shared_ptr<MonitoringManager> monitoringManager = std::make_shared<MonitoringManager>(); std::shared_ptr<MonitoringManager> monitoringManager = std::make_shared<MonitoringManager>();
#endif #endif
auto *serialManager = new SerialManager(commandManager, &timerHandle); auto* serialManager = new SerialManager(commandManager, &timerHandle);
void startWiFiMode(); void startWiFiMode();
void startWiredMode(bool shouldCloseSerialManager); void startWiredMode(bool shouldCloseSerialManager);
@@ -92,7 +92,7 @@ static void initNVSStorage()
ESP_ERROR_CHECK(ret); ESP_ERROR_CHECK(ret);
} }
int websocket_logger(const char *format, va_list args) int websocket_logger(const char* format, va_list args)
{ {
webSocketLogger.log_message(format, args); webSocketLogger.log_message(format, args);
return vprintf(format, args); return vprintf(format, args);
@@ -129,10 +129,9 @@ 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)