refactor: network management code moved to MainTask (memory optimization); removed stopping DHCP server and client on reset wifi

This commit is contained in:
Yurii
2024-01-17 16:08:53 +03:00
parent 8731311c62
commit 133015d7b9
15 changed files with 661 additions and 608 deletions

View File

@@ -1,43 +0,0 @@
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#include "lwip/etharp.h"
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#endif
struct Connection {
enum class Status {
CONNECTED,
CONNECTING,
GOT_IP,
DISCONNECTED
};
enum class DisconnectReason {
BEACON_TIMEOUT,
NO_AP_FOUND,
AUTH_FAIL,
ASSOC_FAIL,
HANDSHAKE_TIMEOUT,
DHCP_TIMEOUT,
OTHER,
NONE
};
static Status status;
static DisconnectReason disconnectReason;
static void setup(bool useDhcp);
static void setUseDhcp(bool value);
static Status getStatus();
static DisconnectReason getDisconnectReason();
#if defined(ARDUINO_ARCH_ESP8266)
static void onEvent(System_Event_t *evt);
#elif defined(ARDUINO_ARCH_ESP32)
static void onEvent(WiFiEvent_t event, WiFiEventInfo_t info);
#endif
protected:
static DisconnectReason convertDisconnectReason(uint8_t reason);
static bool useDhcp;
};

View File

