🎨 Replace Arduino String with std::string

This commit is contained in:
Rune Harlyk
2025-09-14 20:08:41 +02:00
committed by Rune Harlyk
parent 0285b522f1
commit 3ce8c88a84
20 changed files with 115 additions and 97 deletions
+9 -8
View File
@@ -6,11 +6,12 @@
#include <list> #include <list>
#include <map> #include <map>
#include <vector> #include <vector>
#include <string>
enum message_type_t { CONNECT = 0, DISCONNECT = 1, EVENT = 2, PING = 3, PONG = 4, BINARY_EVENT = 5 }; enum message_type_t { CONNECT = 0, DISCONNECT = 1, EVENT = 2, PING = 3, PONG = 4, BINARY_EVENT = 5 };
typedef std::function<void(JsonVariant &root, int originId)> EventCallback; typedef std::function<void(JsonVariant &root, int originId)> EventCallback;
typedef std::function<void(const String &originId, bool sync)> SubscribeCallback; typedef std::function<void(const std::string &originId, bool sync)> SubscribeCallback;
class EventSocket { class EventSocket {
public: public:
@@ -20,9 +21,9 @@ class EventSocket {
bool hasSubscribers(const char *event); bool hasSubscribers(const char *event);
void onEvent(String event, EventCallback callback); void onEvent(std::string event, EventCallback callback);
void onSubscribe(String event, SubscribeCallback callback); void onSubscribe(std::string event, SubscribeCallback callback);
void emit(const char *event, JsonVariant &payload, const char *originId = "", bool onlyToSameOrigin = false); void emit(const char *event, JsonVariant &payload, const char *originId = "", bool onlyToSameOrigin = false);
@@ -31,12 +32,12 @@ class EventSocket {
PsychicHttpServer &_server; PsychicHttpServer &_server;
const char *_route; const char *_route;
std::map<String, std::list<int>> client_subscriptions; std::map<std::string, std::list<int>> client_subscriptions;
std::map<String, std::list<EventCallback>> event_callbacks; std::map<std::string, std::list<EventCallback>> event_callbacks;
std::map<String, std::list<SubscribeCallback>> subscribe_callbacks; std::map<std::string, std::list<SubscribeCallback>> subscribe_callbacks;
void handleEventCallbacks(String event, JsonVariant &jsonObject, int originId); void handleEventCallbacks(std::string event, JsonVariant &jsonObject, int originId);
void send(PsychicWebSocketClient *client, const char *data, size_t len); void send(PsychicWebSocketClient *client, const char *data, size_t len);
void handleSubscribeCallbacks(String event, const String &originId); void handleSubscribeCallbacks(std::string event, const std::string &originId);
void onWSOpen(PsychicWebSocketClient *client); void onWSOpen(PsychicWebSocketClient *client);
void onWSClose(PsychicWebSocketClient *client); void onWSClose(PsychicWebSocketClient *client);
+2 -2
View File
@@ -17,10 +17,10 @@
namespace FileSystem { namespace FileSystem {
extern PsychicUploadHandler *uploadHandler; extern PsychicUploadHandler *uploadHandler;
String listFiles(const String &directory, bool isRoot = true); std::string listFiles(const std::string &directory, bool isRoot = true);
bool deleteFile(const char *filename); bool deleteFile(const char *filename);
bool editFile(const char *filename, const char *content); bool editFile(const char *filename, const char *content);
esp_err_t uploadFile(PsychicRequest *request, const String &filename, uint64_t index, uint8_t *data, size_t len, esp_err_t uploadFile(PsychicRequest *request, const std::string &filename, uint64_t index, uint8_t *data, size_t len,
bool last); bool last);
esp_err_t getFiles(PsychicRequest *request); esp_err_t getFiles(PsychicRequest *request);
+5 -4
View File
@@ -6,6 +6,7 @@
#include <utils/json_utils.h> #include <utils/json_utils.h>
#include <utils/ip_utils.h> #include <utils/ip_utils.h>
#include <template/state_result.h> #include <template/state_result.h>
#include <string>
#include <DNSServer.h> #include <DNSServer.h>
#include <IPAddress.h> #include <IPAddress.h>
@@ -58,8 +59,8 @@ enum APNetworkStatus { ACTIVE = 0, INACTIVE, LINGERING };
class APSettings { class APSettings {
public: public:
uint8_t provisionMode; uint8_t provisionMode;
String ssid; std::string ssid;
String password; std::string password;
uint8_t channel; uint8_t channel;
bool ssidHidden; bool ssidHidden;
uint8_t maxClients; uint8_t maxClients;
@@ -76,8 +77,8 @@ class APSettings {
static void read(APSettings &settings, JsonVariant &root) { static void read(APSettings &settings, JsonVariant &root) {
root["provision_mode"] = settings.provisionMode; root["provision_mode"] = settings.provisionMode;
root["ssid"] = settings.ssid; root["ssid"] = settings.ssid.c_str();
root["password"] = settings.password; root["password"] = settings.password.c_str();
root["channel"] = settings.channel; root["channel"] = settings.channel;
root["ssid_hidden"] = settings.ssidHidden; root["ssid_hidden"] = settings.ssidHidden;
root["max_clients"] = settings.maxClients; root["max_clients"] = settings.maxClients;
+17 -16
View File
@@ -4,6 +4,7 @@
#include <utils/json_utils.h> #include <utils/json_utils.h>
#include <template/state_result.h> #include <template/state_result.h>
#include <filesystem.h> #include <filesystem.h>
#include <string>
#ifndef FACTORY_MDNS_HOSTNAME #ifndef FACTORY_MDNS_HOSTNAME
#define FACTORY_MDNS_HOSTNAME "esp32" #define FACTORY_MDNS_HOSTNAME "esp32"
@@ -14,31 +15,31 @@
#endif #endif
typedef struct { typedef struct {
String key; std::string key;
String value; std::string value;
void serialize(JsonVariant &json) const { void serialize(JsonVariant &json) const {
json["key"] = key; json["key"] = key.c_str();
json["value"] = value; json["value"] = value.c_str();
} }
bool deserialize(const JsonVariant &json) { bool deserialize(const JsonVariant &json) {
key = json["key"].as<String>(); key = json["key"].as<std::string>();
value = json["value"].as<String>(); value = json["value"].as<std::string>();
return key.length() > 0; return key.length() > 0;
} }
} mdns_txt_record_t; } mdns_txt_record_t;
typedef struct { typedef struct {
String service; std::string service;
String protocol; std::string protocol;
uint16_t port; uint16_t port;
std::vector<mdns_txt_record_t> txtRecords; std::vector<mdns_txt_record_t> txtRecords;
void serialize(JsonVariant &json) const { void serialize(JsonVariant &json) const {
json["service"] = service; json["service"] = service.c_str();
json["protocol"] = protocol; json["protocol"] = protocol.c_str();
json["port"] = port; json["port"] = port;
if (txtRecords.size() > 0) { if (txtRecords.size() > 0) {
@@ -51,8 +52,8 @@ typedef struct {
} }
bool deserialize(const JsonVariant &json) { bool deserialize(const JsonVariant &json) {
service = json["service"].as<String>(); service = json["service"].as<std::string>();
protocol = json["protocol"].as<String>(); protocol = json["protocol"].as<std::string>();
port = json["port"] | 0; port = json["port"] | 0;
txtRecords.clear(); txtRecords.clear();
@@ -72,14 +73,14 @@ typedef struct {
class MDNSSettings { class MDNSSettings {
public: public:
String hostname; std::string hostname;
String instance; std::string instance;
std::vector<mdns_service_t> services; std::vector<mdns_service_t> services;
std::vector<mdns_txt_record_t> globalTxtRecords; std::vector<mdns_txt_record_t> globalTxtRecords;
static void read(MDNSSettings &settings, JsonVariant &root) { static void read(MDNSSettings &settings, JsonVariant &root) {
root["hostname"] = settings.hostname; root["hostname"] = settings.hostname.c_str();
root["instance"] = settings.instance; root["instance"] = settings.instance.c_str();
JsonArray servicesArray = root["services"].to<JsonArray>(); JsonArray servicesArray = root["services"].to<JsonArray>();
for (const auto &service : settings.services) { for (const auto &service : settings.services) {
+7 -6
View File
@@ -1,6 +1,7 @@
#include <Arduino.h> #include <Arduino.h>
#include <template/state_result.h> #include <template/state_result.h>
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <string>
#ifndef FACTORY_NTP_ENABLED #ifndef FACTORY_NTP_ENABLED
#define FACTORY_NTP_ENABLED true #define FACTORY_NTP_ENABLED true
@@ -21,15 +22,15 @@
class NTPSettings { class NTPSettings {
public: public:
bool enabled; bool enabled;
String tzLabel; std::string tzLabel;
String tzFormat; std::string tzFormat;
String server; std::string server;
static void read(NTPSettings &settings, JsonVariant &root) { static void read(NTPSettings &settings, JsonVariant &root) {
root["enabled"] = settings.enabled; root["enabled"] = settings.enabled;
root["server"] = settings.server; root["server"] = settings.server.c_str();
root["tz_label"] = settings.tzLabel; root["tz_label"] = settings.tzLabel.c_str();
root["tz_format"] = settings.tzFormat; root["tz_format"] = settings.tzFormat.c_str();
} }
static StateUpdateResult update(JsonVariant &root, NTPSettings &settings) { static StateUpdateResult update(JsonVariant &root, NTPSettings &settings) {
@@ -3,6 +3,7 @@
#include <vector> #include <vector>
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <template/state_result.h> #include <template/state_result.h>
#include <string>
/* /*
* I2C software connection * I2C software connection
@@ -20,11 +21,11 @@
class PinConfig { class PinConfig {
public: public:
int pin; int pin;
String mode; std::string mode;
String type; std::string type;
String role; std::string role;
PinConfig(int p, String m, String t, String r) : pin(p), mode(m), type(t), role(r) {} PinConfig(int p, std::string m, std::string t, std::string r) : pin(p), mode(m), type(t), role(r) {}
}; };
class PeripheralsConfiguration { class PeripheralsConfiguration {
+10 -9
View File
@@ -6,6 +6,7 @@
#include <utils/json_utils.h> #include <utils/json_utils.h>
#include <utils/ip_utils.h> #include <utils/ip_utils.h>
#include <template/state_result.h> #include <template/state_result.h>
#include <string>
#ifndef FACTORY_WIFI_SSID #ifndef FACTORY_WIFI_SSID
#define FACTORY_WIFI_SSID "" #define FACTORY_WIFI_SSID ""
@@ -24,10 +25,10 @@
#endif #endif
typedef struct { typedef struct {
String ssid; std::string ssid;
uint8_t bssid[6]; uint8_t bssid[6];
int32_t channel; int32_t channel;
String password; std::string password;
bool staticIPConfig; bool staticIPConfig;
IPAddress localIP; IPAddress localIP;
IPAddress gatewayIP; IPAddress gatewayIP;
@@ -37,8 +38,8 @@ typedef struct {
bool available; bool available;
void serialize(JsonVariant &json) const { void serialize(JsonVariant &json) const {
json["ssid"] = ssid; json["ssid"] = ssid.c_str();
json["password"] = password; json["password"] = password.c_str();
json["static_ip_config"] = staticIPConfig; json["static_ip_config"] = staticIPConfig;
if (staticIPConfig) { if (staticIPConfig) {
JsonUtils::writeIP(json, "local_ip", localIP); JsonUtils::writeIP(json, "local_ip", localIP);
@@ -50,8 +51,8 @@ typedef struct {
} }
bool deserialize(const JsonVariant &json) { bool deserialize(const JsonVariant &json) {
String newSsid = json["ssid"].as<String>(); std::string newSsid = json["ssid"].as<std::string>();
String newPassword = json["password"].as<String>(); std::string newPassword = json["password"].as<std::string>();
if (newSsid.length() < 1 || newSsid.length() > 31 || newPassword.length() > 64) { if (newSsid.length() < 1 || newSsid.length() > 31 || newPassword.length() > 64) {
ESP_LOGE("WiFiSettings", "SSID or password length is invalid"); ESP_LOGE("WiFiSettings", "SSID or password length is invalid");
return false; return false;
@@ -98,11 +99,11 @@ inline wifi_settings_t createDefaultWiFiSettings() {
class WiFiSettings { class WiFiSettings {
public: public:
String hostname; std::string hostname;
bool priorityBySignalStrength; bool priorityBySignalStrength;
std::vector<wifi_settings_t> wifiSettings; std::vector<wifi_settings_t> wifiSettings;
static void read(WiFiSettings &settings, JsonVariant &root) { static void read(WiFiSettings &settings, JsonVariant &root) {
root["hostname"] = settings.hostname; root["hostname"] = settings.hostname.c_str();
root["priority_RSSI"] = settings.priorityBySignalStrength; root["priority_RSSI"] = settings.priorityBySignalStrength;
JsonArray wifiNetworks = root["wifi_networks"].to<JsonArray>(); JsonArray wifiNetworks = root["wifi_networks"].to<JsonArray>();
for (const auto &wifi : settings.wifiSettings) { for (const auto &wifi : settings.wifiSettings) {
@@ -129,7 +130,7 @@ class WiFiSettings {
networkCount++; networkCount++;
} }
} }
} else if (String(FACTORY_WIFI_SSID).length() > 0) { } else if (std::string(FACTORY_WIFI_SSID).length() > 0) {
ESP_LOGI("WiFiSettings", "No WiFi config found - using factory settings"); ESP_LOGI("WiFiSettings", "No WiFi config found - using factory settings");
settings.wifiSettings.push_back(createDefaultWiFiSettings()); settings.wifiSettings.push_back(createDefaultWiFiSettings());
} }
+1 -1
View File
@@ -13,7 +13,7 @@
if (handle != nullptr) vTaskDelete(handle) if (handle != nullptr) vTaskDelete(handle)
struct task_t { struct task_t {
String name; std::string name;
TaskHandle_t handle; TaskHandle_t handle;
uint32_t stackSize; uint32_t stackSize;
UBaseType_t priority; UBaseType_t priority;
@@ -82,7 +82,7 @@ class FSPersistence {
void enableUpdateHandler() { void enableUpdateHandler() {
if (!_updateHandlerId) { if (!_updateHandlerId) {
_updateHandlerId = _statefulService->addUpdateHandler([&](const String &originId) { writeToFS(); }); _updateHandlerId = _statefulService->addUpdateHandler([&](const std::string &originId) { writeToFS(); });
} }
} }
@@ -99,11 +99,11 @@ class FSPersistence {
// "/directory1/directory2/filename" We create a directory for each missing // "/directory1/directory2/filename" We create a directory for each missing
// parent // parent
void mkdirs() { void mkdirs() {
String path(_filePath); std::string path(_filePath);
int index = 0; size_t index = 0;
while ((index = path.indexOf('/', index + 1)) != -1) { while ((index = path.find('/', index + 1)) != std::string::npos) {
String segment = path.substring(0, index); std::string segment = path.substr(0, index);
if (!_fs->exists(segment)) _fs->mkdir(segment); if (!_fs->exists(segment.c_str())) _fs->mkdir(segment.c_str());
} }
} }
+10 -9
View File
@@ -7,6 +7,7 @@
#include <functional> #include <functional>
#include <freertos/FreeRTOS.h> #include <freertos/FreeRTOS.h>
#include <freertos/semphr.h> #include <freertos/semphr.h>
#include <string>
#include <template/state_result.h> #include <template/state_result.h>
@@ -17,8 +18,8 @@ template <typename T>
using JsonStateReader = std::function<void(T &settings, JsonVariant &root)>; using JsonStateReader = std::function<void(T &settings, JsonVariant &root)>;
using HandlerId = size_t; using HandlerId = size_t;
using StateUpdateCallback = std::function<void(const String &originId)>; using StateUpdateCallback = std::function<void(const std::string &originId)>;
using StateHookCallback = std::function<void(const String &originId, StateUpdateResult &result)>; using StateHookCallback = std::function<void(const std::string &originId, StateUpdateResult &result)>;
class HandlerBase { class HandlerBase {
protected: protected:
@@ -40,7 +41,7 @@ class UpdateHandler : public HandlerBase {
UpdateHandler(StateUpdateCallback callback, bool allowRemove) UpdateHandler(StateUpdateCallback callback, bool allowRemove)
: HandlerBase(allowRemove), callback_(std::move(callback)) {} : HandlerBase(allowRemove), callback_(std::move(callback)) {}
void invoke(const String &originId) const { callback_(originId); } void invoke(const std::string &originId) const { callback_(originId); }
}; };
class HookHandler : public HandlerBase { class HookHandler : public HandlerBase {
@@ -50,7 +51,7 @@ class HookHandler : public HandlerBase {
HookHandler(StateHookCallback callback, bool allowRemove) HookHandler(StateHookCallback callback, bool allowRemove)
: HandlerBase(allowRemove), callback_(std::move(callback)) {} : HandlerBase(allowRemove), callback_(std::move(callback)) {}
void invoke(const String &originId, StateUpdateResult &result) const { callback_(originId, result); } void invoke(const std::string &originId, StateUpdateResult &result) const { callback_(originId, result); }
}; };
template <class T> template <class T>
@@ -83,7 +84,7 @@ class StatefulService {
[id](const HookHandler &handler) { return handler.isRemovable() && handler.getId() == id; }); [id](const HookHandler &handler) { return handler.isRemovable() && handler.getId() == id; });
} }
StateUpdateResult update(std::function<StateUpdateResult(T &)> stateUpdater, const String &originId) { StateUpdateResult update(std::function<StateUpdateResult(T &)> stateUpdater, const std::string &originId) {
lock(); lock();
StateUpdateResult result = stateUpdater(state_); StateUpdateResult result = stateUpdater(state_);
unlock(); unlock();
@@ -98,7 +99,7 @@ class StatefulService {
return result; return result;
} }
StateUpdateResult update(JsonVariant &jsonObject, JsonStateUpdater<T> stateUpdater, const String &originId) { StateUpdateResult update(JsonVariant &jsonObject, JsonStateUpdater<T> stateUpdater, const std::string &originId) {
lock(); lock();
StateUpdateResult result = stateUpdater(jsonObject, state_); StateUpdateResult result = stateUpdater(jsonObject, state_);
unlock(); unlock();
@@ -125,13 +126,13 @@ class StatefulService {
unlock(); unlock();
} }
void callUpdateHandlers(const String &originId) { void callUpdateHandlers(const std::string &originId) {
for (const UpdateHandler &updateHandler : updateHandlers_) { for (const UpdateHandler &updateHandler : updateHandlers_) {
updateHandler.invoke(originId); updateHandler.invoke(originId);
} }
} }
void callHookHandlers(const String &originId, StateUpdateResult &result) { void callHookHandlers(const std::string &originId, StateUpdateResult &result) {
for (const HookHandler &hookHandler : hookHandlers_) { for (const HookHandler &hookHandler : hookHandlers_) {
hookHandler.invoke(originId, result); hookHandler.invoke(originId, result);
} }
@@ -145,7 +146,7 @@ class StatefulService {
inline void lock() { xSemaphoreTakeRecursive(mutex_, portMAX_DELAY); } inline void lock() { xSemaphoreTakeRecursive(mutex_, portMAX_DELAY); }
inline void unlock() { xSemaphoreGiveRecursive(mutex_); } inline void unlock() { xSemaphoreGiveRecursive(mutex_); }
void notifyStateChange(const String &originId, StateUpdateResult &result) { void notifyStateChange(const std::string &originId, StateUpdateResult &result) {
callHookHandlers(originId, result); callHookHandlers(originId, result);
if (result == StateUpdateResult::CHANGED) { if (result == StateUpdateResult::CHANGED) {
callUpdateHandlers(originId); callUpdateHandlers(originId);
+4 -3
View File
@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <PsychicHttp.h> #include <PsychicHttp.h>
#include <string>
// #include <event_socket.h> // #include <event_socket.h>
#include <template/stateful_service.h> #include <template/stateful_service.h>
@@ -11,7 +12,7 @@ class EventEndpoint {
EventEndpoint(JsonStateReader<T> stateReader, JsonStateUpdater<T> stateUpdater, StatefulService<T> *statefulService, EventEndpoint(JsonStateReader<T> stateReader, JsonStateUpdater<T> stateUpdater, StatefulService<T> *statefulService,
const char *event) const char *event)
: _stateReader(stateReader), _stateUpdater(stateUpdater), _statefulService(statefulService), _event(event) { : _stateReader(stateReader), _stateUpdater(stateUpdater), _statefulService(statefulService), _event(event) {
_statefulService->addUpdateHandler([&](const String &originId) { syncState(originId); }, false); _statefulService->addUpdateHandler([&](const std::string &originId) { syncState(originId); }, false);
} }
void begin() { void begin() {
@@ -28,10 +29,10 @@ class EventEndpoint {
const char *_event; const char *_event;
void updateState(JsonVariant &root, int originId) { void updateState(JsonVariant &root, int originId) {
_statefulService->update(root, _stateUpdater, String(originId)); _statefulService->update(root, _stateUpdater, std::to_string(originId));
} }
void syncState(const String &originId, bool sync = false) { void syncState(const std::string &originId, bool sync = false) {
JsonDocument jsonDocument; JsonDocument jsonDocument;
JsonVariant root = jsonDocument.to<JsonVariant>(); JsonVariant root = jsonDocument.to<JsonVariant>();
_statefulService->read(root, _stateReader); _statefulService->read(root, _stateReader);
+6 -5
View File
@@ -4,25 +4,26 @@
#include <Arduino.h> #include <Arduino.h>
#include <utils/ip_utils.h> #include <utils/ip_utils.h>
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <string>
class JsonUtils { class JsonUtils {
public: public:
static void readIP(const JsonVariant &root, const String &key, IPAddress &ip, const String &def) { static void readIP(const JsonVariant &root, const std::string &key, IPAddress &ip, const std::string &def) {
IPAddress defaultIp = {}; IPAddress defaultIp = {};
if (!defaultIp.fromString(def)) { if (!defaultIp.fromString(def.c_str())) {
defaultIp = INADDR_NONE; defaultIp = INADDR_NONE;
} }
readIP(root, key, ip, defaultIp); readIP(root, key, ip, defaultIp);
} }
static void readIP(const JsonVariant &root, const String &key, IPAddress &ip, static void readIP(const JsonVariant &root, const std::string &key, IPAddress &ip,
const IPAddress &defaultIp = INADDR_NONE) { const IPAddress &defaultIp = INADDR_NONE) {
if (!root[key].is<String>() || !ip.fromString(root[key].as<String>())) { if (!root[key].is<std::string>() || !ip.fromString(root[key].as<std::string>().c_str())) {
ip = defaultIp; ip = defaultIp;
} }
} }
static void writeIP(JsonVariant &root, const String &key, const IPAddress &ip) { static void writeIP(JsonVariant &root, const std::string &key, const IPAddress &ip) {
if (IPUtils::isSet(ip)) { if (IPUtils::isSet(ip)) {
root[key] = ip.toString(); root[key] = ip.toString();
} }
+2 -1
View File
@@ -1,11 +1,12 @@
#include <ap_service.h> #include <ap_service.h>
#include <string>
static const char *TAG = "APService"; static const char *TAG = "APService";
APService::APService() APService::APService()
: endpoint(APSettings::read, APSettings::update, this), : endpoint(APSettings::read, APSettings::update, this),
_persistence(APSettings::read, APSettings::update, this, AP_SETTINGS_FILE) { _persistence(APSettings::read, APSettings::update, this, AP_SETTINGS_FILE) {
addUpdateHandler([&](const String &originId) { reconfigureAP(); }, false); addUpdateHandler([&](const std::string &originId) { reconfigureAP(); }, false);
} }
APService::~APService() {} APService::~APService() {}
+6 -5
View File
@@ -1,4 +1,5 @@
#include <event_socket.h> #include <event_socket.h>
#include <string>
SemaphoreHandle_t clientSubscriptionsMutex = xSemaphoreCreateMutex(); SemaphoreHandle_t clientSubscriptionsMutex = xSemaphoreCreateMutex();
@@ -78,7 +79,7 @@ esp_err_t EventSocket::onFrame(PsychicWebSocketRequest *request, httpd_ws_frame
if (message_type == CONNECT) { if (message_type == CONNECT) {
ESP_LOGV("EventSocket", "Connect: %s", event); ESP_LOGV("EventSocket", "Connect: %s", event);
client_subscriptions[event].push_back(request->client()->socket()); client_subscriptions[event].push_back(request->client()->socket());
handleSubscribeCallbacks(event, String(request->client()->socket())); handleSubscribeCallbacks(event, std::to_string(request->client()->socket()));
} else if (message_type == DISCONNECT) { } else if (message_type == DISCONNECT) {
ESP_LOGV("EventSocket", "Disconnect: %s", event); ESP_LOGV("EventSocket", "Disconnect: %s", event);
client_subscriptions[event].remove(request->client()->socket()); client_subscriptions[event].remove(request->client()->socket());
@@ -155,22 +156,22 @@ void EventSocket::send(PsychicWebSocketClient *client, const char *data, size_t
#endif #endif
} }
void EventSocket::handleEventCallbacks(String event, JsonVariant &jsonObject, int originId) { void EventSocket::handleEventCallbacks(std::string event, JsonVariant &jsonObject, int originId) {
for (auto &callback : event_callbacks[event]) { for (auto &callback : event_callbacks[event]) {
callback(jsonObject, originId); callback(jsonObject, originId);
} }
} }
void EventSocket::handleSubscribeCallbacks(String event, const String &originId) { void EventSocket::handleSubscribeCallbacks(std::string event, const std::string &originId) {
for (auto &callback : subscribe_callbacks[event]) { for (auto &callback : subscribe_callbacks[event]) {
callback(originId, true); callback(originId, true);
} }
} }
void EventSocket::onEvent(String event, EventCallback callback) { void EventSocket::onEvent(std::string event, EventCallback callback) {
event_callbacks[event].push_back(std::move(callback)); event_callbacks[event].push_back(std::move(callback));
} }
void EventSocket::onSubscribe(String event, SubscribeCallback callback) { void EventSocket::onSubscribe(std::string event, SubscribeCallback callback) {
subscribe_callbacks[event].push_back(std::move(callback)); subscribe_callbacks[event].push_back(std::move(callback));
} }
+13 -9
View File
@@ -1,4 +1,5 @@
#include <filesystem.h> #include <filesystem.h>
#include <string>
static const char *TAG = "FileService"; static const char *TAG = "FileService";
@@ -10,7 +11,10 @@ class Initializer {
public: public:
Initializer() { Initializer() {
uploadHandler = new PsychicUploadHandler(); uploadHandler = new PsychicUploadHandler();
uploadHandler->onUpload(uploadFile); uploadHandler->onUpload([](PsychicRequest *request, const String &filename, uint64_t index, uint8_t *data,
size_t len, bool last) -> esp_err_t {
return uploadFile(request, std::string(filename.c_str()), index, data, len, last);
});
uploadHandler->onRequest([](PsychicRequest *request) { return request->reply(200); }); uploadHandler->onRequest([](PsychicRequest *request) { return request->reply(200); });
} }
}; };
@@ -42,8 +46,8 @@ esp_err_t handleEdit(PsychicRequest *request, JsonVariant &json) {
bool deleteFile(const char *filename) { return ESP_FS.remove(filename); } bool deleteFile(const char *filename) { return ESP_FS.remove(filename); }
String listFiles(const String &directory, bool isRoot) { std::string listFiles(const std::string &directory, bool isRoot) {
File root = ESP_FS.open(directory.startsWith("/") ? directory : "/" + directory); File root = ESP_FS.open(directory.find("/") == 0 ? directory.c_str() : ("/" + directory).c_str());
if (!root.isDirectory()) return "{}"; if (!root.isDirectory()) return "{}";
File file = root.openNextFile(); File file = root.openNextFile();
@@ -51,14 +55,14 @@ String listFiles(const String &directory, bool isRoot) {
return isRoot ? "{ \"root\": {} }" : "{}"; return isRoot ? "{ \"root\": {} }" : "{}";
} }
String output = isRoot ? "{ \"root\": {" : "{"; std::string output = isRoot ? "{ \"root\": {" : "{";
while (file) { while (file) {
String name = String(file.name()); std::string name = std::string(file.name());
if (file.isDirectory()) { if (file.isDirectory()) {
output += "\"" + name + "\": " + listFiles(name, false); output += "\"" + name + "\": " + listFiles(name, false);
} else { } else {
output += "\"" + name + "\": " + String(file.size()); output += "\"" + name + "\": " + std::to_string(file.size());
} }
File next = root.openNextFile(); File next = root.openNextFile();
@@ -72,15 +76,15 @@ String listFiles(const String &directory, bool isRoot) {
return output; return output;
} }
esp_err_t uploadFile(PsychicRequest *request, const String &filename, uint64_t index, uint8_t *data, size_t len, esp_err_t uploadFile(PsychicRequest *request, const std::string &filename, uint64_t index, uint8_t *data, size_t len,
bool last) { bool last) {
File file; File file;
String path = "/www/" + filename; std::string path = "/www/" + filename;
ESP_LOGI(TAG, "Writing %d/%d bytes to: %s\n", (int)index + (int)len, request->contentLength(), path.c_str()); ESP_LOGI(TAG, "Writing %d/%d bytes to: %s\n", (int)index + (int)len, request->contentLength(), path.c_str());
if (last) ESP_LOGI(TAG, "%s is finished. Total bytes: %d\n", path.c_str(), (int)index + (int)len); if (last) ESP_LOGI(TAG, "%s is finished. Total bytes: %d\n", path.c_str(), (int)index + (int)len);
file = ESP_FS.open(path, !index ? FILE_WRITE : FILE_APPEND); file = ESP_FS.open(path.c_str(), !index ? FILE_WRITE : FILE_APPEND);
if (!file) { if (!file) {
ESP_LOGE(TAG, "Failed to open file"); ESP_LOGE(TAG, "Failed to open file");
return ESP_FAIL; return ESP_FAIL;
+4 -3
View File
@@ -1,11 +1,12 @@
#include <mdns_service.h> #include <mdns_service.h>
#include <string>
static const char *TAG = "MDNSService"; static const char *TAG = "MDNSService";
MDNSService::MDNSService() MDNSService::MDNSService()
: _persistence(MDNSSettings::read, MDNSSettings::update, this, MDNS_SETTINGS_FILE), : _persistence(MDNSSettings::read, MDNSSettings::update, this, MDNS_SETTINGS_FILE),
endpoint(MDNSSettings::read, MDNSSettings::update, this) { endpoint(MDNSSettings::read, MDNSSettings::update, this) {
addUpdateHandler([&](const String &originId) { reconfigureMDNS(); }, false); addUpdateHandler([&](const std::string &originId) { reconfigureMDNS(); }, false);
} }
MDNSService::~MDNSService() { MDNSService::~MDNSService() {
@@ -77,8 +78,8 @@ void MDNSService::getStatus(JsonVariant &root) {
} }
esp_err_t MDNSService::queryServices(PsychicRequest *request, JsonVariant &json) { esp_err_t MDNSService::queryServices(PsychicRequest *request, JsonVariant &json) {
String service = json["service"].as<String>(); std::string service = json["service"].as<std::string>();
String proto = json["protocol"].as<String>(); std::string proto = json["protocol"].as<std::string>();
PsychicJsonResponse response = PsychicJsonResponse(request, false); PsychicJsonResponse response = PsychicJsonResponse(request, false);
JsonVariant root = response.getRoot(); JsonVariant root = response.getRoot();
+1 -1
View File
@@ -33,7 +33,7 @@ CameraService::CameraService()
: endpoint(CameraSettings::read, CameraSettings::update, this), : endpoint(CameraSettings::read, CameraSettings::update, this),
_eventEndpoint(CameraSettings::read, CameraSettings::update, this, EVENT_CAMERA_SETTINGS), _eventEndpoint(CameraSettings::read, CameraSettings::update, this, EVENT_CAMERA_SETTINGS),
_persistence(CameraSettings::read, CameraSettings::update, this, CAMERA_SETTINGS_FILE) { _persistence(CameraSettings::read, CameraSettings::update, this, CAMERA_SETTINGS_FILE) {
addUpdateHandler([&](const String &originId) { updateCamera(); }, false); addUpdateHandler([&](const std::string &originId) { updateCamera(); }, false);
} }
esp_err_t CameraService::begin() { esp_err_t CameraService::begin() {
+1 -1
View File
@@ -6,7 +6,7 @@ Peripherals::Peripherals()
EVENT_CONFIGURATION_SETTINGS), EVENT_CONFIGURATION_SETTINGS),
_persistence(PeripheralsConfiguration::read, PeripheralsConfiguration::update, this, DEVICE_CONFIG_FILE) { _persistence(PeripheralsConfiguration::read, PeripheralsConfiguration::update, this, DEVICE_CONFIG_FILE) {
_accessMutex = xSemaphoreCreateMutex(); _accessMutex = xSemaphoreCreateMutex();
addUpdateHandler([&](const String &originId) { updatePins(); }, false); addUpdateHandler([&](const std::string &originId) { updatePins(); }, false);
} }
void Peripherals::begin() { void Peripherals::begin() {
+3 -2
View File
@@ -1,4 +1,5 @@
#include "system_service.h" #include "system_service.h"
#include <string>
namespace system_service { namespace system_service {
@@ -38,9 +39,9 @@ void reset() {
File root = ESP_FS.open(FS_CONFIG_DIRECTORY); File root = ESP_FS.open(FS_CONFIG_DIRECTORY);
File file; File file;
while (file = root.openNextFile()) { while (file = root.openNextFile()) {
String path = file.path(); std::string path = file.path();
file.close(); file.close();
ESP_FS.remove(path); ESP_FS.remove(path.c_str());
} }
restart(); restart();
} }
+3 -2
View File
@@ -1,9 +1,10 @@
#include <wifi_service.h> #include <wifi_service.h>
#include <string>
WiFiService::WiFiService() WiFiService::WiFiService()
: _persistence(WiFiSettings::read, WiFiSettings::update, this, WIFI_SETTINGS_FILE), : _persistence(WiFiSettings::read, WiFiSettings::update, this, WIFI_SETTINGS_FILE),
endpoint(WiFiSettings::read, WiFiSettings::update, this) { endpoint(WiFiSettings::read, WiFiSettings::update, this) {
addUpdateHandler([&](const String &originId) { reconfigureWiFiConnection(); }, false); addUpdateHandler([&](const std::string &originId) { reconfigureWiFiConnection(); }, false);
} }
WiFiService::~WiFiService() {} WiFiService::~WiFiService() {}
@@ -144,7 +145,7 @@ void WiFiService::connectToWiFi() {
WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan); WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan);
for (auto &network : state().wifiSettings) { for (auto &network : state().wifiSettings) {
if (ssid_scan == network.ssid) { if (ssid_scan == network.ssid.c_str()) {
if (rssi_scan >= FACTORY_WIFI_RSSI_THRESHOLD) { if (rssi_scan >= FACTORY_WIFI_RSSI_THRESHOLD) {
network.available = true; network.available = true;
} }