🪄 Formats ESP32SvelteKit

This commit is contained in:
Rune Harlyk
2024-07-09 20:09:22 +02:00
committed by Rune Harlyk
parent b75c3bc251
commit 0e29dba043
3 changed files with 86 additions and 178 deletions
+25 -38
View File
@@ -15,8 +15,7 @@
#include <ESP32SvelteKit.h> #include <ESP32SvelteKit.h>
ESP32SvelteKit::ESP32SvelteKit(PsychicHttpServer *server, ESP32SvelteKit::ESP32SvelteKit(PsychicHttpServer *server, unsigned int numberEndpoints)
unsigned int numberEndpoints)
: _server(server), : _server(server),
_numberEndpoints(numberEndpoints), _numberEndpoints(numberEndpoints),
_taskManager(), _taskManager(),
@@ -27,8 +26,7 @@ ESP32SvelteKit::ESP32SvelteKit(PsychicHttpServer *server,
_wifiStatus(server, &_securitySettingsService), _wifiStatus(server, &_securitySettingsService),
_apSettingsService(server, &ESPFS, &_securitySettingsService), _apSettingsService(server, &ESPFS, &_securitySettingsService),
_apStatus(server, &_securitySettingsService, &_apSettingsService), _apStatus(server, &_securitySettingsService, &_apSettingsService),
_socket(server, &_securitySettingsService, _socket(server, &_securitySettingsService, AuthenticationPredicates::IS_AUTHENTICATED),
AuthenticationPredicates::IS_AUTHENTICATED),
#if FT_ENABLED(FT_NTP) #if FT_ENABLED(FT_NTP)
_ntpSettingsService(server, &ESPFS, &_securitySettingsService), _ntpSettingsService(server, &ESPFS, &_securitySettingsService),
_ntpStatus(server, &_securitySettingsService), _ntpStatus(server, &_securitySettingsService),
@@ -37,8 +35,7 @@ ESP32SvelteKit::ESP32SvelteKit(PsychicHttpServer *server,
_uploadFirmwareService(server, &_securitySettingsService), _uploadFirmwareService(server, &_securitySettingsService),
#endif #endif
#if FT_ENABLED(FT_DOWNLOAD_FIRMWARE) #if FT_ENABLED(FT_DOWNLOAD_FIRMWARE)
_downloadFirmwareService(server, &_securitySettingsService, &_socket, _downloadFirmwareService(server, &_securitySettingsService, &_socket, &_taskManager),
&_taskManager),
#endif #endif
#if FT_ENABLED(FT_SECURITY) #if FT_ENABLED(FT_SECURITY)
_authenticationService(server, &_securitySettingsService), _authenticationService(server, &_securitySettingsService),
@@ -61,16 +58,16 @@ ESP32SvelteKit::ESP32SvelteKit(PsychicHttpServer *server,
_systemStatus(server, &_securitySettingsService), _systemStatus(server, &_securitySettingsService),
_fileExplorer(server, &_securitySettingsService), _fileExplorer(server, &_securitySettingsService),
#if FT_ENABLED(FT_MOTION) #if FT_ENABLED(FT_MOTION)
_motionService(_server, &_socket, &_securitySettingsService,&_taskManager), _motionService(_server, &_socket, &_securitySettingsService, &_taskManager),
#endif #endif
#if FT_ENABLED(FT_WS2812) #if FT_ENABLED(FT_WS2812)
_ledService(&_taskManager), _ledService(&_taskManager),
#endif #endif
#if FT_ENABLED(FT_SERVO) #if FT_ENABLED(FT_SERVO)
_servoController(server, &ESPFS, &_securitySettingsService, &_socket), _servoController(server, &ESPFS, &_securitySettingsService, &_socket),
#endif #endif
_peripherals(server, &ESPFS, &_securitySettingsService, &_socket) _peripherals(server, &ESPFS, &_securitySettingsService, &_socket) {
{ } }
void ESP32SvelteKit::begin() { void ESP32SvelteKit::begin() {
ESP_LOGV("ESP32SvelteKit", "Loading settings from files system"); ESP_LOGV("ESP32SvelteKit", "Loading settings from files system");
@@ -86,8 +83,7 @@ void ESP32SvelteKit::begin() {
startServices(); startServices();
ESP_LOGV("ESP32SvelteKit", "Starting loop task"); ESP_LOGV("ESP32SvelteKit", "Starting loop task");
_taskManager.createTask(this->_loopImpl, "Spot main", 4096, this, _taskManager.createTask(this->_loopImpl, "Spot main", 4096, this, (tskIDLE_PRIORITY + 1), NULL,
(tskIDLE_PRIORITY + 1), NULL,
ESP32SVELTEKIT_RUNNING_CORE); ESP32SVELTEKIT_RUNNING_CORE);
} }
@@ -96,21 +92,17 @@ void ESP32SvelteKit::setupServer() {
_server->listen(80); _server->listen(80);
#ifdef EMBED_WWW #ifdef EMBED_WWW
ESP_LOGV("ESP32SvelteKit", ESP_LOGV("ESP32SvelteKit", "Registering routes from PROGMEM static resources");
"Registering routes from PROGMEM static resources"); WWWData::registerRoutes([&](const String &uri, const String &contentType, const uint8_t *content, size_t len) {
WWWData::registerRoutes([&](const String &uri, const String &contentType, PsychicHttpRequestCallback requestHandler = [contentType, content, len](PsychicRequest *request) {
const uint8_t *content, size_t len) { PsychicResponse response(request);
PsychicHttpRequestCallback requestHandler = response.setCode(200);
[contentType, content, len](PsychicRequest *request) { response.setContentType(contentType.c_str());
PsychicResponse response(request); response.addHeader("Content-Encoding", "gzip");
response.setCode(200); response.addHeader("Cache-Control", "public, immutable, max-age=31536000");
response.setContentType(contentType.c_str()); response.setContent(content, len);
response.addHeader("Content-Encoding", "gzip"); return response.send();
response.addHeader("Cache-Control", };
"public, immutable, max-age=31536000");
response.setContent(content, len);
return response.send();
};
PsychicWebHandler *handler = new PsychicWebHandler(); PsychicWebHandler *handler = new PsychicWebHandler();
handler->onRequest(requestHandler); handler->onRequest(requestHandler);
_server->on(uri.c_str(), HTTP_GET, handler); _server->on(uri.c_str(), HTTP_GET, handler);
@@ -123,15 +115,13 @@ void ESP32SvelteKit::setupServer() {
}); });
#else #else
// Serve static resources from /www/ // Serve static resources from /www/
ESP_LOGV("ESP32SvelteKit", ESP_LOGV("ESP32SvelteKit", "Registering routes from FS /www/ static resources");
"Registering routes from FS /www/ static resources");
_server->serveStatic("/_app/", ESPFS, "/www/_app/"); _server->serveStatic("/_app/", ESPFS, "/www/_app/");
_server->serveStatic("/favicon.png", ESPFS, "/www/favicon.png"); _server->serveStatic("/favicon.png", ESPFS, "/www/favicon.png");
// Serving all other get requests with "/www/index.htm" // Serving all other get requests with "/www/index.htm"
_server->onNotFound([](PsychicRequest *request) { _server->onNotFound([](PsychicRequest *request) {
if (request->method() == HTTP_GET) { if (request->method() == HTTP_GET) {
PsychicFileResponse response(request, ESPFS, "/www/index.html", PsychicFileResponse response(request, ESPFS, "/www/index.html", "text/html");
"text/html");
return response.send(); return response.send();
// String url = "http://" + request->host() + "/index.html"; // String url = "http://" + request->host() + "/index.html";
// request->redirect(url.c_str()); // request->redirect(url.c_str());
@@ -144,12 +134,9 @@ void ESP32SvelteKit::setupServer() {
#if defined(ENABLE_CORS) #if defined(ENABLE_CORS)
ESP_LOGV("ESP32SvelteKit", "Enabling CORS headers"); ESP_LOGV("ESP32SvelteKit", "Enabling CORS headers");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", CORS_ORIGIN);
CORS_ORIGIN); DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "Accept, Content-Type, Authorization");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
"Accept, Content-Type, Authorization");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials",
"true");
#endif #endif
DefaultHeaders::Instance().addHeader("Server", _appName); DefaultHeaders::Instance().addHeader("Server", _appName);
} }
@@ -236,7 +223,7 @@ void IRAM_ATTR ESP32SvelteKit::_loop() {
#if FT_ENABLED(FT_WS2812) #if FT_ENABLED(FT_WS2812)
_ledService.loop(); _ledService.loop();
#endif #endif
_peripherals.loop(); _peripherals.loop();
delay(20); delay(20);
} }
} }
+24 -86
View File
@@ -71,126 +71,64 @@
#define ESP32SVELTEKIT_RUNNING_CORE -1 #define ESP32SVELTEKIT_RUNNING_CORE -1
#endif #endif
class ESP32SvelteKit class ESP32SvelteKit {
{ public:
public:
ESP32SvelteKit(PsychicHttpServer *server, unsigned int numberEndpoints = 115); ESP32SvelteKit(PsychicHttpServer *server, unsigned int numberEndpoints = 115);
void begin(); void begin();
FS *getFS() FS *getFS() { return &ESPFS; }
{
return &ESPFS;
}
PsychicHttpServer *getServer() PsychicHttpServer *getServer() { return _server; }
{
return _server;
}
SecurityManager *getSecurityManager() SecurityManager *getSecurityManager() { return &_securitySettingsService; }
{
return &_securitySettingsService;
}
EventSocket *getSocket() EventSocket *getSocket() { return &_socket; }
{
return &_socket;
}
StatefulService<WiFiSettings> *getWiFiSettingsService() StatefulService<WiFiSettings> *getWiFiSettingsService() { return &_wifiSettingsService; }
{
return &_wifiSettingsService;
}
StatefulService<APSettings> *getAPSettingsService() StatefulService<APSettings> *getAPSettingsService() { return &_apSettingsService; }
{
return &_apSettingsService;
}
#if FT_ENABLED(FT_NTP) #if FT_ENABLED(FT_NTP)
StatefulService<NTPSettings> *getNTPSettingsService() StatefulService<NTPSettings> *getNTPSettingsService() { return &_ntpSettingsService; }
{
return &_ntpSettingsService;
}
#endif #endif
#if FT_ENABLED(FT_SLEEP) #if FT_ENABLED(FT_SLEEP)
SleepService *getSleepService() SleepService *getSleepService() { return &_sleepService; }
{
return &_sleepService;
}
#endif #endif
#if FT_ENABLED(FT_BATTERY) #if FT_ENABLED(FT_BATTERY)
BatteryService *getBatteryService() BatteryService *getBatteryService() { return &_batteryService; }
{
return &_batteryService;
}
#endif #endif
FeaturesService *getFeatureService() FeaturesService *getFeatureService() { return &_featureService; }
{
return &_featureService;
}
TaskManager *getTaskManager() TaskManager *getTaskManager() { return &_taskManager; }
{
return &_taskManager;
}
FileExplorer *getFileExplorer() FileExplorer *getFileExplorer() { return &_fileExplorer; }
{
return &_fileExplorer;
}
#if FT_ENABLED(FT_MOTION) #if FT_ENABLED(FT_MOTION)
MotionService *getMotionService() MotionService *getMotionService() { return &_motionService; }
{
return &_motionService;
}
#endif #endif
#if FT_ENABLED(FT_CAMERA) #if FT_ENABLED(FT_CAMERA)
CameraService *getCameraService() CameraService *getCameraService() { return &_cameraService; }
{ CameraSettingsService *getCameraSettingsService() { return &_cameraSettingsService; }
return &_cameraService;
}
CameraSettingsService *getCameraSettingsService()
{
return &_cameraSettingsService;
}
#endif #endif
Peripherals *getPeripherals() Peripherals *getPeripherals() { return &_peripherals; }
{
return &_peripherals;
}
#if FT_ENABLED(FT_SERVO) #if FT_ENABLED(FT_SERVO)
ServoController *getServoController() ServoController *getServoController() { return &_servoController; }
{
return &_servoController;
}
#endif #endif
void factoryReset() void factoryReset() { _factoryResetService.factoryReset(); }
{
_factoryResetService.factoryReset();
}
void setMDNSAppName(String name) void setMDNSAppName(String name) { _appName = name; }
{
_appName = name;
}
void recoveryMode() void recoveryMode() { _apSettingsService.recoveryMode(); }
{
_apSettingsService.recoveryMode();
}
private: private:
PsychicHttpServer *_server; PsychicHttpServer *_server;
unsigned int _numberEndpoints; unsigned int _numberEndpoints;
FeaturesService _featureService; FeaturesService _featureService;
@@ -245,7 +183,7 @@ private:
String _appName = APP_NAME; String _appName = APP_NAME;
protected: protected:
static void _loopImpl(void *_this) { static_cast<ESP32SvelteKit *>(_this)->_loop(); } static void _loopImpl(void *_this) { static_cast<ESP32SvelteKit *>(_this)->_loop(); }
void _loop(); void _loop();
void setupServer(); void setupServer();
+36 -53
View File
@@ -26,8 +26,8 @@
#endif #endif
#define SERVO_STATE_SPEED_MS 20 #define SERVO_STATE_SPEED_MS 20
#define SERVO_MIN 150 // This is the 'minimum' pulse length count (out of 4096) #define SERVO_MIN 150 // This is the 'minimum' pulse length count (out of 4096)
#define SERVO_MAX 650 // This is the 'maximum' pulse length count (out of 4096) #define SERVO_MAX 650 // This is the 'maximum' pulse length count (out of 4096)
enum SERVO_STATE { SERVO_STATE_ACTIVE, SERVO_STATE_SWEEPING_FORWARD, SERVO_STATE_SWEEPING_BACKWARD }; enum SERVO_STATE { SERVO_STATE_ACTIVE, SERVO_STATE_SWEEPING_FORWARD, SERVO_STATE_SWEEPING_BACKWARD };
@@ -41,18 +41,17 @@ struct servo_t {
}; };
class ServoConfiguration { class ServoConfiguration {
public: public:
int32_t servo_oscillator_frequency{FACTORY_SERVO_OSCILLATOR_FREQUENCY}; int32_t servo_oscillator_frequency {FACTORY_SERVO_OSCILLATOR_FREQUENCY};
int32_t servo_pwm_frequency{FACTORY_SERVO_PWM_FREQUENCY}; int32_t servo_pwm_frequency {FACTORY_SERVO_PWM_FREQUENCY};
std::vector<servo_t> servos_config; std::vector<servo_t> servos_config;
bool is_active{true}; bool is_active {true};
const int8_t servo_invert[12] = {-1, 1, 1, -1, -1, -1, 1, 1, 1, 1, -1, -1}; const int8_t servo_invert[12] = {-1, 1, 1, -1, -1, -1, 1, 1, 1, 1, -1, -1};
static void read(ServoConfiguration &settings, JsonObject &root) { static void read(ServoConfiguration &settings, JsonObject &root) {
root["is_active"] = settings.is_active; root["is_active"] = settings.is_active;
root["servo_pwm_frequency"] = settings.servo_pwm_frequency; root["servo_pwm_frequency"] = settings.servo_pwm_frequency;
root["servo_oscillator_frequency"] = root["servo_oscillator_frequency"] = settings.servo_oscillator_frequency;
settings.servo_oscillator_frequency;
JsonArray servos = root["servos"].to<JsonArray>(); JsonArray servos = root["servos"].to<JsonArray>();
@@ -68,14 +67,10 @@ class ServoConfiguration {
} }
} }
static StateUpdateResult update(JsonObject &root, static StateUpdateResult update(JsonObject &root, ServoConfiguration &settings) {
ServoConfiguration &settings) {
settings.is_active = root["is_active"] | settings.is_active; settings.is_active = root["is_active"] | settings.is_active;
settings.servo_pwm_frequency = settings.servo_pwm_frequency = root["servo_pwm_frequency"] | settings.servo_pwm_frequency;
root["servo_pwm_frequency"] | settings.servo_pwm_frequency; settings.servo_oscillator_frequency = root["servo_oscillator_frequency"] | settings.servo_oscillator_frequency;
settings.servo_oscillator_frequency =
root["servo_oscillator_frequency"] |
settings.servo_oscillator_frequency;
JsonArray servos = root["servos"]; JsonArray servos = root["servos"];
@@ -83,15 +78,15 @@ class ServoConfiguration {
ESP_LOGI("ControllerSettings", "No servos found, adding default servos"); ESP_LOGI("ControllerSettings", "No servos found, adding default servos");
for (int8_t i = 0; i < FACTORY_SERVO_NUM; i++) { for (int8_t i = 0; i < FACTORY_SERVO_NUM; i++) {
ESP_LOGI("ControllerSettings", "Adding servo %d", i); ESP_LOGI("ControllerSettings", "Adding servo %d", i);
settings.servos_config.push_back( settings.servos_config.push_back(servo_t {
servo_t{.name = "Servo " + String(i), .name = "Servo " + String(i),
.channel = i, .channel = i,
.inverted = 1, .inverted = 1,
.angle = 0, .angle = 0,
.center_angle = FACTORY_SERVO_CENTER_ANGLE .center_angle = FACTORY_SERVO_CENTER_ANGLE
// , // ,
// .state = SERVO_STATE_ACTIVE // .state = SERVO_STATE_ACTIVE
}); });
} }
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
} }
@@ -99,22 +94,18 @@ class ServoConfiguration {
for (auto new_servo_json : servos) { for (auto new_servo_json : servos) {
JsonObject servo_config = new_servo_json.as<JsonObject>(); JsonObject servo_config = new_servo_json.as<JsonObject>();
int8_t channel = servo_config["channel"] | -1; int8_t channel = servo_config["channel"] | -1;
servo_t *servo = servo_t *servo = get_servo_by_channel(settings.servos_config, channel);
get_servo_by_channel(settings.servos_config, channel);
if (servo != nullptr) { if (servo != nullptr) {
servo->name = servo_config["name"].as<String>() || servo->name; servo->name = servo_config["name"].as<String>() || servo->name;
if (servo_config["inverted"]) if (servo_config["inverted"]) servo->inverted = servo_config["inverted"];
servo->inverted = servo_config["inverted"];
if (servo_config["angle"].is<int16_t>()) { if (servo_config["angle"].is<int16_t>()) {
servo->angle = servo_config["angle"].as<int16_t>(); servo->angle = servo_config["angle"].as<int16_t>();
servo->state = SERVO_STATE_ACTIVE; servo->state = SERVO_STATE_ACTIVE;
} }
if (servo_config["center_angle"].is<int16_t>()) if (servo_config["center_angle"].is<int16_t>())
servo->center_angle = servo->center_angle = servo_config["center_angle"].as<int16_t>();
servo_config["center_angle"].as<int16_t>(); if (servo_config["sweep"]) servo->state = SERVO_STATE_SWEEPING_FORWARD;
if (servo_config["sweep"])
servo->state = SERVO_STATE_SWEEPING_FORWARD;
continue; continue;
} }
@@ -131,8 +122,7 @@ class ServoConfiguration {
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}; };
static servo_t *get_servo_by_channel(std::vector<servo_t> &servos_config, static servo_t *get_servo_by_channel(std::vector<servo_t> &servos_config, int8_t channel_id) {
int8_t channel_id) {
for (auto &servo : servos_config) { for (auto &servo : servos_config) {
if (servo.channel == channel_id) { if (servo.channel == channel_id) {
return &servo; return &servo;
@@ -142,20 +132,16 @@ class ServoConfiguration {
} }
}; };
class ServoController : public Adafruit_PWMServoDriver, class ServoController : public Adafruit_PWMServoDriver, public StatefulService<ServoConfiguration> {
public StatefulService<ServoConfiguration> { public:
public: ServoController(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager, EventSocket *socket)
ServoController(PsychicHttpServer *server, FS *fs,
SecurityManager *securityManager, EventSocket *socket)
: Adafruit_PWMServoDriver(), : Adafruit_PWMServoDriver(),
_server(server), _server(server),
_securityManager(securityManager), _securityManager(securityManager),
_eventEndpoint(ServoConfiguration::read, ServoConfiguration::update, _eventEndpoint(ServoConfiguration::read, ServoConfiguration::update, this, socket,
this, socket, EVENT_CONFIGURATION_SETTINGS), EVENT_CONFIGURATION_SETTINGS),
_fsPersistence(ServoConfiguration::read, ServoConfiguration::update, _fsPersistence(ServoConfiguration::read, ServoConfiguration::update, this, fs, SERVO_CONFIG_FILE) {
this, fs, SERVO_CONFIG_FILE) { addUpdateHandler([&](const String &originId) { updateServos(); }, false);
addUpdateHandler([&](const String &originId) { updateServos(); },
false);
} }
void configure() { void configure() {
@@ -164,8 +150,7 @@ class ServoController : public Adafruit_PWMServoDriver,
setOscillatorFrequency(_state.servo_oscillator_frequency); setOscillatorFrequency(_state.servo_oscillator_frequency);
setPWMFreq(_state.servo_pwm_frequency); setPWMFreq(_state.servo_pwm_frequency);
deactivate(); deactivate();
ESP_LOGI("ServoController", ESP_LOGI("ServoController", "Configured with oscillator frequency %d and PWM frequency %d",
"Configured with oscillator frequency %d and PWM frequency %d",
_state.servo_oscillator_frequency, _state.servo_pwm_frequency); _state.servo_oscillator_frequency, _state.servo_pwm_frequency);
} }
@@ -195,7 +180,7 @@ class ServoController : public Adafruit_PWMServoDriver,
} }
} }
void setAngle(servo_t* servo) { void setAngle(servo_t *servo) {
int8_t channel = servo->channel; int8_t channel = servo->channel;
bool invert = servo->inverted; bool invert = servo->inverted;
int16_t angle = invert ? 180 - servo->angle : servo->angle; int16_t angle = invert ? 180 - servo->angle : servo->angle;
@@ -203,9 +188,7 @@ class ServoController : public Adafruit_PWMServoDriver,
setPWM(channel, 0, angleToPwm(angle)); setPWM(channel, 0, angleToPwm(angle));
} }
uint16_t angleToPwm(int angle) { uint16_t angleToPwm(int angle) { return map(angle, 0, 180, SERVO_MIN, SERVO_MAX); }
return map(angle, 0, 180, SERVO_MIN, SERVO_MAX);
}
void updateServoState() { void updateServoState() {
for (auto &servo : _state.servos_config) { for (auto &servo : _state.servos_config) {
@@ -233,13 +216,13 @@ class ServoController : public Adafruit_PWMServoDriver,
} }
} }
private: private:
PsychicHttpServer *_server; PsychicHttpServer *_server;
SecurityManager *_securityManager; SecurityManager *_securityManager;
EventEndpoint<ServoConfiguration> _eventEndpoint; EventEndpoint<ServoConfiguration> _eventEndpoint;
FSPersistence<ServoConfiguration> _fsPersistence; FSPersistence<ServoConfiguration> _fsPersistence;
bool is_active{true}; bool is_active {true};
unsigned long _lastUpdate; unsigned long _lastUpdate;
constexpr static int ServoInterval = 2; constexpr static int ServoInterval = 2;
}; };