@@ -4,6 +4,8 @@
class HomeAssistantHelper {
public:
typedef std::function<void(const char*, bool)> PublishEventCallback;
HomeAssistantHelper() {}
void setWriter() {
@@ -14,12 +16,8 @@ public:
this->writer = writer;
}
void setEventPublishCallback(std::function<void(const char*, bool)> callback) {
this->eventPublishCallback = callback;
}
void setEventPublishCallback() {
this->eventPublishCallback = nullptr;
void setPublishEventCallback(PublishEventCallback callback) {
this->publishEventCallback = callback;
}
void setDevicePrefix(const char* value) {
@@ -48,7 +46,10 @@ public:
bool publish(const char* topic, JsonDocument& doc) {
if (this->writer == nullptr) {
this->eventPublishCallback(topic, false);
if (this->publishEventCallback) {
this->publishEventCallback(topic, false);
}
return false;
}
@@ -75,8 +76,8 @@ public:
doc.clear();
doc.shrinkToFit();
if (this->eventPublishCallback) {
this->eventPublishCallback(topic, result);
if (this->publishEventCallback) {
this->publishEventCallback(topic, result);
}
return result;
@@ -84,13 +85,16 @@ public:
bool publish(const char* topic) {
if (this->writer == nullptr) {
this->eventPublishCallback(topic, false);
if (this->publishEventCallback) {
this->publishEventCallback(topic, false);
}
return false;
}
bool result = writer->publish(topic, nullptr, 0, true);
if (this->eventPublishCallback) {
this->eventPublishCallback(topic, result);
if (this->publishEventCallback) {
this->publishEventCallback(topic, result);
}
return result;
@@ -129,7 +133,7 @@ public:
}
protected:
std::function<void(const char*, bool)> eventPublishCallback = nullptr;
PublishEventCallback publishEventCallback;
MqttWriter* writer = nullptr;
const char* prefix = "homeassistant";
const char* devicePrefix = "";

View File

@@ -8,6 +8,10 @@
class MqttWriter {
public:
typedef std::function<void()> YieldCallback;
typedef std::function<void(const char*, size_t, size_t, bool)> PublishEventCallback;
typedef std::function<void(size_t, size_t)> FlushEventCallback;
MqttWriter(MqttClient* client, size_t bufferSize = 64) {
this->client = client;
this->bufferSize = bufferSize;
@@ -26,28 +30,22 @@ public:
#endif
}
void setYieldCallback(std::function<void()> callback) {
MqttWriter* setYieldCallback(YieldCallback callback = nullptr) {
this->yieldCallback = callback;
return this;
}
void setYieldCallback() {
this->yieldCallback = nullptr;
MqttWriter* setPublishEventCallback(PublishEventCallback callback) {
this->publishEventCallback = callback;
return this;
}
void setEventPublishCallback(std::function<void(const char*, size_t, size_t, bool)> callback) {
this->eventPublishCallback = callback;
}
MqttWriter* setFlushEventCallback(FlushEventCallback callback) {
this->flushEventCallback = callback;
void setEventPublishCallback() {
this->eventPublishCallback = nullptr;
}
void setEventFlushCallback(std::function<void(size_t, size_t)> callback) {
this->eventFlushCallback = callback;
}
void setEventFlushCallback() {
this->eventFlushCallback = nullptr;
return this;
}
bool lock() {
@@ -103,8 +101,8 @@ public:
}
this->unlock();
if (this->eventPublishCallback) {
this->eventPublishCallback(topic, written, docSize, written == docSize);
if (this->publishEventCallback) {
this->publishEventCallback(topic, written, docSize, written == docSize);
}
return written == docSize;
@@ -142,8 +140,8 @@ public:
}
this->unlock();
if (this->eventPublishCallback) {
this->eventPublishCallback(topic, written, length, result);
if (this->publishEventCallback) {
this->publishEventCallback(topic, written, length, result);
}
return result;
@@ -198,14 +196,17 @@ public:
this->writeAfterLock += written;
}
if (this->eventFlushCallback) {
this->eventFlushCallback(written, length);
if (this->flushEventCallback) {
this->flushEventCallback(written, length);
}
return written == length;
}
protected:
YieldCallback yieldCallback;
PublishEventCallback publishEventCallback;
FlushEventCallback flushEventCallback;
MqttClient* client;
uint8_t* buffer;
size_t bufferSize = 64;
@@ -216,7 +217,4 @@ protected:
#endif
unsigned long lockedTime = 0;
size_t writeAfterLock = 0;
std::function<void()> yieldCallback = nullptr;
std::function<void(const char*, size_t, size_t, bool)> eventPublishCallback = nullptr;
std::function<void(size_t, size_t)> eventFlushCallback = nullptr;
};

View File

@@ -1,4 +1,5 @@
#include "Connection.h"
#include "NetworkConnection.h"
using namespace Network;
void Connection::setup(bool useDhcp) {
setUseDhcp(useDhcp);
@@ -10,6 +11,11 @@ void Connection::setup(bool useDhcp) {
#endif
}
void Connection::reset() {
status = Status::NONE;
disconnectReason = DisconnectReason::NONE;
}
void Connection::setUseDhcp(bool value) {
useDhcp = value;
}
@@ -23,8 +29,8 @@ Connection::DisconnectReason Connection::getDisconnectReason() {
}
#if defined(ARDUINO_ARCH_ESP8266)
void Connection::onEvent(System_Event_t *evt) {
switch (evt->event) {
void Connection::onEvent(System_Event_t *event) {
switch (event->event) {
case EVENT_STAMODE_CONNECTED:
status = useDhcp ? Status::CONNECTING : Status::CONNECTED;
disconnectReason = DisconnectReason::NONE;
@@ -43,8 +49,25 @@ void Connection::onEvent(System_Event_t *evt) {
case EVENT_STAMODE_DISCONNECTED:
status = Status::DISCONNECTED;
disconnectReason = convertDisconnectReason(evt->event_info.disconnected.reason);
disconnectReason = convertDisconnectReason(event->event_info.disconnected.reason);
// https://github.com/esp8266/Arduino/blob/d5eb265f78bff9deb7063d10030a02d021c8c66c/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp#L231
if ((wifi_station_get_connect_status() == STATION_GOT_IP) && !wifi_station_get_reconnect_policy()) {
wifi_station_disconnect();
}
break;
case EVENT_STAMODE_AUTHMODE_CHANGE:
// https://github.com/esp8266/Arduino/blob/d5eb265f78bff9deb7063d10030a02d021c8c66c/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp#L241
{
auto& src = event->event_info.auth_change;
if ((src.old_mode != AUTH_OPEN) && (src.new_mode == AUTH_OPEN)) {
status = Status::DISCONNECTED;
disconnectReason = DisconnectReason::OTHER;
wifi_station_disconnect();
}
}
break;
default:
@@ -80,8 +103,6 @@ void Connection::onEvent(WiFiEvent_t event, WiFiEventInfo_t info) {
default:
break;
}
//Serial.printf("SYS EVENT: %d, reason: %d\n\r", evt->event, disconnectReason);
}
#endif
@@ -125,5 +146,5 @@ Connection::DisconnectReason Connection::convertDisconnectReason(uint8_t reason)
}
bool Connection::useDhcp = false;
Connection::Status Connection::status = Status::DISCONNECTED;
Connection::Status Connection::status = Status::NONE;
Connection::DisconnectReason Connection::disconnectReason = DisconnectReason::NONE;

View File

@@ -0,0 +1,46 @@
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#include "lwip/etharp.h"
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#endif
namespace Network {
struct Connection {
enum class Status {
CONNECTED,
CONNECTING,
DISCONNECTED,
NONE
};
enum class DisconnectReason {
BEACON_TIMEOUT,
NO_AP_FOUND,
AUTH_FAIL,
ASSOC_FAIL,
HANDSHAKE_TIMEOUT,
DHCP_TIMEOUT,
OTHER,
NONE
};
static Status status;
static DisconnectReason disconnectReason;
static void setup(bool useDhcp);
static void setUseDhcp(bool value);
static void reset();
static Status getStatus();
static DisconnectReason getDisconnectReason();
#if defined(ARDUINO_ARCH_ESP8266)
static void onEvent(System_Event_t *evt);
#elif defined(ARDUINO_ARCH_ESP32)
static void onEvent(WiFiEvent_t event, WiFiEventInfo_t info);
#endif
protected:
static DisconnectReason convertDisconnectReason(uint8_t reason);
static bool useDhcp;
};
}

View File

@@ -0,0 +1,417 @@
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#include "lwip/etharp.h"
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#endif
#include <NetworkConnection.h>
namespace Network {
class Manager {
public:
typedef std::function<void()> YieldCallback;
typedef std::function<void(unsigned int)> DelayCallback;
Manager() {
Connection::setup(this->useDhcp);
this->resetWifi();
}
Manager* setYieldCallback(YieldCallback callback = nullptr) {
this->yieldCallback = callback;
return this;
}
Manager* setDelayCallback(DelayCallback callback = nullptr) {
this->delayCallback = callback;
return this;
}
Manager* setHostname(const char* value) {
this->hostname = value;
return this;
}
Manager* setApCredentials(const char* ssid, const char* password = nullptr, byte channel = 0) {
this->apName = ssid;
this->apPassword = password;
this->apChannel = channel;
return this;
}
Manager* setStaCredentials(const char* ssid = nullptr, const char* password = nullptr, byte channel = 0) {
this->staSsid = ssid;
this->staPassword = password;
this->staChannel = channel;
return this;
}
Manager* setUseDhcp(bool value) {
this->useDhcp = value;
Connection::setup(this->useDhcp);
return this;
}
Manager* setStaticConfig(const char* ip, const char* gateway, const char* subnet, const char* dns) {
this->staticIp.fromString(ip);
this->staticGateway.fromString(gateway);
this->staticSubnet.fromString(subnet);
this->staticDns.fromString(dns);
return this;
}
Manager* setStaticConfig(IPAddress &ip, IPAddress &gateway, IPAddress &subnet, IPAddress &dns) {
this->staticIp = ip;
this->staticGateway = gateway;
this->staticSubnet = subnet;
this->staticDns = dns;
return this;
}
bool hasStaCredentials() {
return this->staSsid != nullptr;
}
bool isConnected() {
return this->isStaEnabled() && Connection::getStatus() == Connection::Status::CONNECTED;
}
bool isConnecting() {
return this->isStaEnabled() && Connection::getStatus() == Connection::Status::CONNECTING;
}
bool isStaEnabled() {
return (WiFi.getMode() & WIFI_STA) != 0;
}
bool isApEnabled() {
return (WiFi.getMode() & WIFI_AP) != 0;
}
bool hasApClients() {
if (!this->isApEnabled()) {
return false;
}
return WiFi.softAPgetStationNum() > 0;
}
short int getRssi() {
return WiFi.RSSI();
}
IPAddress getApIp() {
return WiFi.softAPIP();
}
IPAddress getStaIp() {
return WiFi.localIP();
}
IPAddress getStaSubnet() {
return WiFi.subnetMask();
}
IPAddress getStaGateway() {
return WiFi.gatewayIP();
}
IPAddress getStaDns() {
return WiFi.dnsIP();
}
String getStaMac() {
return WiFi.macAddress();
}
const char* getStaSsid() {
return this->staSsid;
}
const char* getStaPassword() {
return this->staPassword;
}
byte getStaChannel() {
return this->staChannel;
}
bool resetWifi() {
WiFi.persistent(false);
WiFi.setAutoConnect(false);
WiFi.setAutoReconnect(false);
#ifdef ARDUINO_ARCH_ESP8266
WiFi.setSleepMode(WIFI_NONE_SLEEP);
/*if (wifi_softap_dhcps_status() == DHCP_STARTED) {
wifi_softap_dhcps_stop();
}*/
#elif defined(ARDUINO_ARCH_ESP32)
WiFi.setSleep(WIFI_PS_NONE);
#endif
WiFi.softAPdisconnect();
/*#ifdef ARDUINO_ARCH_ESP8266
if (wifi_station_dhcpc_status() == DHCP_STARTED) {
wifi_station_dhcpc_stop();
}
#endif*/
WiFi.disconnect(false, true);
return WiFi.mode(WIFI_OFF);
}
void reconnect() {
this->reconnectFlag = true;
}
bool connect(bool force = false, unsigned int timeout = 1000u) {
if (this->isConnected() && !force) {
return true;
}
if (force && !this->isApEnabled()) {
this->resetWifi();
} else {
/*#ifdef ARDUINO_ARCH_ESP8266
if (wifi_station_dhcpc_status() == DHCP_STARTED) {
wifi_station_dhcpc_stop();
}
#endif*/
WiFi.disconnect(false, true);
}
if (!this->hasStaCredentials()) {
return false;
}
this->delayCallback(200);
#ifdef ARDUINO_ARCH_ESP32
if (this->setWifiHostname(this->hostname)) {
Log.straceln(FPSTR(L_NETWORK), F("Set hostname '%s': success"), this->hostname);
} else {
Log.serrorln(FPSTR(L_NETWORK), F("Set hostname '%s': fail"), this->hostname);
}
#endif
if (!WiFi.mode((WiFiMode_t)(WiFi.getMode() | WIFI_STA))) {
return false;
}
this->delayCallback(200);
#ifdef ARDUINO_ARCH_ESP8266
if (this->setWifiHostname(this->hostname)) {
Log.straceln(FPSTR(L_NETWORK), F("Set hostname '%s': success"), this->hostname);
} else {
Log.serrorln(FPSTR(L_NETWORK), F("Set hostname '%s': fail"), this->hostname);
}
this->delayCallback(200);
#endif
if (!this->useDhcp) {
WiFi.config(this->staticIp, this->staticGateway, this->staticSubnet, this->staticDns);
}
WiFi.begin(this->staSsid, this->staPassword, this->staChannel);
unsigned long beginConnectionTime = millis();
while (millis() - beginConnectionTime < timeout) {
this->delayCallback(100);
Connection::Status status = Connection::getStatus();
if (status != Connection::Status::CONNECTING && status != Connection::Status::NONE) {
return status == Connection::Status::CONNECTED;
}
}
return false;
}
void loop() {
if (this->isConnected() && !this->hasStaCredentials()) {
Log.sinfoln(FPSTR(L_NETWORK), F("Reset"));
this->resetWifi();
} else if (this->isConnected() && !this->reconnectFlag) {
if (!this->connected) {
this->connectedTime = millis();
this->connected = true;
Log.sinfoln(
FPSTR(L_NETWORK),
F("Connected, downtime: %lu s., IP: %s, RSSI: %hhd"),
(millis() - this->disconnectedTime) / 1000,
WiFi.localIP().toString().c_str(),
WiFi.RSSI()
);
}
if (this->isApEnabled() && millis() - this->connectedTime > this->reconnectInterval && !this->hasApClients()) {
Log.sinfoln(FPSTR(L_NETWORK), F("Stop AP because connected, start only STA"));
WiFi.mode(WIFI_STA);
return;
}
#ifdef ARDUINO_ARCH_ESP8266
if (millis() - this->prevArpGratuitous > 60000) {
this->stationKeepAliveNow();
this->prevArpGratuitous = millis();
}
#endif
} else {
if (this->connected) {
this->disconnectedTime = millis();
this->connected = false;
Log.sinfoln(
FPSTR(L_NETWORK),
F("Disconnected, reason: %d, uptime: %lu s."),
Connection::getDisconnectReason(),
(millis() - this->connectedTime) / 1000
);
}
if (!this->hasStaCredentials() && !this->isApEnabled()) {
Log.sinfoln(FPSTR(L_NETWORK), F("No STA credentials, start AP"));
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(this->apName, this->apPassword, this->apChannel);
} else if (!this->isApEnabled() && millis() - this->disconnectedTime > this->failedConnectTimeout) {
Log.sinfoln(FPSTR(L_NETWORK), F("Disconnected for a long time, start AP"));
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(this->apName, this->apPassword, this->apChannel);
} else if (this->isConnecting() && millis() - this->prevReconnectingTime > this->resetConnectionTimeout) {
Log.swarningln(FPSTR(L_NETWORK), F("Connection timeout, reset wifi..."));
this->resetWifi();
} else if (!this->isConnecting() && this->hasStaCredentials() && (!this->prevReconnectingTime || millis() - this->prevReconnectingTime > this->reconnectInterval)) {
Log.sinfoln(FPSTR(L_NETWORK), F("Try connect..."));
this->reconnectFlag = false;
Connection::reset();
if (!this->connect(true, this->connectionTimeout)) {
Log.straceln(FPSTR(L_NETWORK), F("Connection failed. Status: %d, reason: %d"), Connection::getStatus(), Connection::getDisconnectReason());
}
this->prevReconnectingTime = millis();
}
}
}
static byte rssiToSignalQuality(short int rssi) {
return constrain(map(rssi, -100, -50, 0, 100), 0, 100);
}
protected:
const unsigned int reconnectInterval = 5000;
const unsigned int failedConnectTimeout = 30000; // 120000
const unsigned int connectionTimeout = 15000;
const unsigned int resetConnectionTimeout = 60000;
YieldCallback yieldCallback = []() {
::yield();
};
DelayCallback delayCallback = [](unsigned int time) {
::delay(time);
};
const char* hostname = "esp";
const char* apName = "ESP";
const char* apPassword = nullptr;
byte apChannel = 1;
const char* staSsid = nullptr;
const char* staPassword = nullptr;
byte staChannel = 0;
bool useDhcp = true;
IPAddress staticIp;
IPAddress staticGateway;
IPAddress staticSubnet;
IPAddress staticDns;
bool connected = false;
bool reconnectFlag = false;
unsigned long prevArpGratuitous = 0;
unsigned long prevReconnectingTime = 0;
unsigned long connectedTime = 0;
unsigned long disconnectedTime = 0;
bool setWifiHostname(const char* hostname) {
if (!this->isHostnameValid(hostname)) {
return false;
}
if (strcmp(WiFi.getHostname(), hostname) == 0) {
return true;
}
return WiFi.setHostname(hostname);
}
#ifdef ARDUINO_ARCH_ESP8266
/**
* @brief
* https://github.com/arendst/Tasmota/blob/e6515883f0ee5451931b6280ff847b117de5a231/tasmota/tasmota_support/support_wifi.ino#L1196
*/
static void stationKeepAliveNow(void) {
for (netif* interface = netif_list; interface != nullptr; interface = interface->next) {
if (
(interface->flags & NETIF_FLAG_LINK_UP)
&& (interface->flags & NETIF_FLAG_UP)
&& interface->num == STATION_IF
&& (!ip4_addr_isany_val(*netif_ip4_addr(interface)))
) {
etharp_gratuitous(interface);
break;
}
}
}
#endif
/**
* @brief check RFC compliance
*
* @param value
* @return true
* @return false
*/
static bool isHostnameValid(const char* value) {
size_t len = strlen(value);
if (len > 24) {
return false;
} else if (value[len - 1] == '-') {
return false;
}
for (size_t i = 0; i < len; i++) {
if (!isalnum(value[i]) && value[i] != '-') {
return false;
}
}
return true;
}
};
}

View File

@@ -3,9 +3,9 @@
class DynamicPage : public RequestHandler {
public:
typedef std::function<bool(HTTPMethod, const String&)> canHandleFunction;
typedef std::function<bool()> beforeSendFunction;
typedef std::function<String(const char*)> templateFunction;
typedef std::function<bool(HTTPMethod, const String&)> CanHandleCallback;
typedef std::function<bool()> BeforeSendCallback;
typedef std::function<String(const char*)> TemplateCallback;
DynamicPage(const char* uri, FS* fs, const char* path, const char* cacheHeader = nullptr) {
this->uri = uri;
@@ -14,20 +14,20 @@ public:
this->cacheHeader = cacheHeader;
}
DynamicPage* setCanHandleFunction(canHandleFunction val = nullptr) {
this->canHandleFn = val;
DynamicPage* setCanHandleCallback(CanHandleCallback callback = nullptr) {
this->canHandleCallback = callback;
return this;
}
DynamicPage* setBeforeSendFunction(beforeSendFunction val = nullptr) {
this->beforeSendFn = val;
DynamicPage* setBeforeSendCallback(BeforeSendCallback callback = nullptr) {
this->beforeSendCallback = callback;
return this;
}
DynamicPage* setTemplateFunction(templateFunction val = nullptr) {
this->templateFn = val;
DynamicPage* setTemplateCallback(TemplateCallback callback = nullptr) {
this->templateCallback = callback;
return this;
}
@@ -37,7 +37,7 @@ public:
#else
bool canHandle(HTTPMethod method, const String& uri) override {
#endif
return uri.equals(this->uri) && (!this->canHandleFn || this->canHandleFn(method, uri));
return uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri));
}
#if defined(ARDUINO_ARCH_ESP32)
@@ -49,7 +49,7 @@ public:
return false;
}
if (this->beforeSendFn && !this->beforeSendFn()) {
if (this->beforeSendCallback && !this->beforeSendCallback()) {
return true;
}
@@ -98,7 +98,7 @@ public:
argName[fullSizeArgName] = '\0';
// send arg value
String argValue = this->templateFn((const char*) argName);
String argValue = this->templateCallback((const char*) argName);
if (argValue.length()) {
server.sendContent(argValue.c_str());
@@ -159,7 +159,7 @@ public:
argName[sizeArgName] = '\0';
// send arg value
String argValue = this->templateFn((const char*) argName);
String argValue = this->templateCallback((const char*) argName);
if (argValue.length()) {
// send content before var
if (argStartPos - buf > 0) {
@@ -217,9 +217,9 @@ public:
protected:
FS* fs = nullptr;
canHandleFunction canHandleFn;
beforeSendFunction beforeSendFn;
templateFunction templateFn;
CanHandleCallback canHandleCallback;
BeforeSendCallback beforeSendCallback;
TemplateCallback templateCallback;
String eTag;
const char* uri = nullptr;
const char* path = nullptr;

View File

@@ -2,8 +2,8 @@
class StaticPage : public RequestHandler {
public:
typedef std::function<bool(HTTPMethod, const String&)> canHandleFunction;
typedef std::function<bool()> beforeSendFunction;
typedef std::function<bool(HTTPMethod, const String&)> CanHandleCallback;
typedef std::function<bool()> BeforeSendCallback;
StaticPage(const char* uri, FS* fs, const char* path, const char* cacheHeader = nullptr) {
this->uri = uri;
@@ -12,14 +12,14 @@ public:
this->cacheHeader = cacheHeader;
}
StaticPage* setCanHandleFunction(canHandleFunction val = nullptr) {
this->canHandleFn = val;
StaticPage* setCanHandleCallback(CanHandleCallback callback = nullptr) {
this->canHandleCallback = callback;
return this;
}
StaticPage* setBeforeSendFunction(beforeSendFunction val = nullptr) {
this->beforeSendFn = val;
StaticPage* setBeforeSendCallback(BeforeSendCallback callback = nullptr) {
this->beforeSendCallback = callback;
return this;
}
@@ -29,7 +29,7 @@ public:
#else
bool canHandle(HTTPMethod method, const String& uri) override {
#endif
return method == HTTP_GET && uri.equals(this->uri) && (!this->canHandleFn || this->canHandleFn(method, uri));
return method == HTTP_GET && uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri));
}
#if defined(ARDUINO_ARCH_ESP32)
@@ -41,7 +41,7 @@ public:
return false;
}
if (this->beforeSendFn && !this->beforeSendFn()) {
if (this->beforeSendCallback && !this->beforeSendCallback()) {
return true;
}
@@ -87,8 +87,8 @@ public:
protected:
FS* fs = nullptr;
canHandleFunction canHandleFn;
beforeSendFunction beforeSendFn;
CanHandleCallback canHandleCallback;
BeforeSendCallback beforeSendCallback;
String eTag;
const char* uri = nullptr;
const char* path = nullptr;

View File

@@ -24,35 +24,35 @@ public:
String error;
} UpgradeResult;
typedef std::function<bool(HTTPMethod, const String&)> CanHandleFunction;
typedef std::function<bool(const String&)> CanUploadFunction;
typedef std::function<bool(UpgradeType)> BeforeUpgradeFunction;
typedef std::function<void(const UpgradeResult&, const UpgradeResult&)> AfterUpgradeFunction;
typedef std::function<bool(HTTPMethod, const String&)> CanHandleCallback;
typedef std::function<bool(const String&)> CanUploadCallback;
typedef std::function<bool(UpgradeType)> BeforeUpgradeCallback;
typedef std::function<void(const UpgradeResult&, const UpgradeResult&)> AfterUpgradeCallback;
UpgradeHandler(const char* uri) {
this->uri = uri;
}
UpgradeHandler* setCanHandleFunction(CanHandleFunction val = nullptr) {
this->canHandleFn = val;
UpgradeHandler* setCanHandleCallback(CanHandleCallback callback = nullptr) {
this->canHandleCallback = callback;
return this;
}
UpgradeHandler* setCanUploadFunction(CanUploadFunction val = nullptr) {
this->canUploadFn = val;
UpgradeHandler* setCanUploadCallback(CanUploadCallback callback = nullptr) {
this->canUploadCallback = callback;
return this;
}
UpgradeHandler* setBeforeUpgradeFunction(BeforeUpgradeFunction val = nullptr) {
this->beforeUpgradeFn = val;
UpgradeHandler* setBeforeUpgradeCallback(BeforeUpgradeCallback callback = nullptr) {
this->beforeUpgradeCallback = callback;
return this;
}
UpgradeHandler* setAfterUpgradeFunction(AfterUpgradeFunction val = nullptr) {
this->afterUpgradeFn = val;
UpgradeHandler* setAfterUpgradeCallback(AfterUpgradeCallback callback = nullptr) {
this->afterUpgradeCallback = callback;
return this;
}
@@ -62,7 +62,7 @@ public:
#else
bool canHandle(HTTPMethod method, const String& uri) override {
#endif
return method == HTTP_POST && uri.equals(this->uri) && (!this->canHandleFn || this->canHandleFn(method, uri));
return method == HTTP_POST && uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri));
}
#if defined(ARDUINO_ARCH_ESP32)
@@ -70,7 +70,7 @@ public:
#else
bool canUpload(const String& uri) override {
#endif
return uri.equals(this->uri) && (!this->canUploadFn || this->canUploadFn(uri));
return uri.equals(this->uri) && (!this->canUploadCallback || this->canUploadCallback(uri));
}
#if defined(ARDUINO_ARCH_ESP32)
@@ -78,8 +78,8 @@ public:
#else
bool handle(WebServer& server, HTTPMethod method, const String& uri) override {
#endif
if (this->afterUpgradeFn) {
this->afterUpgradeFn(this->firmwareResult, this->filesystemResult);
if (this->afterUpgradeCallback) {
this->afterUpgradeCallback(this->firmwareResult, this->filesystemResult);
}
this->firmwareResult.status = UpgradeStatus::NONE;
@@ -109,7 +109,7 @@ public:
return;
}
if (this->beforeUpgradeFn && !this->beforeUpgradeFn(result->type)) {
if (this->beforeUpgradeCallback && !this->beforeUpgradeCallback(result->type)) {
result->status = UpgradeStatus::PROHIBITED;
return;
}
@@ -207,10 +207,10 @@ public:
}
protected:
CanHandleFunction canHandleFn;
CanUploadFunction canUploadFn;
BeforeUpgradeFunction beforeUpgradeFn;
AfterUpgradeFunction afterUpgradeFn;
CanHandleCallback canHandleCallback;
CanUploadCallback canUploadCallback;
BeforeUpgradeCallback beforeUpgradeCallback;
AfterUpgradeCallback afterUpgradeCallback;
const char* uri = nullptr;
UpgradeResult firmwareResult{UpgradeType::FIRMWARE, UpgradeStatus::NONE};